Restore integration tests in CI

This commit is contained in:
Matthieu 2021-02-17 22:55:31 +01:00
parent 7b7117b359
commit 8b90e17fc4
26 changed files with 989 additions and 1031 deletions

View File

@ -1,8 +1,8 @@
image: reactivecircus/android-emulator-26:latest
image: reactivecircus/android-emulator-23:latest
variables:
API_LEVEL: "26"
API_LEVEL: "23"
ARCH: "x86"
TARGET: "default"
@ -34,25 +34,24 @@ debugTests:
- ./gradlew -Pci --console=plain :app:testDebug
#emulatorTest:
# interruptible: true
# stage: test
# script:
# - sdkmanager --sdk_root=${ANDROID_HOME} "system-images;android-${API_LEVEL};${TARGET};${ARCH}"
# - echo no | avdmanager create avd --force --name "api-${API_LEVEL}" --abi "${TARGET}/${ARCH}" --package "system-images;android-${API_LEVEL};${TARGET};${ARCH}"
# - $ANDROID_HOME/emulator/emulator -avd "api-${API_LEVEL}" -no-window -gpu swiftshader_indirect -no-snapshot -noaudio -no-boot-anim -camera-back none &
# - chmod +x android-wait-for-emulator.sh
# - ./gradlew build
# - ./android-wait-for-emulator.sh
# - adb shell settings put global window_animation_scale 0.0
# - adb shell settings put global transition_animation_scale 0.0
# - adb shell settings put global animator_duration_scale 0.0
emulatorTest:
interruptible: true
stage: test
script:
- echo no | avdmanager create avd --force --name "api-${API_LEVEL}" --abi "${TARGET}/${ARCH}" --package "system-images;android-${API_LEVEL};${TARGET};${ARCH}"
- $ANDROID_SDK_ROOT/emulator/emulator -avd "api-${API_LEVEL}" -no-window -gpu swiftshader_indirect -no-snapshot -noaudio -no-boot-anim -camera-back none &
- chmod +x android-wait-for-emulator.sh
- ./gradlew build
- ./android-wait-for-emulator.sh
- adb shell settings put global window_animation_scale 0.0
- adb shell settings put global transition_animation_scale 0.0
- adb shell settings put global animator_duration_scale 0.0
# - ./gradlew build connectedCheck connectedDebugAndroidTest jacocoTestReport
- ./gradlew build connectedCheck connectedStagingAndroidTest jacocoTestReport
# - cat app/build/reports/jacoco/jacocoTestReport/html/index.html | grep -o 'Total[^%]*%'
- cat app/build/reports/jacoco/jacocoTestReport/html/index.html | grep -o 'Total[^%]*%'
# artifacts:
# paths:
# - ./app/build/reports/jacoco/jacocoTestReport/
# expire_in: 1 week
artifacts:
paths:
- ./app/build/reports/jacoco/jacocoTestReport/
expire_in: 1 week

View File

