├── testing ├── android │ ├── app │ │ ├── .gitignore │ │ ├── src │ │ │ ├── main │ │ │ │ ├── res │ │ │ │ │ ├── values │ │ │ │ │ │ ├── strings.xml │ │ │ │ │ │ ├── colors.xml │ │ │ │ │ │ └── themes.xml │ │ │ │ │ ├── mipmap-hdpi │ │ │ │ │ │ ├── ic_launcher.webp │ │ │ │ │ │ └── ic_launcher_round.webp │ │ │ │ │ ├── mipmap-mdpi │ │ │ │ │ │ ├── ic_launcher.webp │ │ │ │ │ │ └── ic_launcher_round.webp │ │ │ │ │ ├── mipmap-xhdpi │ │ │ │ │ │ ├── ic_launcher.webp │ │ │ │ │ │ └── ic_launcher_round.webp │ │ │ │ │ ├── mipmap-xxhdpi │ │ │ │ │ │ ├── ic_launcher.webp │ │ │ │ │ │ └── ic_launcher_round.webp │ │ │ │ │ ├── mipmap-xxxhdpi │ │ │ │ │ │ ├── ic_launcher.webp │ │ │ │ │ │ └── ic_launcher_round.webp │ │ │ │ │ ├── mipmap-anydpi-v26 │ │ │ │ │ │ ├── ic_launcher.xml │ │ │ │ │ │ └── ic_launcher_round.xml │ │ │ │ │ ├── values-night │ │ │ │ │ │ └── themes.xml │ │ │ │ │ ├── drawable-v24 │ │ │ │ │ │ └── ic_launcher_foreground.xml │ │ │ │ │ └── drawable │ │ │ │ │ │ └── ic_launcher_background.xml │ │ │ │ └── AndroidManifest.xml │ │ │ ├── test │ │ │ │ └── java │ │ │ │ │ └── live │ │ │ │ │ └── ditto │ │ │ │ │ └── dittotesting │ │ │ │ │ └── ExampleUnitTest.kt │ │ │ └── androidTest │ │ │ │ └── java │ │ │ │ └── live │ │ │ │ └── ditto │ │ │ │ └── dittotesting │ │ │ │ ├── CustomDirectoryAndroidDittoDependencies.kt │ │ │ │ ├── helpers.kt │ │ │ │ ├── ExampleDittoTest.kt │ │ │ │ ├── TestAndroidDittoDependencies.kt │ │ │ │ └── DittoTestBase.kt │ │ ├── proguard-rules.pro │ │ └── build.gradle │ ├── README.md │ ├── gradle │ │ └── wrapper │ │ │ ├── gradle-wrapper.jar │ │ │ └── gradle-wrapper.properties │ ├── .gitignore │ ├── settings.gradle │ ├── build.gradle │ ├── gradle.properties │ ├── .run │ │ └── Instrumented Tests.run.xml │ ├── gradlew.bat │ └── gradlew └── SwiftUI │ ├── Sources │ └── SwiftUI │ │ └── SwiftUI.swift │ ├── README.md │ ├── .gitignore │ ├── .swiftpm │ └── xcode │ │ ├── package.xcworkspace │ │ └── xcshareddata │ │ │ └── IDEWorkspaceChecks.plist │ │ └── xcshareddata │ │ └── xcschemes │ │ ├── SwiftUITests.xcscheme │ │ ├── SwiftUI-Package.xcscheme │ │ └── SwiftUI.xcscheme │ ├── Package.resolved │ ├── Package.swift │ └── Tests │ └── SwiftUITests │ └── SwiftUITests.swift ├── README.md └── .gitignore /testing/android/app/.gitignore: -------------------------------------------------------------------------------- 1 | /build -------------------------------------------------------------------------------- /testing/android/README.md: -------------------------------------------------------------------------------- 1 | # Ditto Testing Example 2 | 3 | An example for testing Ditto in Android Kotlin. 4 | -------------------------------------------------------------------------------- /testing/android/app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | DittoTesting 3 | -------------------------------------------------------------------------------- /testing/android/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/getditto/samples/HEAD/testing/android/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /testing/SwiftUI/Sources/SwiftUI/SwiftUI.swift: -------------------------------------------------------------------------------- 1 | public struct SwiftUI { 2 | public private(set) var text = "Hello, World!" 3 | 4 | public init() { 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /testing/android/app/src/main/res/mipmap-hdpi/ic_launcher.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/getditto/samples/HEAD/testing/android/app/src/main/res/mipmap-hdpi/ic_launcher.webp -------------------------------------------------------------------------------- /testing/android/app/src/main/res/mipmap-mdpi/ic_launcher.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/getditto/samples/HEAD/testing/android/app/src/main/res/mipmap-mdpi/ic_launcher.webp -------------------------------------------------------------------------------- /testing/android/app/src/main/res/mipmap-xhdpi/ic_launcher.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/getditto/samples/HEAD/testing/android/app/src/main/res/mipmap-xhdpi/ic_launcher.webp -------------------------------------------------------------------------------- /testing/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/getditto/samples/HEAD/testing/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp -------------------------------------------------------------------------------- /testing/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/getditto/samples/HEAD/testing/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp -------------------------------------------------------------------------------- /testing/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/getditto/samples/HEAD/testing/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp -------------------------------------------------------------------------------- /testing/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/getditto/samples/HEAD/testing/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp -------------------------------------------------------------------------------- /testing/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/getditto/samples/HEAD/testing/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp -------------------------------------------------------------------------------- /testing/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/getditto/samples/HEAD/testing/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp -------------------------------------------------------------------------------- /testing/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/getditto/samples/HEAD/testing/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp -------------------------------------------------------------------------------- /testing/SwiftUI/README.md: -------------------------------------------------------------------------------- 1 | # Ditto Testing Example 2 | 3 | An example for testing Ditto in SwiftUI. 4 | 5 | See [the docs](https://docs.ditto.live/swift/quick-tips/testing) for more information. 6 | -------------------------------------------------------------------------------- /testing/SwiftUI/.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | /.build 3 | /Packages 4 | /*.xcodeproj 5 | xcuserdata/ 6 | DerivedData/ 7 | .swiftpm/config/registries.json 8 | .swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata 9 | .netrc 10 | -------------------------------------------------------------------------------- /testing/android/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Fri Aug 04 16:27:00 EDT 2023 2 | distributionBase=GRADLE_USER_HOME 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.2-bin.zip 4 | distributionPath=wrapper/dists 5 | zipStorePath=wrapper/dists 6 | zipStoreBase=GRADLE_USER_HOME 7 | -------------------------------------------------------------------------------- /testing/android/.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea/caches 5 | /.idea/libraries 6 | /.idea/modules.xml 7 | /.idea/workspace.xml 8 | /.idea/navEditor.xml 9 | /.idea/assetWizardSettings.xml 10 | .DS_Store 11 | /build 12 | /captures 13 | .externalNativeBuild 14 | .cxx 15 | local.properties 16 | -------------------------------------------------------------------------------- /testing/SwiftUI/.swiftpm/xcode/package.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /testing/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /testing/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /testing/SwiftUI/Package.resolved: -------------------------------------------------------------------------------- 1 | { 2 | "pins" : [ 3 | { 4 | "identity" : "dittoswiftpackage", 5 | "kind" : "remoteSourceControl", 6 | "location" : "https://github.com/getditto/DittoSwiftPackage", 7 | "state" : { 8 | "branch" : "main", 9 | "revision" : "be03dc47d1517fb669f173833625262340b4aab8" 10 | } 11 | } 12 | ], 13 | "version" : 2 14 | } 15 | -------------------------------------------------------------------------------- /testing/android/settings.gradle: -------------------------------------------------------------------------------- 1 | pluginManagement { 2 | repositories { 3 | gradlePluginPortal() 4 | google() 5 | mavenCentral() 6 | } 7 | } 8 | dependencyResolutionManagement { 9 | repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) 10 | repositories { 11 | google() 12 | mavenCentral() 13 | } 14 | } 15 | rootProject.name = "DittoTesting" 16 | include ':app' 17 | -------------------------------------------------------------------------------- /testing/android/app/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #FFBB86FC 4 | #FF6200EE 5 | #FF3700B3 6 | #FF03DAC5 7 | #FF018786 8 | #FF000000 9 | #FFFFFFFF 10 | -------------------------------------------------------------------------------- /testing/android/app/src/test/java/live/ditto/dittotesting/ExampleUnitTest.kt: -------------------------------------------------------------------------------- 1 | package live.ditto.dittotesting 2 | 3 | import org.junit.Test 4 | 5 | import org.junit.Assert.* 6 | 7 | /** 8 | * Example local unit test, which will execute on the development machine (host). 9 | * 10 | * See [testing documentation](http://d.android.com/tools/testing). 11 | */ 12 | class ExampleUnitTest { 13 | @Test 14 | fun addition_isCorrect() { 15 | assertEquals(4, 2 + 2) 16 | } 17 | } -------------------------------------------------------------------------------- /testing/android/app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /testing/android/build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | ext { 3 | kotlin_version = "1.8.22" 4 | } 5 | 6 | repositories { 7 | google() 8 | mavenCentral() 9 | } 10 | } 11 | /// Top-level build file where you can add configuration options common to all sub-projects/modules. 12 | plugins { 13 | id "com.android.application" version "8.1.0" apply false 14 | id "com.android.library" version "8.1.0" apply false 15 | id "org.jetbrains.kotlin.android" version "$kotlin_version" apply false 16 | id "com.google.devtools.ksp" version "1.8.22-1.0.11" apply false 17 | } 18 | -------------------------------------------------------------------------------- /testing/android/app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile -------------------------------------------------------------------------------- /testing/android/app/src/androidTest/java/live/ditto/dittotesting/CustomDirectoryAndroidDittoDependencies.kt: -------------------------------------------------------------------------------- 1 | package live.ditto.dittotesting 2 | 3 | import live.ditto.android.* 4 | import android.content.Context 5 | import java.io.File 6 | 7 | /** 8 | * Implementation of `AndroidDittoDependencies` which uses a custom `persistenceDirectory`. 9 | */ 10 | data class CustomDirectoryAndroidDittoDependencies( 11 | private val androidDittoDependencies: DefaultAndroidDittoDependencies, 12 | private val customDir: File 13 | ): AndroidDittoDependencies { 14 | 15 | override fun persistenceDirectory(): String { 16 | return customDir.path 17 | } 18 | 19 | override fun ensureDirectoryExists(path: String) { 20 | androidDittoDependencies.ensureDirectoryExists(path) 21 | } 22 | 23 | override fun context(): Context { 24 | return androidDittoDependencies.context() 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /testing/android/app/src/main/res/values/themes.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 16 | -------------------------------------------------------------------------------- /testing/android/app/src/main/res/values-night/themes.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 16 | -------------------------------------------------------------------------------- /testing/SwiftUI/Package.swift: -------------------------------------------------------------------------------- 1 | // swift-tools-version: 5.6 2 | // The swift-tools-version declares the minimum version of Swift required to build this package. 3 | 4 | import PackageDescription 5 | 6 | let package = Package( 7 | name: "SwiftUI", 8 | platforms: [ .iOS(.v15), .macOS(.v11) ], 9 | products: [ 10 | ], 11 | dependencies: [ 12 | // Dependencies declare other packages that this package depends on. 13 | .package(url: "https://github.com/getditto/DittoSwiftPackage", branch: "main"), 14 | ], 15 | targets: [ 16 | // Targets are the basic building blocks of a package. A target can define a module or a test suite. 17 | // Targets can depend on other targets in this package, and on products in packages this package depends on. 18 | .testTarget( 19 | name: "SwiftUITests", 20 | dependencies: [ 21 | .product(name: "DittoSwift", package: "DittoSwiftPackage") 22 | ] 23 | ) 24 | ] 25 | ) 26 | -------------------------------------------------------------------------------- /testing/android/app/src/androidTest/java/live/ditto/dittotesting/helpers.kt: -------------------------------------------------------------------------------- 1 | package live.ditto.dittotesting 2 | 3 | import android.content.Context 4 | import live.ditto.Ditto 5 | import live.ditto.DittoDependencies 6 | import live.ditto.DittoIdentity 7 | import java.io.File 8 | 9 | 10 | fun clearUpDirectory(directory: File) { 11 | directory.deleteRecursively() 12 | } 13 | @JvmOverloads 14 | fun clearUpDittoDirectories(context: Context, customDir: String? = null) { 15 | val dittoDir = if (customDir == null) File(context.filesDir, "ditto") else File(customDir) 16 | clearUpDirectory(dittoDir) 17 | } 18 | 19 | @JvmOverloads 20 | fun getDitto( 21 | dependencies: DittoDependencies, 22 | identity: DittoIdentity = DittoIdentity.OnlinePlayground( 23 | dependencies, 24 | // Get these values from https://portal.ditto.live 25 | "YOUR_APP_ID", 26 | "YOUR_PLAYGROUND_TOKEN", 27 | false 28 | ), 29 | ): Ditto { 30 | val ditto = Ditto(dependencies, identity) 31 | ditto.disableSyncWithV3() 32 | return ditto 33 | } -------------------------------------------------------------------------------- /testing/android/app/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id "com.android.application" 3 | id "org.jetbrains.kotlin.android" 4 | id "com.google.devtools.ksp" 5 | } 6 | 7 | 8 | 9 | android { 10 | compileSdk 34 11 | 12 | defaultConfig { 13 | applicationId "live.dittolive.chat" 14 | minSdk 29 15 | targetSdk 34 16 | versionCode 16 17 | versionName "3.0" 18 | 19 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 20 | } 21 | buildTypes { 22 | release { 23 | minifyEnabled false 24 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 25 | } 26 | } 27 | compileOptions { 28 | sourceCompatibility JavaVersion.VERSION_17 29 | targetCompatibility JavaVersion.VERSION_17 30 | } 31 | kotlin { 32 | jvmToolchain(17) 33 | } 34 | namespace "live.ditto.dittotesting" 35 | } 36 | 37 | dependencies { 38 | implementation("androidx.core:core-ktx:1.10.1") 39 | implementation("androidx.appcompat:appcompat:1.6.1") 40 | implementation("com.google.android.material:material:1.9.0") 41 | testImplementation("junit:junit:4.13.2") 42 | androidTestImplementation("androidx.test.ext:junit:1.1.5") 43 | androidTestImplementation("androidx.test.espresso:espresso-core:3.5.1") 44 | 45 | implementation("live.ditto:ditto:4.5.1") 46 | } 47 | -------------------------------------------------------------------------------- /testing/android/gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | # IDE (e.g. Android Studio) users: 3 | # Gradle settings configured through the IDE *will override* 4 | # any settings specified in this file. 5 | # For more details on how to configure your build environment visit 6 | # http://www.gradle.org/docs/current/userguide/build_environment.html 7 | # Specifies the JVM arguments used for the daemon process. 8 | # The setting is particularly useful for tweaking memory settings. 9 | org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8 10 | # When configured, Gradle will run in incubating parallel mode. 11 | # This option should only be used with decoupled projects. More details, visit 12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 13 | # org.gradle.parallel=true 14 | # AndroidX package structure to make it clearer which packages are bundled with the 15 | # Android operating system, and which are packaged with your app"s APK 16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn 17 | android.useAndroidX=true 18 | # Kotlin code style for this project: "official" or "obsolete": 19 | kotlin.code.style=official 20 | # Enables namespacing of each library's R class so that its R class includes only the 21 | # resources declared in the library itself and none from the library's dependencies, 22 | # thereby reducing the size of the R class for that library 23 | android.nonTransitiveRClass=true -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Ditto Sample Projects 2 | 3 | ### Table of contents 4 | 5 | 1. [Authentication](https://github.com/getditto/sample-authentication-permissions): Permissions, roles, and integration with Auth0 or your own authentication platform. 6 | 1. [Testing](/testing) 7 | 1. [Authentication Server in C#](https://github.com/getditto/template-c-sharp-server) 8 | 1. [Change Data Capture](https://github.com/getditto/external-sync): Keep your Ditto database in sync with external systems, such as MongoDB. 9 | 1. [Heartbeat](https://github.com/getditto/heartbeat): Create an end-to-end heartbeat to monitor Big Peer status 10 | 1. [Rust SDK Sample](https://github.com/getditto/template-rust) 11 | 12 | ## Getting Started Template Todo Tasks App 13 | 14 | 1. [Electron, React, and Typescript](https://github.com/getditto/template-app-electron-react-ts-todo) 15 | 1. [Swift](https://github.com/getditto/template-app-swift-todo) 16 | 1. [C#](https://github.com/getditto/template-app-csharp-todo) 17 | 1. [C++](https://github.com/getditto/template-app-cpp-todo) 18 | 1. [.NET MAUI](https://github.com/getditto/template-app-maui-tasks-app) 19 | 1. [Xamarin-iOS](https://github.com/getditto/template-app-xamarin-ios-todo) 20 | 1. [Xamarin-Android](https://github.com/getditto/template-app-xamarin-android-todo) 21 | 1. [Nodejs](https://github.com/getditto/template-app-nodejs-todo) 22 | 1. [Jetpack Compose, Kotlin](https://github.com/getditto/template-app-jetpack-compose-kotlin-todo) 23 | 1. [Combine](https://github.com/getditto/Sample-app-Combine) 24 | -------------------------------------------------------------------------------- /testing/android/app/src/androidTest/java/live/ditto/dittotesting/ExampleDittoTest.kt: -------------------------------------------------------------------------------- 1 | package live.ditto.dittotesting 2 | 3 | import kotlinx.coroutines.runBlocking 4 | import org.junit.Assert.assertEquals 5 | import org.junit.Test 6 | import java.io.File 7 | import java.util.concurrent.CountDownLatch 8 | 9 | class ExampleDittoTest: DittoTestBase() { 10 | @Test 11 | fun twoDittos() = runBlocking { 12 | val ditto1 = getDitto(dependenciesWithCustomDirectory(File(getWorkDir(), "ditto1"))) 13 | val ditto2 = getDitto(dependenciesWithCustomDirectory(File(getWorkDir(), "ditto2"))) 14 | 15 | ditto1.startSync() 16 | ditto2.startSync() 17 | 18 | 19 | val collection = "cars" 20 | 21 | // Inserting a car into 'ditto1' store 22 | val car = mapOf("make" to "toyota", "mileage" to 160000) 23 | ditto1.store.execute( 24 | "INSERT INTO $collection DOCUMENTS (:car)", 25 | mapOf("car" to car) 26 | ) 27 | 28 | val selectQuery = "SELECT * FROM $collection" 29 | 30 | // Registering a subscription from 'ditto2' 31 | ditto2.sync.registerSubscription(selectQuery) 32 | 33 | 34 | val count = CountDownLatch(1) 35 | var make = "" 36 | 37 | // Registering a result observer on 'ditto2' store 38 | ditto2.store.registerObserver(selectQuery) { result -> 39 | if (result.items.isNotEmpty()) { 40 | make = result.items.first().value["make"].toString() 41 | count.countDown() 42 | 43 | ditto1.stopSync() 44 | ditto2.stopSync() 45 | } 46 | } 47 | 48 | count.await() 49 | assertEquals(make, "toyota") 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /testing/android/app/src/androidTest/java/live/ditto/dittotesting/TestAndroidDittoDependencies.kt: -------------------------------------------------------------------------------- 1 | package live.ditto.android 2 | 3 | import android.content.Context 4 | import java.io.File 5 | import java.util.UUID 6 | 7 | /** 8 | * Provides a default set of dependencies that you can pass to the [live.ditto.Ditto] initializer 9 | * when running unit tests. 10 | * 11 | * `TestAndroidDittoDependencies` differs from `DefaultAndroidDittoDependencies` in that 12 | * this test class will use a random and unique directory for each instantiation. 13 | */ 14 | class TestAndroidDittoDependencies( 15 | context: Context, 16 | ) : AndroidDittoDependencies { 17 | private val randomDir: String = UUID.randomUUID().toString() 18 | private val androidDittoDependencies: DefaultAndroidDittoDependencies = DefaultAndroidDittoDependencies(context) 19 | 20 | override fun persistenceDirectory(): String { 21 | // We use "ditto" as a stable root dir so that `clearUpDittoDirectories` 22 | // has a well-known path to recursively test. 23 | val dittoDir = File(androidDittoDependencies.context().filesDir, "ditto") 24 | 25 | // Each ditto instance which uses this context will use a random dir 26 | // inside "ditto" as a persistence directory. This allows multiple 27 | // ditto instances to run simultaneously without clobbering each other's 28 | // storage. 29 | val filesDir = File(dittoDir, randomDir) 30 | filesDir.mkdirs() 31 | 32 | return filesDir.path 33 | } 34 | 35 | override fun ensureDirectoryExists(path: String) { 36 | androidDittoDependencies.ensureDirectoryExists(path) 37 | } 38 | 39 | override fun context(): Context { 40 | return androidDittoDependencies.context() 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /testing/android/app/src/main/res/drawable-v24/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 7 | 8 | 9 | 15 | 18 | 21 | 22 | 23 | 24 | 30 | -------------------------------------------------------------------------------- /testing/SwiftUI/.swiftpm/xcode/xcshareddata/xcschemes/SwiftUITests.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 14 | 15 | 17 | 23 | 24 | 25 | 26 | 27 | 37 | 38 | 44 | 45 | 47 | 48 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /testing/SwiftUI/.swiftpm/xcode/xcshareddata/xcschemes/SwiftUI-Package.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 24 | 25 | 30 | 31 | 33 | 39 | 40 | 41 | 42 | 43 | 53 | 54 | 60 | 61 | 63 | 64 | 67 | 68 | 69 | -------------------------------------------------------------------------------- /testing/SwiftUI/Tests/SwiftUITests/SwiftUITests.swift: -------------------------------------------------------------------------------- 1 | import XCTest 2 | import DittoSwift 3 | 4 | 5 | final class SwiftUITests: XCTestCase { 6 | 7 | var ditto1: DittoInstance! 8 | var ditto2: DittoInstance! 9 | 10 | override func setUp() { 11 | self.ditto1 = DittoInstance() 12 | self.ditto2 = DittoInstance() 13 | try! self.ditto1.ditto?.startSync() 14 | try! self.ditto2.ditto?.startSync() 15 | } 16 | 17 | func testExample() async throws { 18 | let exeption = expectation(description: "doc inserted") 19 | let collectionName = "cars" 20 | 21 | // Inserting a car into 'ditto1' store 22 | let car = ["make": "toyota", "color": "red"] 23 | try await ditto1!.ditto!.store.execute( 24 | query: "INSERT INTO \(collectionName) DOCUMENTS (:car)", 25 | arguments: ["car": car] 26 | ) 27 | 28 | let selectQuery = "SELECT * FROM \(collectionName)" 29 | 30 | // Registering a subscription from 'ditto2' 31 | try ditto2.ditto!.sync.registerSubscription(query: selectQuery) 32 | 33 | // Registering a result observer on 'ditto2' store 34 | try ditto2.ditto!.store.registerObserver(query: selectQuery) { result in 35 | if let value = result.items.first?.value { 36 | XCTAssertEqual(value["make"] as! String, "toyota") 37 | exeption.fulfill() 38 | } 39 | } 40 | 41 | await fulfillment(of: [exeption], timeout: 5) 42 | } 43 | } 44 | 45 | 46 | func topLevelDittoDir() -> URL { 47 | let fileManager = FileManager.default 48 | return try! fileManager.url( 49 | for: .documentDirectory, 50 | in: .userDomainMask, 51 | appropriateFor: nil, 52 | create: false 53 | ).appendingPathComponent("ditto_top_level") 54 | } 55 | 56 | 57 | /// Test helper which wraps a Ditto instance. 58 | public class DittoInstance { 59 | internal var ditto: Ditto? 60 | private let instanceDir: URL 61 | 62 | public init() { 63 | let appID = "YOUR_LICENSE_HERE" 64 | let onlinePlaygroundToken = "YOUR_LICENSE_HERE" 65 | 66 | // No need for cleanup, as the TestsSetup class is configured as NSPrincipalClass 67 | // and will delete topLevelDittoDir() before any test job is run 68 | let instanceDir = topLevelDittoDir() 69 | .appendingPathComponent(appID) 70 | .appendingPathComponent(UUID().uuidString) 71 | 72 | self.instanceDir = instanceDir 73 | self.ditto = Ditto( 74 | identity: .onlinePlayground(appID: appID, token: onlinePlaygroundToken, enableDittoCloudSync: false), 75 | persistenceDirectory: instanceDir 76 | ) 77 | 78 | try! self.ditto!.disableSyncWithV3() 79 | } 80 | 81 | public func stop() { 82 | self.ditto!.stopSync() 83 | self.ditto = nil 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /testing/android/.run/Instrumented Tests.run.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 55 | -------------------------------------------------------------------------------- /testing/android/gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /testing/SwiftUI/.swiftpm/xcode/xcshareddata/xcschemes/SwiftUI.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 29 | 35 | 36 | 37 | 38 | 39 | 44 | 45 | 47 | 53 | 54 | 55 | 56 | 57 | 67 | 68 | 74 | 75 | 81 | 82 | 83 | 84 | 86 | 87 | 90 | 91 | 92 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Xcode 2 | # 3 | # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore 4 | # https://github.com/github/gitignore/blob/main/Swift.gitignore 5 | 6 | .DS_Store 7 | 8 | ## User settings 9 | xcuserdata/ 10 | 11 | ## compatibility with Xcode 8 and earlier (ignoring not required starting Xcode 9) 12 | *.xcscmblueprint 13 | *.xccheckout 14 | 15 | ## compatibility with Xcode 3 and earlier (ignoring not required starting Xcode 4) 16 | build/ 17 | DerivedData/ 18 | *.moved-aside 19 | *.pbxuser 20 | !default.pbxuser 21 | *.mode1v3 22 | !default.mode1v3 23 | *.mode2v3 24 | !default.mode2v3 25 | *.perspectivev3 26 | !default.perspectivev3 27 | 28 | ## Obj-C/Swift specific 29 | *.hmap 30 | 31 | ## App packaging 32 | *.ipa 33 | *.dSYM.zip 34 | *.dSYM 35 | 36 | ## Playgrounds 37 | timeline.xctimeline 38 | playground.xcworkspace 39 | 40 | # Swift Package Manager 41 | # 42 | # Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. 43 | # Packages/ 44 | # Package.pins 45 | # Package.resolved 46 | # *.xcodeproj 47 | # 48 | # Xcode automatically generates this directory with a .xcworkspacedata file and xcuserdata 49 | # hence it is not needed unless you have added a package configuration file to your project 50 | # .swiftpm 51 | 52 | .build/ 53 | 54 | # CocoaPods 55 | # 56 | # We recommend against adding the Pods directory to your .gitignore. However 57 | # you should judge for yourself, the pros and cons are mentioned at: 58 | # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control 59 | # 60 | # Pods/ 61 | # 62 | # Add this line if you want to avoid checking in source code from the Xcode workspace 63 | # *.xcworkspace 64 | 65 | # Carthage 66 | # 67 | # Add this line if you want to avoid checking in source code from Carthage dependencies. 68 | # Carthage/Checkouts 69 | 70 | Carthage/Build/ 71 | 72 | # Accio dependency management 73 | Dependencies/ 74 | .accio/ 75 | 76 | 77 | # Code Injection 78 | # 79 | # After new code Injection tools there's a generated folder /iOSInjectionProject 80 | # https://github.com/johnno1962/injectionforxcode 81 | 82 | iOSInjectionProject/ 83 | 84 | 85 | ############################################################ 86 | # Android # 87 | ############################################################ 88 | 89 | # Built application files 90 | *.apk 91 | *.aar 92 | *.ap_ 93 | *.aab 94 | 95 | # Files for the ART/Dalvik VM 96 | *.dex 97 | 98 | # Java class files 99 | *.class 100 | 101 | # Generated files 102 | gen/ 103 | out/ 104 | # Uncomment the following line in case you need and you don't have the release build type files in your app 105 | # release/ 106 | 107 | # Gradle files 108 | .gradle/ 109 | build/ 110 | 111 | # Local configuration file (sdk path, etc) 112 | local.properties 113 | 114 | # Proguard folder generated by Eclipse 115 | proguard/ 116 | 117 | # Log Files 118 | *.log 119 | 120 | # Android Studio Navigation editor temp files 121 | .navigation/ 122 | 123 | # Android Studio captures folder 124 | captures/ 125 | 126 | # IntelliJ 127 | *.iml 128 | *.idea* 129 | .idea/workspace.xml 130 | .idea/tasks.xml 131 | .idea/gradle.xml 132 | .idea/assetWizardSettings.xml 133 | .idea/dictionaries 134 | .idea/libraries 135 | # Android Studio 3 in .gitignore file. 136 | .idea/caches 137 | .idea/modules.xml 138 | # Comment next line if keeping position of elements in Navigation Editor is relevant for you 139 | .idea/navEditor.xml 140 | 141 | # Keystore files 142 | # Uncomment the following lines if you do not want to check your keystore files in. 143 | #*.jks 144 | #*.keystore 145 | 146 | # External native build folder generated in Android Studio 2.2 and later 147 | .externalNativeBuild 148 | .cxx/ 149 | 150 | # Google Services (e.g. APIs or Firebase) 151 | # google-services.json 152 | 153 | # Freeline 154 | freeline.py 155 | freeline/ 156 | freeline_project_description.json 157 | 158 | ## fastlane -------------- 159 | # It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the 160 | # screenshots whenever they are needed. 161 | # For more information about the recommended setup visit: 162 | # https://docs.fastlane.tools/best-practices/source-control/#source-control 163 | fastlane/report.xml 164 | fastlane/Preview.html 165 | fastlane/screenshots 166 | fastlane/test_output 167 | fastlane/readme.md 168 | 169 | # Version control 170 | vcs.xml 171 | 172 | # lint 173 | lint/intermediates/ 174 | lint/generated/ 175 | lint/outputs/ 176 | lint/tmp/ 177 | # lint/reports/ 178 | /tasks/jetpack-compose/secure/debug_creds.properties 179 | 180 | cpp/main 181 | libditto.a 182 | Ditto.tar.gz 183 | -------------------------------------------------------------------------------- /testing/android/app/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 10 | 15 | 20 | 25 | 30 | 35 | 40 | 45 | 50 | 55 | 60 | 65 | 70 | 75 | 80 | 85 | 90 | 95 | 100 | 105 | 110 | 115 | 120 | 125 | 130 | 135 | 140 | 145 | 150 | 155 | 160 | 165 | 170 | 171 | -------------------------------------------------------------------------------- /testing/android/gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | 86 | # Determine the Java command to use to start the JVM. 87 | if [ -n "$JAVA_HOME" ] ; then 88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 89 | # IBM's JDK on AIX uses strange locations for the executables 90 | JAVACMD="$JAVA_HOME/jre/sh/java" 91 | else 92 | JAVACMD="$JAVA_HOME/bin/java" 93 | fi 94 | if [ ! -x "$JAVACMD" ] ; then 95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 96 | 97 | Please set the JAVA_HOME variable in your environment to match the 98 | location of your Java installation." 99 | fi 100 | else 101 | JAVACMD="java" 102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 103 | 104 | Please set the JAVA_HOME variable in your environment to match the 105 | location of your Java installation." 106 | fi 107 | 108 | # Increase the maximum file descriptors if we can. 109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 110 | MAX_FD_LIMIT=`ulimit -H -n` 111 | if [ $? -eq 0 ] ; then 112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 113 | MAX_FD="$MAX_FD_LIMIT" 114 | fi 115 | ulimit -n $MAX_FD 116 | if [ $? -ne 0 ] ; then 117 | warn "Could not set maximum file descriptor limit: $MAX_FD" 118 | fi 119 | else 120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 121 | fi 122 | fi 123 | 124 | # For Darwin, add options to specify how the application appears in the dock 125 | if $darwin; then 126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 127 | fi 128 | 129 | # For Cygwin or MSYS, switch paths to Windows format before running java 130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 133 | 134 | JAVACMD=`cygpath --unix "$JAVACMD"` 135 | 136 | # We build the pattern for arguments to be converted via cygpath 137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 138 | SEP="" 139 | for dir in $ROOTDIRSRAW ; do 140 | ROOTDIRS="$ROOTDIRS$SEP$dir" 141 | SEP="|" 142 | done 143 | OURCYGPATTERN="(^($ROOTDIRS))" 144 | # Add a user-defined pattern to the cygpath arguments 145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 147 | fi 148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 149 | i=0 150 | for arg in "$@" ; do 151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 153 | 154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 156 | else 157 | eval `echo args$i`="\"$arg\"" 158 | fi 159 | i=`expr $i + 1` 160 | done 161 | case $i in 162 | 0) set -- ;; 163 | 1) set -- "$args0" ;; 164 | 2) set -- "$args0" "$args1" ;; 165 | 3) set -- "$args0" "$args1" "$args2" ;; 166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 172 | esac 173 | fi 174 | 175 | # Escape application args 176 | save () { 177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 178 | echo " " 179 | } 180 | APP_ARGS=`save "$@"` 181 | 182 | # Collect all arguments for the java command, following the shell quoting and substitution rules 183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 184 | 185 | exec "$JAVACMD" "$@" 186 | -------------------------------------------------------------------------------- /testing/android/app/src/androidTest/java/live/ditto/dittotesting/DittoTestBase.kt: -------------------------------------------------------------------------------- 1 | package live.ditto.dittotesting 2 | 3 | import android.content.Context 4 | import android.util.Log 5 | import androidx.test.platform.app.InstrumentationRegistry 6 | import live.ditto.DittoDependencies 7 | import live.ditto.android.DefaultAndroidDittoDependencies 8 | import live.ditto.android.TestAndroidDittoDependencies 9 | import org.junit.AssumptionViolatedException 10 | import org.junit.Before 11 | import org.junit.rules.TestRule 12 | import org.junit.runner.Description 13 | import org.junit.runners.model.Statement 14 | import java.io.BufferedReader 15 | import java.io.File 16 | import java.io.IOException 17 | import java.io.InputStreamReader 18 | 19 | /** 20 | * Android-specific test base class 21 | */ 22 | open class DittoTestBase { 23 | @JvmField 24 | val context: Context = InstrumentationRegistry.getInstrumentation().targetContext 25 | 26 | @JvmField 27 | var dependencies: DittoDependencies = TestAndroidDittoDependencies(context) 28 | 29 | @Before 30 | open fun initialize() { 31 | dependencies = TestAndroidDittoDependencies(context) 32 | clearUpDittoDirectories(context) 33 | } 34 | 35 | companion object { 36 | @JvmField 37 | val LOCK: Any = Any() 38 | } 39 | 40 | /** 41 | * Returns a directory suitable for storing files generated by the test. Android tests use the 42 | * app Context to find the files directory on the device or emulator. 43 | */ 44 | fun getWorkDir(): File = context.filesDir 45 | 46 | /** 47 | * Creates a set of Android dependencies combining defaults with a custom directory. 48 | */ 49 | fun dependenciesWithCustomDirectory(customDir: File): DittoDependencies { 50 | val dependencies = DefaultAndroidDittoDependencies(context) 51 | return CustomDirectoryAndroidDittoDependencies(dependencies, customDir) 52 | } 53 | } 54 | 55 | const val LOGCAT_HEADER = "\n==================== Logcat Output ====================" 56 | const val STACKTRACE_HEADER = "\n===================== Stacktrace =====================" 57 | const val ORIGINAL_CLASS_HEADER = "\nOriginal class: " 58 | 59 | class CaptureLogcatOnTestFailureRule : TestRule { 60 | override fun apply(statement: Statement, description: Description): Statement { 61 | return object : Statement() { 62 | override fun evaluate() { 63 | try { 64 | // Runs the statement as given by the TestRunner 65 | statement.evaluate() 66 | } catch (originalThrowable: Throwable) { 67 | if (originalThrowable is AssumptionViolatedException) { 68 | // Test runners know to skip this type of failure 69 | throw originalThrowable 70 | } 71 | 72 | val logcatMessage = getRelevantLogsAfterTestStart(description.methodName).toString() 73 | 74 | // We put out own custom message into the throwable, making sure to keep the 75 | // original message in place. 76 | val originalMsg = originalThrowable.localizedMessage 77 | val originalClass = originalThrowable.javaClass.name 78 | val thrownMessage = "$originalMsg $ORIGINAL_CLASS_HEADER $originalClass $LOGCAT_HEADER $logcatMessage $STACKTRACE_HEADER" 79 | 80 | // Create a throwable with the same stacktrace as the actual failure. By using 81 | // the original stacktrace this logcat addition is a transparent process to 82 | // anyone reading the test failure report. 83 | val modifiedThrowable = Throwable(thrownMessage) 84 | 85 | // Since our Throwable doesn't know about the original error, we have to give it 86 | // that information via our custom message and pass it a stacktrace explicitly. 87 | modifiedThrowable.stackTrace = originalThrowable.stackTrace 88 | throw modifiedThrowable 89 | } 90 | } 91 | } 92 | } 93 | } 94 | 95 | fun getRelevantLogsAfterTestStart(testName: String): StringBuilder { 96 | val builder = StringBuilder() 97 | 98 | // The process id is used to filter the messages. This TestRunner and the test itself run in the 99 | // same process. 100 | val currentProcessId = android.os.Process.myPid().toString() 101 | 102 | // A snippet of text that uniquely determines where the relevant logs start in the logcat. 103 | val testStartMessage = "TestRunner: started: $testName" 104 | 105 | // Flag that, when true, starts the recording of every line from the buffer to the string 106 | // builder. 107 | var isRecording = false 108 | 109 | // Our logcat command 110 | // 111 | // -d states for the command to completely dump to our buffer, then return 112 | // -v threadtime sets the output log format 113 | val command = listOf("logcat", "-d", "-v", "threadtiime").toTypedArray() 114 | 115 | var bufferedReader: BufferedReader? = null 116 | try { 117 | val process = Runtime.getRuntime().exec(command) 118 | bufferedReader = BufferedReader(InputStreamReader(process.inputStream)) 119 | 120 | bufferedReader.forEachLine { line -> 121 | if (line.contains(currentProcessId)) { 122 | if (line.contains(testStartMessage)) { 123 | isRecording = true 124 | } 125 | if (isRecording) { 126 | builder.append(line) 127 | builder.append("\n") 128 | } 129 | } 130 | } 131 | } catch (ex: IOException) { 132 | Log.e("DittoTestBase", "Failed to run logcat command: ${ex.localizedMessage}") 133 | } finally { 134 | if (bufferedReader != null) { 135 | try { 136 | bufferedReader.close() 137 | } catch (ex: IOException) { 138 | Log.e("DittoTestBase", "Failed to close buffered reader: ${ex.localizedMessage}") 139 | } 140 | } 141 | } 142 | 143 | // Once the logcat is cleared, the next run of this logcat reader will have a much shorter 144 | // buffer to deal with, resulting in a faster read time. 145 | clearLogcat() 146 | return builder 147 | } 148 | 149 | // TODO: Unsure if this is what this is supposed to do... 150 | fun clearLogcat() { 151 | val command = listOf("logcat", "-b", "all", "-c").toTypedArray() 152 | val process = Runtime.getRuntime().exec(command) 153 | process.waitFor() 154 | } --------------------------------------------------------------------------------