@ -38,17 +38,39 @@ android {
test.java.srcDirs += 'src/test/java'
androidTest.java.srcDirs += 'src/androidTest/java'
}
testBuildType "staging"
buildTypes {
debug {
}
staging {
initWith debug
testCoverageEnabled true
// These values are first looked for in the env variables, and, if not found there,
// in the local.properties file (which is not checked into version control of course!).
// If you are not running the integration tests, you can just set them to dummy values
// in local.properties or comment the buildConfigField lines
def localProperties = new Properties()
if (rootProject.file("local.properties").exists()) {
localProperties.load(new FileInputStream(rootProject.file("local.properties")))
}
buildConfigField "String", "USER_ID", System.getenv("USER_ID") ?: localProperties['USER_ID']
buildConfigField "String", "INSTANCE_URI", System.getenv("INSTANCE_URI") ?: localProperties['INSTANCE_URI']
buildConfigField "String", "ACCESS_TOKEN", System.getenv("ACCESS_TOKEN") ?: localProperties['ACCESS_TOKEN']
buildConfigField "String", "REFRESH_TOKEN", System.getenv("REFRESH_TOKEN") ?: localProperties['REFRESH_TOKEN']
buildConfigField "String", "CLIENT_ID", System.getenv("CLIENT_ID") ?: localProperties['CLIENT_ID']
buildConfigField "String", "CLIENT_SECRET", System.getenv("CLIENT_SECRET") ?: localProperties['CLIENT_SECRET']
}
release {
minifyEnabled true
shrinkResources true
useProguard true
proguardFiles 'proguard-rules.pro'
}
}
@ -110,7 +132,7 @@ dependencies {
*/
implementation 'com.google.android.material:material:1.2.1'
implementation 'com.google.android.material:material:1.3.0'
//Dagger (dependency injection)
implementation 'com.google.dagger:dagger-android:2.30.1'
@ -167,7 +189,8 @@ dependencies {
*/
// debugImplementation required vs testImplementation: https://issuetracker.google.com/issues/128612536
debugImplementation("androidx.fragment:fragment-testing:1.2.5") {
//noinspection FragmentGradleConfiguration
stagingImplementation("androidx.fragment:fragment-testing:1.3.0") {
exclude group:'androidx.test', module:'monitor'
}
@ -196,7 +219,7 @@ tasks.withType(Test) {
}
task jacocoTestReport(type: JacocoReport, dependsOn: ['connectedDebugAndroidTest', 'testDebugUnitTest', 'createDebugCoverageReport']) {
task jacocoTestReport(type: JacocoReport, dependsOn: ['connectedStagingAndroidTest', 'testStagingUnitTest', 'createStagingCoverageReport']) {
reports {
xml.enabled = true
@ -210,9 +233,9 @@ task jacocoTestReport(type: JacocoReport, dependsOn: ['connectedDebugAndroidTest
getClassDirectories().from(files([kotlinDebugTree]))
getExecutionData().from(fileTree(dir: project.buildDir, includes: [
'outputs/code_coverage/debugAndroidTest/connected/*coverage.ec',
'outputs/code_coverage/stagingAndroidTest/connected/*coverage.ec',
'jacoco/testDebugUnitTest.exec'
'jacoco/testStagingUnitTest.exec'
]))
}

View File

@ -765,3 +765,10 @@
license: The Apache Software License, Version 2.0
licenseUrl: http://www.apache.org/licenses/LICENSE-2.0.txt
url: https://github.com/ongakuer/CircleIndicator
- artifact: androidx.dynamicanimation:dynamicanimation:+
name: dynamicanimation
copyrightHolder: Google Inc
license: The Apache Software License, Version 2.0
licenseUrl: http://www.apache.org/licenses/LICENSE-2.0.txt
url: http://developer.android.com/tools/extras/support-library.html

View File

@ -93,9 +93,6 @@ class CameraTest {
Thread.sleep(1000)
Intents.intended(expectedIntent)
}
@Test
@ -105,6 +102,9 @@ class CameraTest {
fragment.view?.findViewById<ImageButton>(R.id.camera_switch_button)?.performClick()
}
Thread.sleep(1000)
//FIXME this assert doesn't actually do anything...
// All this test really does is make sure it doesn't crash
scenario.onFragment { fragment ->
assert(!fragment.isHidden)
}

View File

@ -12,12 +12,8 @@ import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry.getInstrumentation
import androidx.test.uiautomator.UiDevice
import com.h.pixeldroid.testUtility.*
import com.h.pixeldroid.utils.db.AppDatabase
import com.h.pixeldroid.utils.db.entities.InstanceDatabaseEntity
import com.h.pixeldroid.utils.db.entities.UserDatabaseEntity
import com.h.pixeldroid.testUtility.MockServer
import com.h.pixeldroid.testUtility.clearData
import com.h.pixeldroid.testUtility.initDB
import org.junit.After
import org.junit.Before
import org.junit.Rule
@ -28,7 +24,6 @@ import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class DrawerMenuTest {
private lateinit var mockServer: MockServer
private lateinit var db: AppDatabase
private lateinit var context: Context
@ -38,33 +33,15 @@ class DrawerMenuTest {
@Before
fun before(){
mockServer = MockServer()
mockServer.start()
val baseUrl = mockServer.getUrl()
context = ApplicationProvider.getApplicationContext()
db = initDB(context)
db.clearAllTables()
db.instanceDao().insertInstance(
InstanceDatabaseEntity(
uri = baseUrl.toString(),
title = "PixelTest"
)
testiTestoInstance
)
db.userDao().insertUser(
UserDatabaseEntity(
user_id = "123",
instance_uri = baseUrl.toString(),
username = "Testi",
display_name = "Testi Testo",
avatar_static = "some_avatar_url",
isActive = true,
accessToken = "token",
refreshToken = "refreshToken",
clientId = "clientId",
clientSecret = "clientSecret"
)
testiTesto
)
db.close()
@ -78,7 +55,6 @@ class DrawerMenuTest {
@After
fun after() {
clearData()
mockServer.stop()
}
@Test
@ -132,9 +108,11 @@ class DrawerMenuTest {
onView(withText(R.string.menu_account)).perform(click())
// Check that profile activity was opened.
onView(withId(R.id.editButton)).check(matches(isDisplayed()))
val followersText = context.resources.getQuantityString(R.plurals.nb_followers, 68)
val followersText = context.resources.getQuantityString(R.plurals.nb_followers, 2, 2)
onView(withText(followersText)).perform(click())
onView(withText("Dobios")).check(matches(isDisplayed()))
waitForView(R.id.account_entry_avatar)
onView(withText("PixelDroid Developer")).check(matches(isDisplayed()))
}
@Test
@ -143,9 +121,11 @@ class DrawerMenuTest {
onView(withText(R.string.menu_account)).perform(click())
// Check that profile activity was opened.
onView(withId(R.id.editButton)).check(matches(isDisplayed()))
val followingText = context.resources.getQuantityString(R.plurals.nb_followers, 27)
val followingText = context.resources.getQuantityString(R.plurals.nb_following, 3, 3)
onView(withText(followingText)).perform(click())
onView(withText("Dobios")).check(matches(isDisplayed()))
waitForView(R.id.account_entry_avatar)
onView(withText("@User 1")).check(matches(isDisplayed()))
}
/*@Test
@ -160,31 +140,38 @@ class DrawerMenuTest {
fun clickFollowers() {
// Open My Profile from drawer
onView(withText(R.string.menu_account)).perform(click())
Thread.sleep(1000)
waitForView(R.id.nbFollowersTextView)
// Open followers list
onView(withId(R.id.nbFollowersTextView)).perform(click())
Thread.sleep(1000)
// Open follower's profile
onView(withText("ete2")).perform(click())
Thread.sleep(1000)
onView(withId(R.id.accountNameTextView)).check(matches(withText("Christian")))
waitForView(R.id.account_entry_avatar)
// Open follower's profile
onView(withText("@pixeldroid")).perform(click())
waitForView(R.id.profilePictureImageView)
onView(withId(R.id.accountNameTextView)).check(matches(withText("PixelDroid Developer")))
}
@Test
fun clickFollowing() {
// Open My Profile from drawer
onView(withText(R.string.menu_account)).perform(click())
Thread.sleep(1000)
waitForView(R.id.nbFollowersTextView)
// Open followers list
onView(withId(R.id.nbFollowingTextView)).perform(click())
Thread.sleep(1000)
// Open following's profile
onView(withText("Dobios")).perform(click())
Thread.sleep(1000)
onView(withId(R.id.accountNameTextView)).check(matches(withText("Andrew Dobis")))
waitForView(R.id.account_entry_avatar)
// Open following's profile
onView(withText("@user2")).perform(click())
waitForView(R.id.profilePictureImageView)
onView(withId(R.id.accountNameTextView)).check(matches(withText("User 2")))
}
@Test

View File

@ -25,8 +25,10 @@ import com.google.android.material.tabs.TabLayout
import com.h.pixeldroid.postCreation.photoEdit.PhotoEditActivity
import com.h.pixeldroid.postCreation.photoEdit.ThumbnailAdapter
import com.h.pixeldroid.settings.AboutActivity
import com.h.pixeldroid.testUtility.CustomMatchers
import com.h.pixeldroid.testUtility.clearData
import com.h.pixeldroid.testUtility.clickChildViewWithId
import com.h.pixeldroid.testUtility.slowSwipeLeft
import com.h.pixeldroid.testUtility.waitForView
import org.hamcrest.CoreMatchers.allOf
import org.junit.*
import org.junit.Assert.assertTrue
@ -72,7 +74,7 @@ class EditPhotoTest {
activityScenario = ActivityScenario.launch<PhotoEditActivity>(intent).onActivity{a -> activity = a}
Thread.sleep(1000)
waitForView(R.id.coordinator_edit)
}
@After
@ -119,14 +121,15 @@ class EditPhotoTest {
@Test
fun FiltersIsSwipeableAndClickeable() {
waitForView(R.id.thumbnail)
Espresso.onView(withId(R.id.recycler_view))
.perform(actionOnItemAtPosition<ThumbnailAdapter.MyViewHolder>(1, CustomMatchers.clickChildViewWithId(R.id.thumbnail)))
.perform(actionOnItemAtPosition<ThumbnailAdapter.MyViewHolder>(1, clickChildViewWithId(R.id.thumbnail)))
Thread.sleep(1000)
Espresso.onView(withId(R.id.recycler_view))
.perform(actionOnItemAtPosition<ThumbnailAdapter.MyViewHolder>(1, CustomMatchers.slowSwipeLeft(false)))
.perform(actionOnItemAtPosition<ThumbnailAdapter.MyViewHolder>(1, slowSwipeLeft(false)))
Thread.sleep(1000)
Espresso.onView(withId(R.id.recycler_view))
.perform(actionOnItemAtPosition<ThumbnailAdapter.MyViewHolder>(5, CustomMatchers.clickChildViewWithId(R.id.thumbnail)))
.perform(actionOnItemAtPosition<ThumbnailAdapter.MyViewHolder>(5, clickChildViewWithId(R.id.thumbnail)))
Espresso.onView(withId(R.id.image_preview)).check(matches(isDisplayed()))
}
@ -134,7 +137,7 @@ class EditPhotoTest {
fun BrightnessSaturationContrastTest() {
Espresso.onView(withId(R.id.tabs)).perform(selectTabAtPosition(1))
Thread.sleep(1000)
waitForView(R.id.seekbar_brightness)
var change = 5
Espresso.onView(withId(R.id.seekbar_brightness)).perform(setProgress(change))
@ -159,21 +162,25 @@ class EditPhotoTest {
@Test
fun saveButton() {
// The save button saves the edits and goes back to the post creation activity.
Espresso.onView(withId(R.id.action_save)).perform(click())
Espresso.onView(withId(com.google.android.material.R.id.snackbar_text))
.check(matches(withText(R.string.save_image_success)))
Thread.sleep(1000)
assertTrue(activityScenario.state == Lifecycle.State.DESTROYED)
}
@Test
fun backButton() {
Espresso.onView(withContentDescription(R.string.abc_action_bar_up_description)).perform(click())
Thread.sleep(1000)
assertTrue(activityScenario.state == Lifecycle.State.DESTROYED)
}
@Test
fun croppingIsPossible() {
Espresso.onView(withId(R.id.cropImageButton)).perform(click())
Thread.sleep(1000)
waitForView(R.id.menu_crop)
Espresso.onView(withId(R.id.menu_crop)).perform(click())
Espresso.onView(withId(R.id.image_preview)).check(matches(isDisplayed()))
}

View File

@ -12,19 +12,8 @@ import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.google.android.material.tabs.TabLayout
import com.h.pixeldroid.utils.db.AppDatabase
import com.h.pixeldroid.utils.db.entities.InstanceDatabaseEntity
import com.h.pixeldroid.utils.db.entities.UserDatabaseEntity
import com.h.pixeldroid.posts.StatusViewHolder
import com.h.pixeldroid.testUtility.CustomMatchers.Companion.atPosition
import com.h.pixeldroid.testUtility.CustomMatchers.Companion.clickChildViewWithId
import com.h.pixeldroid.testUtility.CustomMatchers.Companion.first
import com.h.pixeldroid.testUtility.CustomMatchers.Companion.getText
import com.h.pixeldroid.testUtility.CustomMatchers.Companion.second
import com.h.pixeldroid.testUtility.CustomMatchers.Companion.slowSwipeUp
import com.h.pixeldroid.testUtility.CustomMatchers.Companion.typeTextInViewWithId
import com.h.pixeldroid.testUtility.MockServer
import com.h.pixeldroid.testUtility.clearData
import com.h.pixeldroid.testUtility.initDB
import com.h.pixeldroid.testUtility.*
import org.hamcrest.CoreMatchers.not
import org.junit.After
import org.junit.Before
@ -37,7 +26,6 @@ import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class HomeFeedTest {
private lateinit var mockServer: MockServer
private lateinit var activityScenario: ActivityScenario<MainActivity>
private lateinit var db: AppDatabase
private lateinit var context: Context
@ -47,31 +35,14 @@ class HomeFeedTest {
@Before
fun before(){
mockServer = MockServer()
mockServer.start()
val baseUrl = mockServer.getUrl()
context = ApplicationProvider.getApplicationContext()
db = initDB(context)
db.clearAllTables()
db.instanceDao().insertInstance(
InstanceDatabaseEntity(
uri = baseUrl.toString(),
title = "PixelTest"
)
testiTestoInstance
)
db.userDao().insertUser(
UserDatabaseEntity(
user_id = "123",
instance_uri = baseUrl.toString(),
username = "Testi",
display_name = "Testi Testo",
avatar_static = "some_avatar_url",
isActive = true,
accessToken = "token",
refreshToken = "refreshToken",
clientId = "clientId",
clientSecret = "clientSecret"
)
testiTesto
)
db.close()
activityScenario = ActivityScenario.launch(MainActivity::class.java)
@ -79,13 +50,12 @@ class HomeFeedTest {
@After
fun after() {
clearData()
mockServer.stop()
}
@Test
fun clickingTabOnAlbumShowsNextPhoto() {
//Wait for the feed to load
Thread.sleep(1000)
waitForView(R.id.postTabs)
activityScenario.onActivity {
a -> run {
@ -95,6 +65,45 @@ class HomeFeedTest {
}
onView(first(withId(R.id.postTabs))).check(matches(isDisplayed()))
}
/*
@Test
fun clickingReblogButtonWorks() {
onView(withId(R.id.list))
.perform(actionOnItemAtPosition<StatusViewHolder>
(0, clickChildViewWithId(R.id.reblogger)))
onView(withId(R.id.list))
.perform(actionOnItemAtPosition<StatusViewHolder>
(0, clickChildViewWithId(R.id.reblogger)))
onView(first(withId(R.id.nshares)))
.check(matches(withText(getText(first(withId(R.id.nshares))))))
}
@Test
fun doubleTapLikerWorks() {
Thread.sleep(1000)
//Get initial like count
val likes = getText(first(withId(R.id.nlikes)))
val nLikes = likes!!.split(" ")[0].toInt()
//Remove sensitive media warning
onView(withId(R.id.list))
.perform(actionOnItemAtPosition<StatusViewHolder>
(0, clickChildViewWithId(R.id.sensitiveWarning)))
Thread.sleep(100)
//Like the post
onView(withId(R.id.list))
.perform(actionOnItemAtPosition<StatusViewHolder>
(0, clickChildViewWithId(R.id.postPicture)))
onView(withId(R.id.list))
.perform(actionOnItemAtPosition<StatusViewHolder >
(0, clickChildViewWithId(R.id.postPicture)))
//...
Thread.sleep(100)
//Profit
onView(first(withId(R.id.nlikes))).check(matches((withText("${nLikes + 1} Likes"))))
}
@Test
fun clickingLikeButtonWorks() {
@ -114,10 +123,12 @@ class HomeFeedTest {
actionOnItemAtPosition<StatusViewHolder>(2, clickChildViewWithId(R.id.liker))
)
onView((withId(R.id.list))).check(matches(isDisplayed()))
}
}*/
@Test
fun clickingUsernameOpensProfile() {
waitForView(R.id.username)
onView(withId(R.id.list)).perform(
actionOnItemAtPosition<StatusViewHolder>(0, clickChildViewWithId(R.id.username))
)
@ -126,26 +137,18 @@ class HomeFeedTest {
@Test
fun clickingProfilePicOpensProfile() {
waitForView(R.id.profilePic)
onView(withId(R.id.list)).perform(
actionOnItemAtPosition<StatusViewHolder>(0, clickChildViewWithId(R.id.profilePic))
)
onView(withId(R.id.accountNameTextView)).check(matches(isDisplayed()))
}
@Test
fun clickingReblogButtonWorks() {
onView(withId(R.id.list))
.perform(actionOnItemAtPosition<StatusViewHolder>
(0, clickChildViewWithId(R.id.reblogger)))
onView(withId(R.id.list))
.perform(actionOnItemAtPosition<StatusViewHolder>
(0, clickChildViewWithId(R.id.reblogger)))
onView(first(withId(R.id.nshares)))
.check(matches(withText(getText(first(withId(R.id.nshares))))))
}
@Test
fun clickingMentionOpensProfile() {
waitForView(R.id.description)
onView(withId(R.id.list)).perform(
actionOnItemAtPosition<StatusViewHolder>(0, clickChildViewWithId(R.id.description))
)
@ -159,7 +162,7 @@ class HomeFeedTest {
)
onView(withId(R.id.list)).check(matches(isDisplayed()))
}
*/
@Test
fun clickingCommentButtonOpensCommentSection() {
@ -211,20 +214,19 @@ class HomeFeedTest {
Thread.sleep(1000)
onView(first(withId(R.id.commentContainer)))
.check(matches(hasDescendant(withId(R.id.comment))))
}
}*/
@Test
fun performClickOnSensitiveWarning() {
waitForView(R.id.username)
onView(withId(R.id.list)).perform(scrollToPosition<StatusViewHolder>(1))
Thread.sleep(1000)
onView(second(withId(R.id.sensitiveWarning))).check(matches(withEffectiveVisibility(Visibility.VISIBLE)))
Thread.sleep(1000)
onView(withId(R.id.list))
.perform(actionOnItemAtPosition<StatusViewHolder>
(1, clickChildViewWithId(R.id.sensitiveWarning)))
Thread.sleep(1000)
onView(withId(R.id.list))
.check(matches(atPosition(1, not(withId(R.id.sensitiveWarning)))))
@ -232,45 +234,19 @@ class HomeFeedTest {
@Test
fun performClickOnSensitiveWarningTabs() {
waitForView(R.id.username)
onView(withId(R.id.list)).perform(scrollToPosition<StatusViewHolder>(0))
Thread.sleep(1000)
onView(first(withId(R.id.sensitiveWarning))).check(matches(withEffectiveVisibility(Visibility.VISIBLE)))
Thread.sleep(1000)
onView(withId(R.id.list))
.perform(actionOnItemAtPosition<StatusViewHolder>
(0, clickChildViewWithId(R.id.sensitiveWarning)))
Thread.sleep(1000)
onView(first(withId(R.id.sensitiveWarning))).check(matches(withEffectiveVisibility(Visibility.GONE)))
}
@Test
fun doubleTapLikerWorks() {
//Get initial like count
val likes = getText(first(withId(R.id.nlikes)))
val nlikes = likes!!.split(" ")[0].toInt()
//Remove sensitive media warning
onView(withId(R.id.list))
.perform(actionOnItemAtPosition<StatusViewHolder>
(0, clickChildViewWithId(R.id.sensitiveWarning)))
Thread.sleep(100)
//Like the post
onView(withId(R.id.list))
.perform(actionOnItemAtPosition<StatusViewHolder>
(0, clickChildViewWithId(R.id.postPicture)))
onView(withId(R.id.list))
.perform(actionOnItemAtPosition<StatusViewHolder >
(0, clickChildViewWithId(R.id.postPicture)))
//...
Thread.sleep(100)
//Profit
onView(first(withId(R.id.nlikes))).check(matches((withText("${nlikes + 1} Likes"))))
}
/*
@Test
fun goOfflineShowsPosts() {

View File

@ -30,9 +30,7 @@ import com.h.pixeldroid.posts.StatusViewHolder
import com.h.pixeldroid.utils.api.objects.Account
import com.h.pixeldroid.utils.api.objects.Account.Companion.ACCOUNT_TAG
import com.h.pixeldroid.settings.AboutActivity
import com.h.pixeldroid.testUtility.MockServer
import com.h.pixeldroid.testUtility.clearData
import com.h.pixeldroid.testUtility.initDB
import com.h.pixeldroid.testUtility.*
import org.hamcrest.CoreMatchers
import org.hamcrest.Matcher
import org.hamcrest.Matchers
@ -47,7 +45,6 @@ import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class IntentTest {
private lateinit var mockServer: MockServer
private lateinit var db: AppDatabase
private lateinit var context: Context
@ -62,34 +59,14 @@ class IntentTest {
@Before
fun before() {
mockServer = MockServer()
mockServer.start()
val baseUrl = mockServer.getUrl()
context = ApplicationProvider.getApplicationContext()
db = initDB(context)
db.clearAllTables()
db.instanceDao().insertInstance(
InstanceDatabaseEntity(
uri = baseUrl.toString(),
title = "PixelTest"
)
testiTestoInstance
)
db.userDao().insertUser(
UserDatabaseEntity(
user_id = "123",
instance_uri = baseUrl.toString(),
username = "Testi",
display_name = "Testi Testo",
avatar_static = "some_avatar_url",
isActive = true,
accessToken = "token",
refreshToken = "refreshToken",
clientId = "clientId",
clientSecret = "clientSecret"
)
)
db.userDao().insertUser(testiTesto)
db.close()
Intents.init()
@ -100,81 +77,32 @@ class IntentTest {
fun clickingMentionOpensProfile() {
ActivityScenario.launch(MainActivity::class.java)
val account = Account("1450", "deerbard_photo", "deerbard_photo",
"https://pixelfed.social/deerbard_photo", "deerbard photography",
val account = Account("265626292148375552", "user2", "user2",
"https://testing2.pixeldroid.org/user2", "User 2",
"",
"https://pixelfed.social/storage/avatars/000/000/001/450/SMSep5NoabDam1W8UDMh_avatar.png?v=4b227777d4dd1fc61c6f884f48641d02b4d121d3fd328cb08b5531fcacdabf8a",
"https://pixelfed.social/storage/avatars/000/000/001/450/SMSep5NoabDam1W8UDMh_avatar.png?v=4b227777d4dd1fc61c6f884f48641d02b4d121d3fd328cb08b5531fcacdabf8a",
"https://testing2.pixeldroid.org/storage/avatars/default.jpg?v=0",
"https://testing2.pixeldroid.org/storage/avatars/default.jpg?v=0",
"", "", false, emptyList(), null,
"2018-08-01T12:58:21.000000Z", 72, 68, 27,
"2021-02-11T23:44:03.000000Z", 0, 1, 1,
null, null, false, null)
val expectedIntent: Matcher<Intent> = CoreMatchers.allOf(
IntentMatchers.hasExtra(ACCOUNT_TAG, account)
)
Thread.sleep(1000)
waitForView(R.id.description)
//Click the mention
Espresso.onView(ViewMatchers.withId(R.id.list))
.perform(RecyclerViewActions.actionOnItemAtPosition<StatusViewHolder>
(0, clickClickableSpanInDescription("@Dobios")))
(0, clickClickableSpanInDescription("@user2")))
//Wait a bit
Thread.sleep(1000)
//Check that the Profile is shown
//Check that the right intent was launched
intended(expectedIntent)
}
private fun clickClickableSpanInDescription(textToClick: CharSequence): ViewAction {
return object : ViewAction {
override fun getConstraints(): Matcher<View> {
return Matchers.instanceOf(TextView::class.java)
}
override fun getDescription(): String {
return "clicking on a ClickableSpan"
}
override fun perform(uiController: UiController, view: View) {
val textView = view.findViewById<View>(R.id.description) as TextView
val spannableString = textView.text as SpannableString
if (spannableString.isEmpty()) {
// TextView is empty, nothing to do
throw NoMatchingViewException.Builder()
.includeViewHierarchy(true)
.withRootView(textView)
.build()
}
// Get the links inside the TextView and check if we find textToClick
val spans = spannableString.getSpans(0, spannableString.length, ClickableSpan::class.java)
if (spans.isNotEmpty()) {
var spanCandidate: ClickableSpan
for (span: ClickableSpan in spans) {
spanCandidate = span
val start = spannableString.getSpanStart(spanCandidate)
val end = spannableString.getSpanEnd(spanCandidate)
val sequence = spannableString.subSequence(start, end)
if (textToClick.toString() == sequence.toString()) {
span.onClick(textView)
return
}
}
}
// textToClick not found in TextView
throw NoMatchingViewException.Builder()
.includeViewHierarchy(true)
.withRootView(textView)
.build()
}
}
}
@Test
fun clickEditProfileMakesIntent() {
@ -202,6 +130,5 @@ class IntentTest {
fun after() {
Intents.release()
clearData()
mockServer.stop()
}
}

View File

@ -1,6 +1,27 @@
package com.h.pixeldroid
/*
import android.content.Context
import androidx.test.core.app.ActivityScenario
import androidx.test.core.app.ApplicationProvider
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.isDisplayed
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry.getInstrumentation
import androidx.test.uiautomator.UiDevice
import androidx.test.uiautomator.UiSelector
import com.h.pixeldroid.testUtility.clearData
import com.h.pixeldroid.testUtility.initDB
import com.h.pixeldroid.utils.db.AppDatabase
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.rules.Timeout
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class LoginActivityOfflineTest {
@ -10,7 +31,7 @@ class LoginActivityOfflineTest {
fun switchAirplaneMode() {
val device = UiDevice.getInstance(getInstrumentation())
device.openQuickSettings()
device.findObject(UiSelector().textContains("airplane")).click()
device.findObject(UiSelector().textContains("Airplane")).click()
device.pressHome()
}
}
@ -46,6 +67,4 @@ class LoginActivityOfflineTest {
db.close()
clearData()
}
}
*/
}*/

View File

@ -19,9 +19,10 @@ import androidx.test.ext.junit.runners.AndroidJUnit4
import com.h.pixeldroid.utils.db.AppDatabase
import com.h.pixeldroid.utils.db.entities.InstanceDatabaseEntity
import com.h.pixeldroid.utils.db.entities.UserDatabaseEntity
import com.h.pixeldroid.testUtility.MockServer
import com.h.pixeldroid.testUtility.clearData
import com.h.pixeldroid.testUtility.initDB
import com.h.pixeldroid.testUtility.testiTesto
import com.h.pixeldroid.testUtility.testiTestoInstance
import org.junit.After
import org.junit.Before
import org.junit.Rule
@ -35,7 +36,6 @@ class LoginActivityOnlineTest {
private lateinit var db: AppDatabase
private lateinit var context: Context
private lateinit var pref: SharedPreferences
private lateinit var server: MockServer
@get:Rule
var globalTimeout: Timeout = Timeout.seconds(100)
@ -43,8 +43,6 @@ class LoginActivityOnlineTest {
@Before
fun setup() {
context = ApplicationProvider.getApplicationContext()
server = MockServer()
server.start()
context = ApplicationProvider.getApplicationContext()
pref = context.getSharedPreferences("com.h.pixeldroid.pref", Context.MODE_PRIVATE)
pref.edit().clear().apply()
@ -55,7 +53,6 @@ class LoginActivityOnlineTest {
@After
fun after() {
clearData()
server.stop()
}
@Test
@ -102,6 +99,7 @@ class LoginActivityOnlineTest {
))
}
/*
@Test
fun correctIntentReturnLoadsMainActivity() {
context = ApplicationProvider.getApplicationContext()
@ -109,36 +107,21 @@ class LoginActivityOnlineTest {
db.clearAllTables()
db.instanceDao().insertInstance(
InstanceDatabaseEntity(
uri = server.getUrl().toString(),
title = "PixelTest"
)
testiTestoInstance
)
db.userDao().insertUser(
UserDatabaseEntity(
user_id = "123",
instance_uri = server.getUrl().toString(),
username = "Testi",
display_name = "Testi Testo",
avatar_static = "some_avatar_url",
isActive = true,
accessToken = "token",
refreshToken = "refreshToken",
clientId = "clientId",
clientSecret = "clientSecret"
)
)
db.userDao().insertUser(testiTesto)
db.close()
pref.edit()
.putString("domain", server.getUrl().toString())
.putString("clientID", "test_id")
.putString("clientSecret", "test_secret")
.putString("domain", testiTestoInstance.uri)
.putString("clientID", testiTesto.clientId)
.putString("clientSecret", testiTesto.clientSecret)
.apply()
val uri = Uri.parse("oauth2redirect://com.h.pixeldroid?code=test_code")
val uri = Uri.parse("oauth2redirect://com.h.pixeldroid?code=$testiTesto.")
val intent = Intent(ACTION_VIEW, uri, context, LoginActivity::class.java)
ActivityScenario.launch<LoginActivity>(intent)
Thread.sleep(1000)
onView(withId(R.id.main_activity_main_linear_layout)).check(matches(isDisplayed()))
}
*/
}

View File

@ -7,14 +7,20 @@ import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.action.ViewActions.scrollTo
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.intent.Intents
import androidx.test.espresso.intent.Intents.intended
import androidx.test.espresso.intent.matcher.IntentMatchers.hasAction
import androidx.test.espresso.intent.matcher.IntentMatchers.hasDataString
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.espresso.matcher.RootMatchers.isDialog
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry.getInstrumentation
import androidx.test.rule.ActivityTestRule
import androidx.test.uiautomator.UiDevice
import com.h.pixeldroid.BuildConfig.INSTANCE_URI
import com.h.pixeldroid.testUtility.clearData
import com.h.pixeldroid.testUtility.waitForView
import org.hamcrest.CoreMatchers.allOf
import org.hamcrest.CoreMatchers.containsString
import org.hamcrest.Matcher
@ -30,12 +36,13 @@ class LoginCheckIntent {
@get:Rule
var globalTimeout: Timeout = Timeout.seconds(100)
@get:Rule
val intentsTestRule = ActivityTestRule(LoginActivity::class.java)
private lateinit var activityScenario: ActivityScenario<LoginActivity>
@Before
fun before() {
Intents.init()
activityScenario = ActivityScenario.launch(LoginActivity::class.java)
}
@Test
@ -43,11 +50,16 @@ class LoginCheckIntent {
ActivityScenario.launch(LoginActivity::class.java)
val expectedIntent: Matcher<Intent> = allOf(
hasAction(ACTION_VIEW),
hasDataString(containsString("pixelfed.de"))
hasDataString(containsString(INSTANCE_URI))
)
Thread.sleep(1000)
onView(withId(R.id.editText)).perform(scrollTo()).perform(ViewActions.replaceText("pixelfed.de"), ViewActions.closeSoftKeyboard())
waitForView(R.id.editText)
onView(withId(R.id.editText)).perform(scrollTo()).perform(
ViewActions.replaceText(
INSTANCE_URI
), ViewActions.closeSoftKeyboard()
)
onView(withId(R.id.connect_instance_button)).perform(scrollTo()).perform(click())
Thread.sleep(3000)
@ -58,22 +70,20 @@ class LoginCheckIntent {
@Test
fun launchesInstanceInfo() {
ActivityScenario.launch(LoginActivity::class.java)
val expectedIntent: Matcher<Intent> = allOf(
hasAction(ACTION_VIEW),
hasDataString(containsString("pixelfed.org/join"))
)
onView(withId(R.id.whatsAnInstanceTextView)).perform(scrollTo()).perform(click())
Thread.sleep(3000)
intended(expectedIntent)
waitForView(R.id.whats_an_instance_explanation)
onView(withText(R.string.whats_an_instance_explanation))
.inRoot(isDialog())
.check(matches(isDisplayed()));
}
@After
fun after() {
Intents.release()
clearData()
activityScenario.close()
}
}

View File

@ -1,49 +1,44 @@
package com.h.pixeldroid
/*
import android.content.Context
import androidx.test.core.app.ActivityScenario
import androidx.test.core.app.ApplicationProvider
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.google.android.material.tabs.TabLayout
import com.h.pixeldroid.testUtility.*
import com.h.pixeldroid.utils.db.AppDatabase
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class MockedServerTest {
private lateinit var mockServer: MockServer
private lateinit var activityScenario: ActivityScenario<MainActivity>
private lateinit var db: AppDatabase
private lateinit var context: Context
@Before
fun before(){
mockServer = MockServer()
mockServer.start()
val baseUrl = mockServer.getUrl()
context = ApplicationProvider.getApplicationContext()
db = initDB(context)
db.clearAllTables()
db.instanceDao().insertInstance(
InstanceDatabaseEntity(
uri = baseUrl.toString(),
title = "PixelTest"
)
)
db.instanceDao().insertInstance(testiTestoInstance)
db.userDao().insertUser(
UserDatabaseEntity(
user_id = "123",
instance_uri = baseUrl.toString(),
username = "Testi",
display_name = "Testi Testo",
avatar_static = "some_avatar_url",
isActive = true,
accessToken = "token"
)
)
db.userDao().insertUser(testiTesto)
db.close()
activityScenario = ActivityScenario.launch(MainActivity::class.java)
}
@After
fun after() {
clearData()
mockServer.stop()
}
/*
@Test
@ -59,90 +54,53 @@ class MockedServerTest {
Thread.sleep(3000)
onView(first(withId(R.id.username))).check(matches(withText("memo")))
}
*/
@Test
fun searchHashtags() {
activityScenario.onActivity{
a -> a.findViewById<TabLayout>(R.id.tabs).getTabAt(1)?.select()
}
Thread.sleep(1000)
onView(withId(R.id.searchEditText)).perform(ViewActions.replaceText("#caturday"), ViewActions.closeSoftKeyboard())
onView(withId(R.id.search)).perform(typeSearchViewText("#randomNoise"))
onView(withId(R.id.searchButton)).perform(click())
Thread.sleep(3000)
onView(first(withId(R.id.tag_name))).check(matches(withText("#caturday")))
waitForView(R.id.tag_name)
onView(first(withId(R.id.tag_name))).check(matches(withText("#randomNoise")))
}
*/
@Test
fun openDiscoverPost(){
activityScenario.onActivity{
a -> a.findViewById<TabLayout>(R.id.tabs).getTabAt(1)?.select()
}
Thread.sleep(1000)
onView(first(withId(R.id.postPreview))).perform(click())
Thread.sleep(1000)
onView(withId(R.id.username)).check(matches(withText("Arthur")))
waitForView(R.id.postPreview)
onView(first(withId(R.id.postPreview))).perform(click())
waitForView(R.id.username)
onView(withId(R.id.username)).check(matches(withSubstring("User ")))
}
/*
@Test
fun searchAccounts() {
activityScenario.onActivity{
a -> a.findViewById<TabLayout>(R.id.tabs).getTabAt(1)?.select()
}
Thread.sleep(1000)
onView(withId(R.id.searchEditText)).perform(ViewActions.replaceText("@dansup"), ViewActions.closeSoftKeyboard())
waitForView(R.id.search)
onView(withId(R.id.searchButton)).perform(click())
Thread.sleep(3000)
onView(first(withId(R.id.account_entry_username))).check(matches(withText("dansup")))
onView(withId(R.id.search)).perform(typeSearchViewText("@user3"))
waitForView(R.id.account_entry_username)
onView(first(withId(R.id.account_entry_username))).check(matches(withText("User 3")))
}
*/
@Test
fun clickFollowButton() {
//Get initial like count
onView(withId(R.id.list))
.perform(actionOnItemAtPosition<PostViewHolder>
(0, clickChildViewWithId(R.id.username)))
Thread.sleep(1000)
// Unfollow
onView(withId(R.id.followButton)).perform((click()))
Thread.sleep(1000)
onView(withId(R.id.followButton)).check(matches(withText("Follow")))
// Follow
onView(withId(R.id.followButton)).perform((click()))
Thread.sleep(1000)
onView(withId(R.id.followButton)).check(matches(withText("Unfollow")))
}
@Test
fun clickOtherUserFollowers() {
//Get initial like count
onView(withId(R.id.list))
.perform(actionOnItemAtPosition<PostViewHolder>
(0, clickChildViewWithId(R.id.username)))
Thread.sleep(1000)
// Open followers list
onView(withId(R.id.nbFollowersTextView)).perform((click()))
Thread.sleep(1000)
// Open follower's profile
onView(withText("ete2")).perform((click()))
Thread.sleep(1000)
onView(withId(R.id.accountNameTextView)).check(matches(withText("Christian")))
}
/*TODO test notifications (harder since they disappear after 6 months...
@Test
fun testNotificationsList() {
@ -156,7 +114,7 @@ class MockedServerTest {
onView(withId(R.id.view_pager)).perform(ViewActions.swipeDown())
Thread.sleep(1000)
onView(withText("Dobios followed you")).check(matches(withId(R.id.notification_type)))
onView(withText("user2 followed you")).check(matches(withId(R.id.notification_type)))
}
@Test
@ -222,7 +180,7 @@ class MockedServerTest {
Thread.sleep(1000)
onView(first(withText("Andrea"))).check(matches(withId(R.id.username)))
}
}*/
@Test
fun swipingRightStopsAtHomepage() {
@ -230,7 +188,8 @@ class MockedServerTest {
a -> a.findViewById<TabLayout>(R.id.tabs).getTabAt(4)?.select()
} // go to the last tab
Thread.sleep(1000)
waitForView(R.id.main_activity_main_linear_layout)
onView(withId(R.id.main_activity_main_linear_layout))
.perform(ViewActions.swipeRight()) // notifications
.perform(ViewActions.swipeRight()) // camera
@ -246,7 +205,8 @@ class MockedServerTest {
a -> a.findViewById<TabLayout>(R.id.tabs).getTabAt(0)?.select()
}
Thread.sleep(1000)
waitForView(R.id.main_activity_main_linear_layout)
onView(withId(R.id.main_activity_main_linear_layout))
.perform(ViewActions.swipeLeft()) // notifications
.perform(ViewActions.swipeLeft()) // camera
@ -262,7 +222,8 @@ class MockedServerTest {
a -> a.findViewById<TabLayout>(R.id.tabs).getTabAt(4)?.select()
} // go to the last tab
Thread.sleep(1000)
waitForView(R.id.view_pager)
onView(withId(R.id.view_pager))
.perform(ViewActions.swipeRight()) // notifications
.perform(ViewActions.swipeRight()) // camera
@ -276,7 +237,7 @@ class MockedServerTest {
a -> assert(a.findViewById<TabLayout>(R.id.tabs).getTabAt(0)?.isSelected ?: false)
}
}
/*
@Test
fun censorMatrices() {
val array: FloatArray = floatArrayOf(
@ -287,7 +248,5 @@ class MockedServerTest {
assert(censorColorMatrix().equals(ColorMatrix(array)))
assert(uncensorColorMatrix().equals(ColorMatrix()))
}
}
*/
}*/
}

View File

@ -1,11 +1,41 @@
package com.h.pixeldroid
/*
import android.Manifest
import android.content.ClipData
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Color
import android.net.Uri
import android.util.Log
import android.view.View.VISIBLE
import androidx.core.net.toUri
import androidx.core.os.bundleOf
import androidx.test.core.app.ActivityScenario
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.contrib.RecyclerViewActions
import androidx.test.espresso.matcher.ViewMatchers.isDisplayed
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.rule.GrantPermissionRule
import com.h.pixeldroid.postCreation.PostCreationActivity
import com.h.pixeldroid.postCreation.photoEdit.ThumbnailAdapter
import com.h.pixeldroid.settings.AboutActivity
import com.h.pixeldroid.testUtility.*
import com.h.pixeldroid.utils.db.AppDatabase
import org.hamcrest.CoreMatchers.not
import org.junit.*
import org.junit.rules.Timeout
import org.junit.runner.RunWith
import java.io.File
@RunWith(AndroidJUnit4::class)
class PostCreationActivityTest {
private var testScenario: ActivityScenario<PostCreationActivity>? = null
private lateinit var mockServer: MockServer
private lateinit var db: AppDatabase
private lateinit var context: Context
@ -26,33 +56,19 @@ class PostCreationActivityTest {
@Before
fun setup() {
context = InstrumentationRegistry.getInstrumentation().targetContext
mockServer = MockServer()
mockServer.start()
val baseUrl = mockServer.getUrl()
db = initDB(context)
db.clearAllTables()
db.instanceDao().insertInstance(
InstanceDatabaseEntity(
uri = baseUrl.toString(),
title = "PixelTest"
)
testiTestoInstance
)
db.userDao().insertUser(
UserDatabaseEntity(
user_id = "123",
instance_uri = baseUrl.toString(),
username = "Testi",
display_name = "Testi Testo",
avatar_static = "some_avatar_url",
isActive = true,
accessToken = "token"
)
testiTesto
)
db.close()
var uri1: String = ""
var uri2: String = ""
var uri1: Uri? = null
var uri2: Uri? = null
val scenario = ActivityScenario.launch(AboutActivity::class.java)
scenario.onActivity {
val image1 = Bitmap.createBitmap(500, 500, Bitmap.Config.ARGB_8888)
@ -63,28 +79,32 @@ class PostCreationActivityTest {
val file1 = File.createTempFile("temp_img1", ".png")
val file2 = File.createTempFile("temp_img2", ".png")
file1.writeBitmap(image1)
uri1 = file1.toUri().toString()
uri1 = file1.toUri()
file2.writeBitmap(image2)
uri2 = file2.toUri().toString()
Log.d("test", uri1+"\n"+uri2)
uri2 = file2.toUri()
}
val intent = Intent(context, PostCreationActivity::class.java).putExtra("pictures_uri", arrayListOf(uri1, uri2))
val intent = Intent(context, PostCreationActivity::class.java)
intent.clipData = ClipData("", emptyArray(), ClipData.Item(uri1))
intent.clipData!!.addItem(ClipData.Item(uri2))
testScenario = ActivityScenario.launch(intent)
}
@After
fun after() {
clearData()
mockServer.stop()
}
@Test
@Ignore("Annoying to deal with and also sometimes the intent is not working as it should")
fun createPost() {
onView(withId(R.id.post_creation_send_button)).perform(click())
// should send on main activity
onView(withId(R.id.main_activity_main_linear_layout)).check(matches(isDisplayed()))
Thread.sleep(3000)
onView(withId(R.id.list)).check(matches(isDisplayed()))
}
/*
@Test
fun errorShown() {
testScenario!!.onActivity { a -> a.upload_error.visibility = VISIBLE }
@ -113,9 +133,9 @@ class PostCreationActivityTest {
)
)
Thread.sleep(1000)
onView(withId(R.id.action_upload)).perform(click())
onView(withId(R.id.action_save)).perform(click())
Thread.sleep(1000)
onView(withId(R.id.image_grid)).check(matches(isDisplayed()))
onView(withId(R.id.carousel)).check(matches(isDisplayed()))
}
@Test
@ -127,5 +147,5 @@ class PostCreationActivityTest {
)
)
Thread.sleep(1000)
}
}*/
}*/
}

View File

@ -17,12 +17,8 @@ import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.rule.GrantPermissionRule
import com.google.android.material.tabs.TabLayout
import com.h.pixeldroid.testUtility.*
import com.h.pixeldroid.utils.db.AppDatabase
import com.h.pixeldroid.utils.db.entities.InstanceDatabaseEntity
import com.h.pixeldroid.utils.db.entities.UserDatabaseEntity
import com.h.pixeldroid.testUtility.MockServer
import com.h.pixeldroid.testUtility.clearData
import com.h.pixeldroid.testUtility.initDB
import org.hamcrest.Matcher
import org.junit.After
import org.junit.Before
@ -48,12 +44,12 @@ class PostCreationFragmentTest {
onView(withId(R.id.drawer_layout))
.perform(swipeLeft())
.perform(swipeLeft())
Thread.sleep(300)
waitForView(R.id.photo_view_button)
}
// upload intent
// image choosing intent
@Test
fun uploadButtonLaunchesGalleryIntent() {
fun galleryButtonLaunchesGalleryIntent() {
val expectedIntent: Matcher<Intent> = hasAction(Intent.ACTION_CHOOSER)
intending(expectedIntent)
onView(withId(R.id.photo_view_button)).perform(click())
@ -64,7 +60,6 @@ class PostCreationFragmentTest {
@RunWith(AndroidJUnit4::class)
class PostFragmentUITests {
private lateinit var mockServer: MockServer
private lateinit var context: Context
@get:Rule
@ -75,40 +70,21 @@ class PostFragmentUITests {
@Before
fun setup() {
context = InstrumentationRegistry.getInstrumentation().targetContext
mockServer = MockServer()
mockServer.start()
val baseUrl = mockServer.getUrl()
db = initDB(context)
db.clearAllTables()
db.instanceDao().insertInstance(
InstanceDatabaseEntity(
uri = baseUrl.toString(),
title = "PixelTest"
)
testiTestoInstance
)
db.userDao().insertUser(
UserDatabaseEntity(
user_id = "123",
instance_uri = baseUrl.toString(),
username = "Testi",
display_name = "Testi Testo",
avatar_static = "some_avatar_url",
isActive = true,
accessToken = "token",
refreshToken = "refreshToken",
clientId = "clientId",
clientSecret = "clientSecret"
)
testiTesto
)
db.close()
Thread.sleep(300)
}
@After
fun after() {
clearData()
mockServer.stop()
}
@Test
@ -116,7 +92,9 @@ class PostFragmentUITests {
ActivityScenario.launch(MainActivity::class.java).onActivity {
it.findViewById<TabLayout>(R.id.tabs).getTabAt(2)!!.select()
}
Thread.sleep(1500)
waitForView(R.id.photo_view_button)
onView(withId(R.id.photo_view_button)).check(matches(isDisplayed()))
onView(withId(R.id.camera_capture_button)).check(matches(isDisplayed()))
}

View File

@ -13,14 +13,16 @@ import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.platform.app.InstrumentationRegistry.getInstrumentation
import com.h.pixeldroid.BuildConfig.INSTANCE_URI
import com.h.pixeldroid.posts.PostActivity
import com.h.pixeldroid.utils.db.AppDatabase
import com.h.pixeldroid.utils.db.entities.InstanceDatabaseEntity
import com.h.pixeldroid.utils.db.entities.UserDatabaseEntity
import com.h.pixeldroid.utils.api.objects.*
import com.h.pixeldroid.testUtility.MockServer
import com.h.pixeldroid.testUtility.clearData
import com.h.pixeldroid.testUtility.initDB
import com.h.pixeldroid.testUtility.testiTesto
import com.h.pixeldroid.testUtility.testiTestoInstance
import org.hamcrest.CoreMatchers.anyOf
import org.hamcrest.Matcher
import org.junit.*
@ -34,7 +36,6 @@ class PostTest {
private lateinit var context: Context
private lateinit var db: AppDatabase
private lateinit var mockServer: MockServer
@get:Rule
var globalTimeout: Timeout = Timeout.seconds(100)
@ -42,32 +43,13 @@ class PostTest {
@Before
fun before(){
context = InstrumentationRegistry.getInstrumentation().targetContext
mockServer = MockServer()
mockServer.start()
val baseUrl = mockServer.getUrl()
db = initDB(context)
db.clearAllTables()
db.instanceDao().insertInstance(
InstanceDatabaseEntity(
uri = baseUrl.toString(),
title = "PixelTest"
)
testiTestoInstance
)
db.userDao().insertUser(
UserDatabaseEntity(
user_id = "123",
instance_uri = baseUrl.toString(),
username = "Testi",
display_name = "Testi Testo",
avatar_static = "some_avatar_url",
isActive = true,
accessToken = "token",
refreshToken = "refreshToken",
clientId = "clientId",
clientSecret = "clientSecret"
)
)
db.userDao().insertUser(testiTesto)
db.close()
Intents.init()
}
@ -76,15 +58,15 @@ class PostTest {
fun saveToGalleryTestSimplePost() {
val attachment = Attachment(
id = "12",
url = "https://wiki.gnugen.ch/lib/tpl/gnugen/images/logo_web.png",
url = "$INSTANCE_URI/storage/avatars/default.jpg?v=0",
meta = null
)
val post = Status(
id = "12",
account = Account(
id = "12",
username = "douze",
url = "https://pixelfed.de/douze",
username = "SQDFSQDF",
url = "$INSTANCE_URI/pixeldroid",
),
media_attachments = listOf(attachment)
)
@ -107,12 +89,12 @@ class PostTest {
fun saveToGalleryTestAlbum() {
val attachment1 = Attachment(
id = "12",
url = "https://wiki.gnugen.ch/lib/tpl/gnugen/images/logo_web.png",
url = "$INSTANCE_URI/storage/avatars/default.jpg?v=0",
meta = null
)
val attachment2 = Attachment(
id = "13",
url = "https://wiki.gnugen.ch/lib/tpl/gnugen/images/logo_web.png",
url = "$INSTANCE_URI/storage/avatars/default.jpg?v=0",
meta = null
)
val post = Status(
@ -120,7 +102,7 @@ class PostTest {
account = Account(
id = "12",
username = "douze",
url = "https://pixelfed.de/douze"
url = "$INSTANCE_URI/pixeldroid",
),
media_attachments = listOf(attachment1, attachment2)
)
@ -143,18 +125,18 @@ class PostTest {
fun shareTestSimplePost() {
val expectedIntent: Matcher<Intent> = IntentMatchers.hasAction(Intent.ACTION_CHOOSER)
val attachment = Attachment(
id = "12",
url = "https://wiki.gnugen.ch/lib/tpl/gnugen/images/logo_web.png",
id = "12",
url = "$INSTANCE_URI/storage/avatars/default.jpg?v=0",
meta = null
)
val post = Status(
id = "12",
account = Account(
id = "12",
username = "douze",
url = "https://pixelfed.de/douze",
),
media_attachments = listOf(attachment)
account = Account(
id = "12",
username = "douze",
url = "$INSTANCE_URI/pixeldroid",
),
media_attachments = listOf(attachment)
)
val intent = Intent(context, PostActivity::class.java)
intent.putExtra(Status.POST_TAG, post)
@ -170,22 +152,22 @@ class PostTest {
val expectedIntent: Matcher<Intent> = IntentMatchers.hasAction(Intent.ACTION_CHOOSER)
val attachment1 = Attachment(
id = "12",
url = "https://wiki.gnugen.ch/lib/tpl/gnugen/images/logo_web.png",
url = "$INSTANCE_URI/storage/avatars/default.jpg?v=0",
meta = null
)
val attachment2 = Attachment(
id = "13",
url = "https://wiki.gnugen.ch/lib/tpl/gnugen/images/logo_web.png",
id = "13",
url = "$INSTANCE_URI/storage/avatars/default.jpg?v=0",
meta = null
)
val post = Status(
id = "12",
account = Account(
id = "12",
username = "douze",
url = "https://pixelfed.de/douze"
),
media_attachments = listOf(attachment1, attachment2)
account = Account(
id = "12",
username = "douze",
url = "$INSTANCE_URI/pixeldroid",
),
media_attachments = listOf(attachment1, attachment2)
)
val intent = Intent(context, PostActivity::class.java)
intent.putExtra(Status.POST_TAG, post)
@ -249,14 +231,13 @@ class PostTest {
in_reply_to_id=null, in_reply_to_account=null, reblog=null, poll=null, card=null, language=null, text=null, favourited=false, reblogged=false, muted=false, bookmarked=false, pinned=false)
Assert.assertEquals("${status.reblogs_count} Shares",
status.getNShares(getInstrumentation().targetContext))
status.getNShares(context))
}
@After
fun after() {
Intents.release()
clearData()
mockServer.stop()
}
}

View File

@ -0,0 +1,102 @@
package com.h.pixeldroid
import android.content.Context
import android.content.Intent
import androidx.test.core.app.ActivityScenario
import androidx.test.core.app.ApplicationProvider
import androidx.test.espresso.Espresso
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions
import androidx.test.espresso.action.ViewActions.swipeDown
import androidx.test.espresso.assertion.ViewAssertions
import androidx.test.espresso.contrib.RecyclerViewActions
import androidx.test.espresso.matcher.ViewMatchers
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.h.pixeldroid.postCreation.PostCreationActivity
import com.h.pixeldroid.profile.ProfileActivity
import com.h.pixeldroid.testUtility.*
import com.h.pixeldroid.utils.api.objects.Account
import com.h.pixeldroid.utils.db.AppDatabase
import okhttp3.internal.wait
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import java.io.Serializable
@RunWith(AndroidJUnit4::class)
class ProfileTest {
private lateinit var activityScenario: ActivityScenario<ProfileActivity>
private lateinit var db: AppDatabase
private lateinit var context: Context
@Before
fun before(){
context = ApplicationProvider.getApplicationContext()
db = initDB(context)
db.clearAllTables()
db.instanceDao().insertInstance(testiTestoInstance)
db.userDao().insertUser(testiTesto)
db.close()
val intent = Intent(context, ProfileActivity::class.java)
val account = Account(id = "265472486651596800", username = "pixeldroid", acct = "pixeldroid", url = "https://testing2.pixeldroid.org/pixeldroid", display_name = "PixelDroid Developer", avatar = "https://testing2.pixeldroid.org/storage/avatars/default.jpg?v=0", avatar_static = "https://testing2.pixeldroid.org/storage/avatars/default.jpg?v=0", locked = false, emojis = arrayListOf(), discoverable = null, created_at = "2021-02-11T13:32:53.000000Z", statuses_count = 1, followers_count = 1, following_count = 1, moved = null, fields = null, bot = false, source = null)
intent.putExtra(Account.ACCOUNT_TAG, account)
activityScenario = ActivityScenario.launch(intent)
onView(withId(R.id.profileRefreshLayout)).perform(swipeDown())
Thread.sleep(2000)
}
@After
fun after() {
clearData()
}
@Test
fun clickFollowButton() {
if (onView(ViewMatchers.withText("Unfollow")).isDisplayed()) {
//Currently following
// Unfollow
follow("Follow")
// Follow
follow("Unfollow")
} else {
//Currently not following
// Follow
follow("Unfollow")
// Unfollow
follow("Follow")
}
}
private fun follow(follow_or_unfollow: String){
onView(withId(R.id.followButton)).perform((ViewActions.click()))
Thread.sleep(1000)
onView(withId(R.id.followButton)).check(ViewAssertions.matches(ViewMatchers.withText(follow_or_unfollow)))
}
@Test
fun clickOtherUserFollowers() {
// Open followers list
onView(withId(R.id.nbFollowersTextView)).perform((ViewActions.click()))
waitForView(R.id.account_entry_username)
// Open follower's profile
onView(ViewMatchers.withText("testi testo")).perform((ViewActions.click()))
waitForView(R.id.editButton)
//Check that our own profile opened
onView(withId(R.id.editButton)).check(ViewAssertions.matches(ViewMatchers.isDisplayed()))
}
}

View File

@ -1,153 +1,284 @@
package com.h.pixeldroid.testUtility
import android.text.SpannableString
import android.text.style.ClickableSpan
import android.view.View
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.widget.SearchView
import androidx.recyclerview.widget.RecyclerView
import androidx.test.espresso.Espresso
import androidx.test.espresso.UiController
import androidx.test.espresso.ViewAction
import androidx.test.espresso.*
import androidx.test.espresso.action.*
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.BoundedMatcher
import androidx.test.espresso.matcher.ViewMatchers
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.espresso.util.HumanReadables
import androidx.test.espresso.util.TreeIterables
import com.h.pixeldroid.R
import org.hamcrest.BaseMatcher
import org.hamcrest.CoreMatchers.allOf
import org.hamcrest.Description
import org.hamcrest.Matcher
import org.hamcrest.Matchers
import java.util.concurrent.TimeoutException
abstract class CustomMatchers {
companion object {
fun <T> first(matcher: Matcher<T>): Matcher<T>? {
return object : BaseMatcher<T>() {
var isFirst = true
override fun describeTo(description: org.hamcrest.Description?) {
description?.appendText("first matching item")
}
fun ViewInteraction.isDisplayed(): Boolean {
return try {
check(matches(ViewMatchers.isDisplayed()))
true
} catch (e: NoMatchingViewException) {
false
}
}
override fun matches(item: Any?): Boolean {
if (isFirst && matcher.matches(item)) {
isFirst = false
return true
/**
* Waits for a view to appear in the hierarchy
* Doesn't work if the root changes (since it operates on the root!)
* @param viewId The id of the view to wait for.
*/
fun waitForView(viewId: Int) {
Espresso.onView(isRoot()).perform(waitForViewViewAction(viewId))
}
/**
* This ViewAction tells espresso to wait till a certain view is found in the view hierarchy.
* @param viewId The id of the view to wait for.
*/
private fun waitForViewViewAction(viewId: Int): ViewAction {
// The maximum time which espresso will wait for the view to show up (in milliseconds)
val timeOut = 5000
return object : ViewAction {
override fun getConstraints(): Matcher<View> {
return isRoot()
}
override fun getDescription(): String {
return "wait for a specific view with id $viewId; during $timeOut millis."
}
override fun perform(uiController: UiController, rootView: View) {
uiController.loopMainThreadUntilIdle()
val startTime = System.currentTimeMillis()
val endTime = startTime + timeOut
val viewMatcher = withId(viewId)
do {
// Iterate through all views on the screen and see if the view we are looking for is there already
for (child in TreeIterables.breadthFirstViewTraversal(rootView)) {
// found view with required ID
if (viewMatcher.matches(child)) {
return
}
}
// Loops the main thread for a specified period of time.
// Control may not return immediately, instead it'll return after the provided delay has passed and the queue is in an idle state again.
uiController.loopMainThreadForAtLeast(100)
} while (System.currentTimeMillis() < endTime) // in case of a timeout we throw an exception -&gt; test fails
throw PerformException.Builder()
.withCause(TimeoutException())
.withActionDescription(this.description)
.withViewDescription(HumanReadables.describe(rootView))
.build()
}
}
}
fun clickClickableSpanInDescription(textToClick: CharSequence): ViewAction {
return object : ViewAction {
override fun getConstraints(): Matcher<View> {
return Matchers.instanceOf(TextView::class.java)
}
override fun getDescription(): String {
return "clicking on a ClickableSpan"
}
override fun perform(uiController: UiController, view: View) {
val textView = view.findViewById<View>(R.id.description) as TextView
val spannableString = SpannableString(textView.text)
if (spannableString.isEmpty()) {
// TextView is empty, nothing to do
throw NoMatchingViewException.Builder()
.includeViewHierarchy(true)
.withRootView(textView)
.build()
}
// Get the links inside the TextView and check if we find textToClick
val spans = spannableString.getSpans(0, spannableString.length, ClickableSpan::class.java)
if (spans.isNotEmpty()) {
var spanCandidate: ClickableSpan
for (span: ClickableSpan in spans) {
spanCandidate = span
val start = spannableString.getSpanStart(spanCandidate)
val end = spannableString.getSpanEnd(spanCandidate)
val sequence = spannableString.subSequence(start, end)
if (textToClick.toString() == sequence.toString()) {
span.onClick(textView)
return
}
}
}
// textToClick not found in TextView
throw NoMatchingViewException.Builder()
.includeViewHierarchy(true)
.withRootView(textView)
.build()
}
}
}
fun typeSearchViewText(text: String): ViewAction {
return object : ViewAction {
override fun getDescription(): String {
return "Change view text"
}
override fun getConstraints(): Matcher<View> {
return allOf(isDisplayed(), isAssignableFrom(SearchView::class.java))
}
override fun perform(uiController: UiController?, view: View?) {
(view as SearchView).setQuery(text, true)
}
}
}
fun <T> first(matcher: Matcher<T>): Matcher<T> {
return object : BaseMatcher<T>() {
var isFirst = true
override fun describeTo(description: org.hamcrest.Description?) {
description?.appendText("first matching item")
}
override fun matches(item: Any?): Boolean {
if (isFirst && matcher.matches(item)) {
isFirst = false
return true
}
return false
}
}
}
fun <T> second(matcher: Matcher<T>): Matcher<T> {
return object : BaseMatcher<T>() {
var isFirst = true
override fun describeTo(description: org.hamcrest.Description?) {
description?.appendText("second matching item")
}
override fun matches(item: Any?): Boolean {
if (isFirst && matcher.matches(item)) {
isFirst = false
return false
} else if (!isFirst && matcher.matches(item))
return true
return false
}
}
}
fun atPosition(position: Int, itemMatcher: Matcher<View?>): Matcher<View?> {
return object : BoundedMatcher<View?, RecyclerView>(RecyclerView::class.java) {
override fun describeTo(description: Description) {
description.appendText("has item at position $position: ")
itemMatcher.describeTo(description)
}
override fun matchesSafely(view: RecyclerView): Boolean {
val viewHolder = view.findViewHolderForAdapterPosition(position)
?: // has no item on such position
return false
}
}
}
fun <T> second(matcher: Matcher<T>): Matcher<T>? {
return object : BaseMatcher<T>() {
var isFirst = true
override fun describeTo(description: org.hamcrest.Description?) {
description?.appendText("second matching item")
}
override fun matches(item: Any?): Boolean {
if (isFirst && matcher.matches(item)) {
isFirst = false
return false
} else if (!isFirst && matcher.matches(item))
return true
return false
}
}
return itemMatcher.matches(viewHolder.itemView)
}
}
}
fun atPosition(position: Int, itemMatcher: Matcher<View?>): Matcher<View?>? {
return object : BoundedMatcher<View?, RecyclerView>(RecyclerView::class.java) {
override fun describeTo(description: Description) {
description.appendText("has item at position $position: ")
itemMatcher.describeTo(description)
}
override fun matchesSafely(view: RecyclerView): Boolean {
val viewHolder = view.findViewHolderForAdapterPosition(position)
?: // has no item on such position
return false
return itemMatcher.matches(viewHolder.itemView)
}
}
}
/**
* @param percent can be 1 or 0
* 1: swipes all the way up
* 0: swipes half way up
*/
fun slowSwipeUp(percent: Boolean) : ViewAction {
return ViewActions.actionWithAssertions(
GeneralSwipeAction(
/**
* @param percent can be 1 or 0
* 1: swipes all the way up
* 0: swipes half way up
*/
fun slowSwipeUp(percent: Boolean): ViewAction {
return ViewActions.actionWithAssertions(
GeneralSwipeAction(
Swipe.SLOW,
GeneralLocation.BOTTOM_CENTER,
if (percent) GeneralLocation.TOP_CENTER else GeneralLocation.CENTER,
Press.FINGER
)
)
}
)
}
/**
* @param percent can be 1 or 0
* 1: swipes all the way left
* 0: swipes half way left
*/
fun slowSwipeLeft(percent: Boolean) : ViewAction {
return ViewActions.actionWithAssertions(
GeneralSwipeAction(
/**
* @param percent can be 1 or 0
* 1: swipes all the way left
* 0: swipes half way left
*/
fun slowSwipeLeft(percent: Boolean): ViewAction {
return ViewActions.actionWithAssertions(
GeneralSwipeAction(
Swipe.SLOW,
GeneralLocation.CENTER_RIGHT,
if (percent) GeneralLocation.CENTER_LEFT else GeneralLocation.CENTER,
Press.FINGER
)
)
)
}
fun getText(matcher: Matcher<View?>?): String? {
val stringHolder = arrayOf<String?>(null)
Espresso.onView(matcher).perform(object : ViewAction {
override fun getConstraints(): Matcher<View> {
return ViewMatchers.isAssignableFrom(TextView::class.java)
}
fun getText(matcher: Matcher<View?>?): String? {
val stringHolder = arrayOf<String?>(null)
Espresso.onView(matcher).perform(object : ViewAction {
override fun getConstraints(): Matcher<View> {
return ViewMatchers.isAssignableFrom(TextView::class.java)
}
override fun getDescription(): String {
return "getting text from a TextView"
}
override fun perform(
uiController: UiController,
view: View
) {
val tv = view as TextView //Save, because of check in getConstraints()
stringHolder[0] = tv.text.toString()
}
})
return stringHolder[0]
override fun getDescription(): String {
return "getting text from a TextView"
}
fun clickChildViewWithId(id: Int) = object : ViewAction {
override fun getConstraints() = null
override fun getDescription() = "click child view with id $id"
override fun perform(uiController: UiController, view: View) {
val v = view.findViewById<View>(id)
v.performClick()
}
override fun perform(
uiController: UiController,
view: View,
) {
val tv = view as TextView //Save, because of check in getConstraints()
stringHolder[0] = tv.text.toString()
}
})
return stringHolder[0]
}
fun typeTextInViewWithId(id: Int, text: String) = object : ViewAction {
fun clickChildViewWithId(id: Int) = object : ViewAction {
override fun getConstraints() = null
override fun getConstraints() = null
override fun getDescription() = "click child view with id $id"
override fun getDescription() = "click child view with id $id"
override fun perform(uiController: UiController, view: View) {
val v = view.findViewById<EditText>(id)
v.text.append(text)
}
}
override fun perform(uiController: UiController, view: View) {
val v = view.findViewById<View>(id)
v.performClick()
}
}
fun typeTextInViewWithId(id: Int, text: String) = object : ViewAction {
override fun getConstraints() = null
override fun getDescription() = "click child view with id $id"
override fun perform(uiController: UiController, view: View) {
val v = view.findViewById<EditText>(id)
v.text.append(text)
}
}

File diff suppressed because one or more lines are too long

View File

@ -1,235 +0,0 @@
package com.h.pixeldroid.testUtility
import okhttp3.HttpUrl
import okhttp3.mockwebserver.Dispatcher
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import okhttp3.mockwebserver.RecordedRequest
class MockServer {
private val server = MockWebServer()
companion object{
private const val headerName = "Content-Type"
private const val headerValue = "application/json; charset=utf-8"
}
fun start() {
try {
server.start(45106)
server.dispatcher = getDispatcher()
} catch (e: IllegalArgumentException) {
}
}
fun stop(){
try {
server.shutdown()
} catch (e: IllegalArgumentException) {
}
}
private fun getDispatcher(): Dispatcher {
return object : Dispatcher() {
@Throws(InterruptedException::class)
override fun dispatch(request: RecordedRequest): MockResponse {
when (request.path) {
"/api/v1/accounts/verify_credentials" -> return MockResponse()
.addHeader(headerName, headerValue)
.setResponseCode(200).setBody(JsonValues.accountJson)
"/api/v1/instance" -> return MockResponse()
.addHeader(headerName, headerValue)
.setResponseCode(200).setBody(JsonValues.instanceJson.replace("REPLACEWITHDOMAIN", getUrl().toString()))
"/api/v1/media" -> return MockResponse()
.addHeader(headerName, headerValue)
.setResponseCode(200).setBody(JsonValues.mediaUploadResponseJson)
"/api/v1/timelines/home" -> return MockResponse()
.addHeader(headerName, headerValue)
.setResponseCode(200).setBody(JsonValues.feedJson)
"/oauth/token" -> return MockResponse()
.addHeader(headerName, headerValue)
.setResponseCode(200).setBody(JsonValues.tokenJson)
}
when {
request.path?.contains("/api/v1/apps") == true -> {
return MockResponse()
.addHeader("Content-Type", "application/json; charset=utf-8")
.setResponseCode(200).setBody(JsonValues.applicationJson)
}
request.path?.contains("/api/v1/notifications") == true -> {
return MockResponse()
.addHeader("Content-Type", "application/json; charset=utf-8")
.setResponseCode(200).setBody(JsonValues.notificationsJson)
}
request.path?.contains("/api/v1/timelines/home") == true -> {
return MockResponse().addHeader(
"Content-Type",
"application/json; charset=utf-8"
).setResponseCode(200).setBody(JsonValues.feedJson)
}
request.path?.contains("/api/v1/timelines/public") == true -> {
return MockResponse().addHeader(
"Content-Type",
"application/json; charset=utf-8"
).setResponseCode(200).setBody(JsonValues.feedJson)
}
request.path?.contains("/api/v1/accounts/0/statuses") == true -> {
return MockResponse().setHttp2ErrorCode(401)
}
request.path?.matches("/api/v1/accounts/[0-9]*/statuses".toRegex()) == true -> {
return MockResponse().addHeader(
"Content-Type",
"application/json; charset=utf-8"
).setResponseCode(200).setBody(JsonValues.accountStatusesJson)
}
request.path?.contains("/api/v1/statuses/0/context") == true -> {
return MockResponse().setHttp2ErrorCode(401)
}
request.path?.matches("/api/v1/statuses/[0-9]*/context".toRegex()) == true -> {
return MockResponse().addHeader(
"Content-Type",
"application/json; charset=utf-8"
).setResponseCode(200).setBody(JsonValues.commentStatusesJson)
}
request.path?.contains("/api/v1/statuses/0/favourite") == true -> {
return MockResponse().setHttp2ErrorCode(401)
}
request.path?.matches("/api/v1/statuses/[0-9]*/favourite".toRegex()) == true -> {
return MockResponse().addHeader(
"Content-Type",
"application/json; charset=utf-8"
).setResponseCode(200).setBody(JsonValues.likedJson)
}
request.path?.contains("/api/v1/statuses/0/unfavourite") == true -> {
return MockResponse().setHttp2ErrorCode(401)
}
request.path?.matches("/api/v1/statuses/[0-9]*/unfavourite".toRegex()) == true -> {
return MockResponse().addHeader(
"Content-Type",
"application/json; charset=utf-8"
).setResponseCode(200).setBody(JsonValues.unlikeJson)
}
request.path?.contains("/api/v1/statuses") == true -> {
return MockResponse().addHeader(
"Content-Type",
"application/json; charset=utf-8"
).setResponseCode(200).setBody(JsonValues.unlikeJson)
}
request.path?.contains("/api/v1/accounts/0") == true -> {
return MockResponse().setHttp2ErrorCode(401)
}
request.path?.matches("/api/v1/accounts/[0-9]*".toRegex()) == true -> {
return MockResponse().addHeader(
"Content-Type",
"application/json; charset=utf-8"
).setResponseCode(200).setBody(JsonValues.accountJson)
}
request.path?.contains("/api/v1/statuses/0/reblog") == true -> {
return MockResponse().setHttp2ErrorCode(401)
}
request.path?.matches("/api/v1/statuses/[0-9]*/reblog".toRegex()) == true -> {
return MockResponse().addHeader(
"Content-Type",
"application/json; charset=utf-8"
).setResponseCode(200).setBody(JsonValues.reblogJson)
}
request.path?.contains("/api/v1/statuses/0/unreblog") == true -> {
return MockResponse().setHttp2ErrorCode(401)
}
request.path?.matches("/api/v1/statuses/[0-9]*/unreblog".toRegex()) == true -> {
return MockResponse().addHeader(
"Content-Type",
"application/json; charset=utf-8"
).setResponseCode(200).setBody(JsonValues.unlikeJson)
}
request.path?.matches("/api/v1/accounts/[0-9]*/follow".toRegex()) == true -> {
return MockResponse().addHeader(
"Content-Type",
"application/json; charset=utf-8"
).setResponseCode(200).setBody(JsonValues.followRelationshipJson)
}
request.path?.matches("/api/v1/accounts/[0-9]*/unfollow".toRegex()) == true -> {
return MockResponse().addHeader(
"Content-Type",
"application/json; charset=utf-8"
).setResponseCode(200).setBody(JsonValues.unfollowRelationshipJson)
}
request.path?.contains("/api/v1/accounts/relationships") == true -> {
return MockResponse().addHeader(
"Content-Type",
"application/json; charset=utf-8"
).setResponseCode(200).setBody(JsonValues.relationshipJson)
}
request.path?.matches("/api/v1/accounts/[0-9]*/followers\\?limit=[0-9]*".toRegex()) == true -> {
return MockResponse().addHeader(
"Content-Type",
"application/json; charset=utf-8"
).setResponseCode(200).setBody(JsonValues.followersJson)
}
request.path?.matches("/api/v1/accounts/[0-9]*/followers\\?since_id=[0-9]*&limit=[0-9]*".toRegex()) == true -> {
return MockResponse().addHeader(
"Content-Type",
"application/json; charset=utf-8"
).setResponseCode(200).setBody(JsonValues.followersAfterJson)
}
request.path?.matches("/api/v1/accounts/[0-9]*/following\\?limit=[0-9]*".toRegex()) == true -> {
return MockResponse().addHeader(
"Content-Type",
"application/json; charset=utf-8"
).setResponseCode(200).setBody(JsonValues.followersJson)
}
request.path?.matches("/api/v1/accounts/[0-9]*/following\\?since_id=[0-9]*&limit=[0-9]*".toRegex()) == true -> {
return MockResponse().addHeader(
"Content-Type",
"application/json; charset=utf-8"
).setResponseCode(200).setBody(JsonValues.followersAfterJson)
}
request.path?.matches("/api/v2/search\\?type=hashtags&q=caturday&limit=[0-9]*&offset=[0-9]*".toRegex()) == true -> {
return MockResponse().addHeader(
"Content-Type",
"application/json; charset=utf-8"
).setResponseCode(200).setBody(JsonValues.searchEmpty)
}
request.path?.contains("/api/v2/search?type=hashtags&q=caturday")!!-> {
return MockResponse().addHeader(
"Content-Type",
"application/json; charset=utf-8"
).setResponseCode(200).setBody(JsonValues.searchCaturdayHashtags)
}
request.path?.contains("/api/v2/search?type=statuses&q=caturday")!! -> {
return MockResponse().addHeader(
"Content-Type",
"application/json; charset=utf-8"
).setResponseCode(200).setBody(JsonValues.searchCaturday)
}
request.path?.contains("/api/v2/search?type=accounts&q=dansup")!! -> {
return MockResponse().addHeader(
"Content-Type",
"application/json; charset=utf-8"
).setResponseCode(200).setBody(JsonValues.searchDansupAccounts)
}
request.path?.matches("""/api/v2/search\?(max_id=[0-9]*&)?type=(accounts|statuses)&q=dansup(&limit=[0-9]*)?""".toRegex())!! -> {
return MockResponse().addHeader(
"Content-Type",
"application/json; charset=utf-8"
).setResponseCode(200).setBody(JsonValues.searchEmpty)
}
request.path?.contains("/api/v2/discover/posts")!! -> {
return MockResponse().addHeader(
"Content-Type",
"application/json; charset=utf-8"
).setResponseCode(200).setBody(JsonValues.discover)
}
else -> return MockResponse().setResponseCode(404)
}
}
}
}
fun getUrl(): HttpUrl {
return server.url("")
}
}

View File

@ -0,0 +1,28 @@
package com.h.pixeldroid.testUtility
import com.h.pixeldroid.BuildConfig.*
import com.h.pixeldroid.utils.db.entities.InstanceDatabaseEntity
import com.h.pixeldroid.utils.db.entities.UserDatabaseEntity
val testiTestoInstance = InstanceDatabaseEntity(
uri = INSTANCE_URI,
title = "PixelDroid CI instance",
maxStatusChars = 150,
maxPhotoSize = 64000,
maxVideoSize = 64000,
albumLimit = 4
)
val testiTesto = UserDatabaseEntity(
user_id = USER_ID,
instance_uri = INSTANCE_URI,
username = "testitesto",
display_name = "testi testo",
avatar_static = "$INSTANCE_URI/storage/avatars/default.jpg?v=0",
isActive = true,
accessToken = ACCESS_TOKEN,
refreshToken = REFRESH_TOKEN,
clientId = CLIENT_ID,
clientSecret = CLIENT_SECRET
)

View File

@ -19,7 +19,6 @@
android:allowBackup="false"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:networkSecurityConfig="@xml/network_security_config"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme"

View File

@ -30883,6 +30883,253 @@
<pre>Copyright [yyyy] [name of copyright owner]&#x000A;&#x000A;Licensed under the Apache License, Version 2.0 (the "License");&#x000A;you may not use this file except in compliance with the License.&#x000A;You may obtain a copy of the License at&#x000A;&#x000A; http://www.apache.org/licenses/LICENSE-2.0&#x000A;&#x000A;Unless required by applicable law or agreed to in writing, software&#x000A;distributed under the License is distributed on an "AS IS" BASIS,&#x000A;WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.&#x000A;See the License for the specific language governing permissions and&#x000A;limitations under the License.</pre>
</div>
</div>
<div class="library">
<!-- https://opensource.org/licenses/Apache-2.0 -->
<h1 class="title">dynamicanimation</h1>
<p class="notice">Copyright &copy; Google Inc. All rights reserved.</p>
<p><a href="http://developer.android.com/tools/extras/support-library.html">http://developer.android.com/tools/extras/support-library.html</a></p>
<input type="checkbox"><label></label>
<div class="license">
<h2>
Apache License
<br/>
Version 2.0, January 2004
<br/>
http://www.apache.org/licenses/
</h2>
<p>TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION</p>
<h2>1. Definitions.</h2>
<p>
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
</p>
<p>
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
</p>
<p>
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
</p>
<p>
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
</p>
<p>
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
</p>
<p>
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
</p>
<p>
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
</p>
<p>
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
</p>
<p>
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
</p>
<p>
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
</p>
<div class="block">
<h2 class="inline">2. Grant of Copyright License.</h2>
<p class="inline">
Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
</p>
</div>
<div class="block">
<h2 class="inline">3. Grant of Patent License.</h2>
<p class="inline">
Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
</p>
</div>
<div class="block">
<h2 class="inline">4. Redistribution.</h2>
<p class="inline">
You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
</p>
</div>
<ul class="low-alpha">
<li>
You must give any other recipients of the Work or
Derivative Works a copy of this License; and
</li>
<li>
You must cause any modified files to carry prominent notices
stating that You changed the files; and
</li>
<li>
You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of |
the Derivative Works; and
</li>
<li>
If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
</li>
</ul>
<p>
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
</p>
<div class="block">
<h2 class="inline">5. Submission of Contributions.</h2>
<p class="inline">
Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
</p>
</div>
<div class="block">
<h2 class="inline">6. Trademarks.</h2>
<p class="inline">
This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
</p>
</div>
<div class="block">
<h2 class="inline">7. Disclaimer of Warranty.</h2>
<p class="inline">
Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
</p>
</div>
<div class="block">
<h2 class="inline">8. Limitation of Liability.</h2>
<p class="inline">
In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
</p>
</div>
<div class="block">
<h2 class="inline">9. Accepting Warranty or Additional Liability.</h2>
<p class="inline">
While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
</p>
</div>
<p>END OF TERMS AND CONDITIONS</p>
<h1>APPENDIX: How to apply the Apache License to your work.</h1>
<p>
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
</p>
<pre>Copyright [yyyy] [name of copyright owner]&#x000A;&#x000A;Licensed under the Apache License, Version 2.0 (the "License");&#x000A;you may not use this file except in compliance with the License.&#x000A;You may obtain a copy of the License at&#x000A;&#x000A; http://www.apache.org/licenses/LICENSE-2.0&#x000A;&#x000A;Unless required by applicable law or agreed to in writing, software&#x000A;distributed under the License is distributed on an "AS IS" BASIS,&#x000A;WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.&#x000A;See the License for the specific language governing permissions and&#x000A;limitations under the License.</pre>
</div>
</div>
</body>

View File

@ -118,7 +118,7 @@ class LoginActivity : BaseActivity() {
private fun registerAppToServer(normalizedDomain: String) {
if(!validDomain(normalizedDomain)) failedRegistration(getString(R.string.invalid_domain))
if(!validDomain(normalizedDomain)) return failedRegistration(getString(R.string.invalid_domain))
hideKeyboard()
loadingAnimation(true)

View File

@ -319,6 +319,7 @@ class PhotoEditActivity : BaseActivity() {
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if(grantResults.size > 1
&& grantResults[0] == PackageManager.PERMISSION_GRANTED
&& grantResults[1] == PackageManager.PERMISSION_GRANTED) {

View File

@ -97,7 +97,7 @@ class AccountViewHolder(binding: AccountListEntryBinding) : RecyclerView.ViewHol
.circleCrop().placeholder(R.drawable.ic_default_user)
.into(avatar)
username.text = account?.username
username.text = account?.display_name
@SuppressLint("SetTextI18n")
acct.text = "@${account?.acct}"
}

View File

@ -1,6 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="true">localhost</domain>
</domain-config>
</network-security-config>