Compare commits

..
Author SHA1 Message Date
tobiasKaminsky fb969cc6a8 wip
Signed-off-by: tobiasKaminsky <[email protected]>
2020-01-10 20:19:58 +01:00
tobiasKaminsky aaba0a8a53 Fix unittests
Signed-off-by: tobiasKaminsky <[email protected]>
2020-01-10 14:35:05 +01:00
tobiasKaminsky 688a44dd61 remove annotation
Signed-off-by: tobiasKaminsky <[email protected]>
2020-01-10 14:35:05 +01:00
tobiasKaminsky 1e2cbff1c8 fix during CI
Signed-off-by: tobiasKaminsky <[email protected]>
2020-01-10 14:35:05 +01:00
tobiasKaminsky 6da3a0766b update tests
Signed-off-by: tobiasKaminsky <[email protected]>
2020-01-10 14:35:05 +01:00
tobiasKaminsky ebf22f67d2 test CreateFolderOperation without server
Signed-off-by: tobiasKaminsky <[email protected]>
2020-01-10 14:35:05 +01:00
730 changed files with 16767 additions and 29081 deletions

No files matched your search

+16 -71
View File
@@ -1,36 +1,18 @@
---
kind: pipeline
type: docker
name: gplay-stable
name: generic
steps:
- name: gplay
- name: generic
image: nextcloudci/android:android-49
privileged: true
environment:
LOG_USERNAME:
from_secret: LOG_USERNAME
LOG_PASSWORD:
from_secret: LOG_PASSWORD
GIT_USERNAME:
from_secret: GIT_USERNAME
GIT_TOKEN:
from_secret: GIT_TOKEN
ORG_GRADLE_PROJECT_coverage: ''
commands:
- scripts/checkIfRunDrone.sh $GIT_USERNAME $GIT_TOKEN $DRONE_PULL_REQUEST || exit 0
- emulator-headless -avd android-27 -no-snapshot -gpu swiftshader_indirect -no-window -no-audio -skin 500x833 &
- sed -i s'#<bool name="is_beta">false</bool>#<bool name="is_beta">true</bool>#'g src/main/res/values/setup.xml
- sed -i s"#server#server-stable#" gradle.properties
- ./gradlew assembleGplay
- ./gradlew assembleGplayDebug
- scripts/wait_for_emulator.sh
- ./gradlew jacocoTestGplayDebugUnitTestReport || scripts/uploadReport.sh $LOG_USERNAME $LOG_PASSWORD $DRONE_BUILD_NUMBER "stable-Unit" $DRONE_PULL_REQUEST $GIT_USERNAME $GIT_TOKEN
- ./gradlew installGplayDebugAndroidTest
- scripts/wait_for_server.sh "server-stable"
- ./gradlew createGplayDebugCoverageReport || scripts/uploadReport.sh $LOG_USERNAME $LOG_PASSWORD $DRONE_BUILD_NUMBER "stable-IT" $DRONE_PULL_REQUEST $GIT_USERNAME $GIT_TOKEN
- ./gradlew executeScreenshotTests || scripts/uploadReport.sh $LOG_USERNAME $LOG_PASSWORD $DRONE_BUILD_NUMBER "stable-Screenshot" $DRONE_PULL_REQUEST $GIT_USERNAME $GIT_TOKEN
- ./gradlew combinedTestReport
- ./gradlew assembleGeneric
- name: notify
image: drillster/drone-email
settings:
@@ -45,6 +27,10 @@ steps:
from_secret: EMAIL_RECIPIENTS
host:
from_secret: EMAIL_HOST
GIT_USERNAME:
from_secret: GIT_USERNAME
GIT_TOKEN:
from_secret: GIT_TOKEN
when:
event:
- push
@@ -53,35 +39,16 @@ steps:
branch:
- master
services:
- name: server-stable
image: nextcloudci/server:server-17 # also change in updateScreenshots.sh
commands:
- BRANCH='stable18' /usr/local/bin/initnc.sh
- su www-data -c "OC_PASS=user1 php /var/www/html/occ user:add --password-from-env --display-name='User One' user1"
- su www-data -c "OC_PASS=user2 php /var/www/html/occ user:add --password-from-env --display-name='User Two' user2"
- su www-data -c "OC_PASS=user3 php /var/www/html/occ user:add --password-from-env --display-name='User Three' user3"
- su www-data -c "php /var/www/html/occ user:setting user2 files quota 1G"
- su www-data -c "php /var/www/html/occ group:add users"
- su www-data -c "php /var/www/html/occ group:adduser users user1"
- su www-data -c "php /var/www/html/occ group:adduser users user2"
- su www-data -c "git clone -b stable18 https://github.com/nextcloud/activity.git /var/www/html/apps/activity/"
- su www-data -c "php /var/www/html/occ app:enable activity"
- su www-data -c "git clone -b stable18 https://github.com/nextcloud/text.git /var/www/html/apps/text/"
- su www-data -c "php /var/www/html/occ app:enable text"
- su www-data -c "php /var/www/html/occ app:enable end_to_end_encryption"
- /usr/local/bin/run.sh
trigger:
branch:
- master
event:
- push
- pull_request
- push
---
kind: pipeline
type: docker
name: gplay-master
name: gplay
steps:
- name: gplay
@@ -100,16 +67,13 @@ steps:
commands:
- scripts/checkIfRunDrone.sh $GIT_USERNAME $GIT_TOKEN $DRONE_PULL_REQUEST || exit 0
- emulator-headless -avd android-27 -no-snapshot -gpu swiftshader_indirect -no-window -no-audio -skin 500x833 &
- sed -i s'#<bool name="is_beta">false</bool>#<bool name="is_beta">true</bool>#'g src/main/res/values/setup.xml
- sed -i s"#server#server-master#" gradle.properties
- ./gradlew assembleGplay
- ./gradlew assembleGplayDebug
- scripts/wait_for_emulator.sh
- ./gradlew jacocoTestGplayDebugUnitTestReport || scripts/uploadReport.sh $LOG_USERNAME $LOG_PASSWORD $DRONE_BUILD_NUMBER "master-Unit" $DRONE_PULL_REQUEST $GIT_USERNAME $GIT_TOKEN
- ./gradlew jacocoTestGplayDebugUnitTestReport || scripts/uploadReport.sh $LOG_USERNAME $LOG_PASSWORD $DRONE_BUILD_NUMBER "Unit" $DRONE_PULL_REQUEST $GIT_USERNAME $GIT_TOKEN
- ./gradlew installGplayDebugAndroidTest
- scripts/wait_for_server.sh "server-master"
- ./gradlew createGplayDebugCoverageReport || scripts/uploadReport.sh $LOG_USERNAME $LOG_PASSWORD $DRONE_BUILD_NUMBER "master-IT" $DRONE_PULL_REQUEST $GIT_USERNAME $GIT_TOKEN
- ./gradlew executeScreenshotTests || scripts/uploadReport.sh $LOG_USERNAME $LOG_PASSWORD $DRONE_BUILD_NUMBER "master-Screenshot" $DRONE_PULL_REQUEST $GIT_USERNAME $GIT_TOKEN
- ./gradlew createGplayDebugCoverageReport || scripts/uploadReport.sh $LOG_USERNAME $LOG_PASSWORD $DRONE_BUILD_NUMBER "IT" $DRONE_PULL_REQUEST $GIT_USERNAME $GIT_TOKEN
- ./gradlew executeScreenshotTests || scripts/uploadReport.sh $LOG_USERNAME $LOG_PASSWORD $DRONE_BUILD_NUMBER "Screenshot" $DRONE_PULL_REQUEST $GIT_USERNAME $GIT_TOKEN
- ./gradlew combinedTestReport
- curl -o codecov.sh https://codecov.io/bash
- bash ./codecov.sh -t fc506ba4-33c3-43e4-a760-aada38c24fd5
@@ -136,25 +100,8 @@ steps:
- master
services:
- name: server-master
image: nextcloudci/server:server-17 # also change in updateScreenshots.sh
commands:
- /usr/local/bin/initnc.sh
- su www-data -c "php /var/www/html/occ status"
- su www-data -c "OC_PASS=user1 php /var/www/html/occ user:add --password-from-env --display-name='User One' user1"
- su www-data -c "OC_PASS=user2 php /var/www/html/occ user:add --password-from-env --display-name='User Two' user2"
- su www-data -c "OC_PASS=user3 php /var/www/html/occ user:add --password-from-env --display-name='User Three' user3"
- su www-data -c "php /var/www/html/occ user:setting user2 files quota 1G"
- su www-data -c "php /var/www/html/occ group:add users"
- su www-data -c "php /var/www/html/occ group:adduser users user1"
- su www-data -c "php /var/www/html/occ group:adduser users user2"
- su www-data -c "git clone -b master https://github.com/nextcloud/activity.git /var/www/html/apps/activity/"
- su www-data -c "php /var/www/html/occ app:enable activity"
- su www-data -c "git clone -b master https://github.com/nextcloud/text.git /var/www/html/apps/text/"
- su www-data -c "php /var/www/html/occ app:enable text"
- su www-data -c "git clone -b master https://github.com/nextcloud/end_to_end_encryption/ /var/www/html/apps/end_to_end_encryption/"
- su www-data -c "php /var/www/html/occ app:enable end_to_end_encryption"
- /usr/local/bin/run.sh
- name: server
image: nextcloudci/server:server-3
trigger:
branch:
@@ -164,7 +111,6 @@ trigger:
- pull_request
---
kind: pipeline
type: docker
name: analysis
steps:
@@ -214,7 +160,6 @@ trigger:
- pull_request
---
kind: pipeline
type: docker
name: qa
steps:
-7
View File
@@ -16,11 +16,6 @@ labels: bug
### Actual behaviour
- Tell us what happens
### Can you reproduce this problem on https://try.nextcloud.com?
- Please create a test demo account and see if this still happens there.
- If yes, please open up a bug report
- If not, please verify server setup and ask for help on forum
### Environment data
Android version:
@@ -32,8 +27,6 @@ Nextcloud app version:
Nextcloud server version:
Reverse proxy:
### Logs
#### Web server error log
```
-9
View File
@@ -1,9 +0,0 @@
### Testing
Writing tests is very important. Please try to write some tests for your PR.
If you need help, please do not hesitate to ask in this PR for help.
[unit tests](https://github.com/nextcloud/android/blob/master/CONTRIBUTING.md#unit-tests)
[instrumented tests](https://github.com/nextcloud/android/blob/master/CONTRIBUTING.md#instrumented-tests)
[UI tests](https://github.com/nextcloud/android/blob/master/CONTRIBUTING.md#ui-tests)
- [ ] Tests written, or not not needed
+8 -6
View File
@@ -2,17 +2,19 @@
daysUntilStale: 28
# Number of days of inactivity before a stale issue is closed
daysUntilClose: 14
# Only issues or pull requests with all of these labels are check if stale. Defaults to `[]` (disabled)
onlyLabels:
- bug
- "needs info/discussion"
# Issues with these labels will never be considered stale
exemptLabels: []
exemptLabels:
- 1. developing
- 2. to review
- 3. to release
- approved
- enhancement
- overview
# Label to use when marking an issue as stale
staleLabel: stale
# Comment to post when marking an issue as stale. Set to `false` to disable
markComment: >
This bug report did not receive an update in the last 4 weeks.
This request did not receive an update in the last 4 weeks.
Please take a look again and update the issue with new details,
otherwise the issue will be automatically closed in 2 weeks. Thank you!
# Comment to post when closing a stale issue. Set to `false` to disable
-20
View File
@@ -1,20 +0,0 @@
name: Detekt
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
jobs:
detekt:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up JDK 1.8
uses: actions/setup-java@v1
with:
java-version: 1.8
- name: Runt detekt
run: ./gradlew detekt
-25
View File
@@ -1,25 +0,0 @@
name: "Gplay Flavor"
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
jobs:
gPlayFlavor:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: set up JDK 1.8
uses: actions/setup-java@v1
with:
java-version: 1.8
- name: Install NDK
run: echo "y" | sudo /usr/local/lib/android/sdk/tools/bin/sdkmanager --install "ndk;20.0.5594570" --sdk_root=${ANDROID_SDK_ROOT}
- name: Build with Gradle
run: |
mkdir -p $HOME/.gradle
echo "org.gradle.jvmargs=-Xmx2g -XX:MaxMetaspaceSize=512m -XX:+HeapDumpOnOutOfMemoryError" > $HOME/.gradle/gradle.properties
./gradlew assembleGplay
-25
View File
@@ -1,25 +0,0 @@
name: "Generic Flavor"
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
jobs:
genericFlavor:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: set up JDK 1.8
uses: actions/setup-java@v1
with:
java-version: 1.8
- name: Install NDK
run: echo "y" | sudo /usr/local/lib/android/sdk/tools/bin/sdkmanager --install "ndk;20.0.5594570" --sdk_root=${ANDROID_SDK_ROOT}
- name: Build generic
run: |
mkdir -p $HOME/.gradle
echo "org.gradle.jvmargs=-Xmx2g -XX:MaxMetaspaceSize=512m -XX:+HeapDumpOnOutOfMemoryError" > $HOME/.gradle/gradle.properties
./gradlew assembleGeneric
@@ -1,15 +0,0 @@
name: "Validate Gradle Wrapper"
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
jobs:
validation:
name: "Validation"
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: gradle/wrapper-validation-action@v1
-20
View File
@@ -1,20 +0,0 @@
name: KtLint
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
jobs:
ktlint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up JDK 1.8
uses: actions/setup-java@v1
with:
java-version: 1.8
- name: Runt ktlint
run: ./gradlew ktlint
+4 -8
View File
@@ -29,6 +29,9 @@
</option>
<option name="RIGHT_MARGIN" value="120" />
<option name="WRAP_WHEN_TYPING_REACHES_RIGHT_MARGIN" value="true" />
<AndroidXmlCodeStyleSettings>
<option name="ARRANGEMENT_SETTINGS_MIGRATED_TO_191" value="true" />
</AndroidXmlCodeStyleSettings>
<JavaCodeStyleSettings>
<option name="IMPORT_LAYOUT_TABLE">
<value>
@@ -70,7 +73,6 @@
</XML>
<codeStyleSettings language="JAVA">
<option name="ALIGN_MULTILINE_PARAMETERS_IN_CALLS" value="true" />
<option name="ALIGN_MULTILINE_METHOD_BRACKETS" value="true" />
<option name="WRAP_COMMENTS" value="true" />
<option name="IF_BRACE_FORCE" value="3" />
<option name="DOWHILE_BRACE_FORCE" value="3" />
@@ -78,9 +80,6 @@
<option name="FOR_BRACE_FORCE" value="3" />
<option name="FIELD_ANNOTATION_WRAP" value="0" />
</codeStyleSettings>
<codeStyleSettings language="Markdown">
<option name="RIGHT_MARGIN" value="120" />
</codeStyleSettings>
<codeStyleSettings language="XML">
<indentOptions>
<option name="CONTINUATION_INDENT_SIZE" value="4" />
@@ -193,8 +192,5 @@
</rules>
</arrangement>
</codeStyleSettings>
<codeStyleSettings language="kotlin">
<option name="ALIGN_MULTILINE_METHOD_BRACKETS" value="true" />
</codeStyleSettings>
</code_scheme>
</component>
</component>
+3 -47
View File
@@ -1,61 +1,17 @@
## 3.11.1 (April, 23, 2020)
- Crash while browsing files
- auto upload:
- fix wrong conflict detection on custom folder
- allow to choose default conflict strategy @fodinabor
- fix hanging UI after saving
- open office files online if no local app installed
For a full list, please see https://github.com/nextcloud/android/milestone/47
## 3.11.0 (March, 26, 2020)
- not enough space dialog @Shagequi
- fix shared search
- upload existing images in auto upload @koying @ArisuOngaku
- allow deep links @Charon77
- support for circle
- last version supporting Android 4.1
For a full list, please see https://github.com/nextcloud/android/milestone/41
## 3.10.1 (February, 05, 2020)
- fix crash on self-signed certificates
- fix openOffice open files with special chars
For a full list, please see https://github.com/nextcloud/android/milestone/45
## 3.10.0 (January, 17, 2020)
- Dark theme (@dan0xii, @AndyScherzinger)
- Rich workspace (NC18+)
- collaborative text editor (NC18+)
- links in Markdown previews clickable (@AndyScherzinger)
- Show/Hide auto upload list items (@AndyScherzinger)
- drop 4.0.x support
- outdated server warning set to NC15
- latest supported version NC13
For a full list, please see https://github.com/nextcloud/android/milestone/40
## 3.9.2 (December, 05, 2019)
3.9.2 (December, 05, 2019)
- HOTFIX: fix login loop
- Fix crash on opening png images
- Translation updates
For a full list, please see https://github.com/nextcloud/android/milestone/44
## 3.9.1 (December, 04, 2019)
3.9.1 (December, 04, 2019)
- Fix crash on opening png images
- Translation updates
For a full list, please see https://github.com/nextcloud/android/milestone/43
## 3.9.0 (November, 12, 2019)
3.9.0 (November, 12, 2019)
- preview Markdown with syntax highlighting @AndyScherzinger
- improved DavX5 integration @bitfireAT
+40 -180
View File
@@ -5,46 +5,40 @@
# Index
1. [Guidelines](#guidelines)
1. [Issue reporting](#issue-reporting)
1. [Labels](#labels)
1. [Pull request](#pull-request)
1. [Issue](#issue)
1. [Bug workflow](#bug-workflow)
1. [Contributing to Source Code](#contributing-to-source-code)
1. [Developing process](#developing-process)
1. [Branching model](#branching-model)
1. [Android Studio formatter setup](#android-studio-formatter-setup)
1. [Build variants](#build-variants)
1. [Contribution process](#contribution-process)
1. [Fork and download android repository](#fork-and-download-android-repository)
1. [Create pull request](#create-pull-request)
1. [Create another pull request](#create-another-pull-request)
1. [Backport pull request](#backport-pull-request)
1. [Pull requests that also need changes on library](#pull-requests-that-also-need-changes-on-library)
1. [Adding new files](#adding-new-files)
1. [Testing](#testing)
1. [File naming](#file-naming)
1. [Menu files](#menu-files)
1. [Translations](#translations)
1. [Engineering practices](#engineering-practices)
1. [Approach to technical debt](#approach-to-technical-debt)
1. [Dependency injection](#dependency-injection)
1. [Custom platform APIs](#custom-platform-apis)
1. [Testing](#testing)
1. [Releases](#releases)
1. [Types](#types)
1. [Stable](#stable)
1. [Release Candidate](#release-candidate)
1. [Dev](#dev)
1. [Version Name and number](#version-name-and-number)
1. [Stable / Release candidate](#stable-release-candidate)
1. [Dev](#dev)
1. [Release cycle](#release-cycle)
1. [Release Process](#release-process)
1. [Stable Release](#stable-release)
1. [Release Candidate Release](#release-candidate-release)
1. [Development Dev](#development-dev)
1. Guidelines
1. Issue reporting
1. Labels
1. Pull request (PR)
1. Issue
1. Bug workflow
1. Contributing to Source Code
1. Developing process
1. Branching model
1. Android Studio formatter setup
1. Build variants
1. Contribution process
1. Fork and download android/master repository
1. Create pull request
1. Create another pull request
1. Backport pull request
1. Pull requests that also need changes on library
1. Adding new files
1. File naming
1. Menu files
1. Translations
1. Releases
1. Types
1. Stable
1. Release Candidate
1. Dev
1. Version Name and number
1. Stable / Release candidate
1. Dev
1. Release cycle
1. Release Process
1. Stable Release
1. Release Candidate Release
1. Development Dev
# Guidelines
@@ -72,7 +66,6 @@ If your issue appears to be a bug, and hasn't been reported, open a new issue.
### Bug workflow
Every bug should be triaged in approved/needs info in a given time.
* approved: at least one other is able to reproduce it
* needs info: something unclear, or not able to reproduce
* if no response within 1 months, bug will be closed
@@ -124,18 +117,18 @@ There are three build variants
* For your first contribution start a pull request on master.
### Fork and download android repository:
### 1. Fork and download android/master repository:
* Please follow [SETUP.md](https://github.com/nextcloud/android/blob/master/SETUP.md) to setup Nextcloud Android app work environment.
### Create pull request:
### 2. Create pull request:
* Commit your changes locally: ```git commit -a```
* Push your changes to your GitHub repo: ```git push```
* Browse to <https://github.com/YOURGITHUBNAME/android/pulls> and issue pull request
* Enter description and send pull request.
### Create another pull request:
### 3. Create another pull request:
To make sure your new pull request does not contain commits which are already contained in previous PRs, create a new branch which is a clone of upstream/master.
* ```git fetch upstream```
@@ -144,12 +137,12 @@ To make sure your new pull request does not contain commits which are already co
* Push branch to server: ```git push -u origin name_of_local_master_branch```
* Use GitHub to issue PR
### Backport pull request:
### 4. Backport pull request:
Use backport-bot via "/backport to stable-version", e.g. "/backport to stable-3.7".
This will automatically add "backport-request" label to PR and bot will create a new PR to targeted branch once the base PR is merged.
If automatic backport fails, it will create a comment.
### Pull requests that also need changes on library
### 5. Pull requests that also need changes on library
For speeding up developing, we do use a master snapshot of nextcloud-library, provided by jitpack.io.
This means that if a breaking change is merged on library, master branch of the app will fail.
To limit this risk please follow this approach:
@@ -163,7 +156,7 @@ Once both PRs are reviewed and ready to merge:
With this approach the "downtime" of not building master is limited to the timestamp between merge lib PR and merging app PR, which is only limited by CI.
### Adding new files
### 6. Adding new files
If you create a new file it needs to contain a license header. We encourage you to use the same license (AGPL3+) as we do.
Copyright of Nextcloud GmbH is optional.
@@ -245,56 +238,6 @@ Source code of app:
-->
```
### Testing
- testing is very important, but is lacking a lot on this project. Starting with 2020 we aim to write tests for every
new pull request.
- Code coverage can be found [here](https://codecov.io/gh/nextcloud/android).
#### Unit tests
- small, isolated tests, with no need of Android SDK
- code coverage can be directly shown via right click on test and select "Run Test with Coverage"
#### Instrumented tests
- tests to see larger code working in correct way
- tests that require parts of Android SDK
- best to avoid server communication, see https://github.com/nextcloud/android/pull/3624
- run all tests ```./gradlew createGplayDebugCoverageReport -Pcoverage=true```
- run selective test class: ```./gradlew createGplayDebugCoverageReport -Pcoverage=true
-Pandroid.testInstrumentationRunnerArguments.class=com.owncloud.android.datamodel.FileDataStorageManagerTest```
- run multiple test classes:
- separate by ","
- ```./gradlew createGplayDebugCoverageReport -Pcoverage=true -Pandroid.testInstrumentationRunnerArguments.class=com.owncloud.android.datamodel.FileDataStorageManagerTest,com.nextcloud.client.FileDisplayActivityIT```
- run one test in class: ```./gradlew createGplayDebugCoverageReport -Pcoverage=true
-Pandroid.testInstrumentationRunnerArguments.class=com.owncloud.android.datamodel.FileDataStorageManagerTest#saveNewFile```
- JaCoCo results are shown as html: firefox ./build/reports/coverage/gplay/debug/index.html
#### UI tests
We use [shot](https://github.com/Karumi/Shot) for taking screenshots and compare them
- check screenshots: ```./gradlew executeScreenshotTests ```
- update/generate new screenshots: ```scripts/updateScreenshots.sh ```
- in this script are samples how to only execute a given class/test
- this will fire up docker & emulator to ensure that screenshots look the same
- creating own UI comparision tests:
- add IntentsTestRule for launching activity directly:
```java
@Rule public IntentsTestRule<SettingsActivity> activityRule = new IntentsTestRule<>(SettingsActivity.class,
true,
false);
```
- in test method:
```java
Activity activity = activityRule.launchActivity(null);
…do something, e.g. navigate, create folder, etc. …
Screenshot.snapActivity(activity).record();
```
- best practise is to first create test with emulator too see behaviour and then create screenshots
## File naming
The file naming patterns are inspired and based on [Ribot's Android Project And Code Guidelines](https://github.com/ribot/android-guidelines/blob/c1d8c9c904eb31bf01fe24aadb963b74281fe79a/project_and_code_guidelines.md).
@@ -314,95 +257,12 @@ Similar to layout files, menu files should match the name of the component. For
A good practice is to not include the word `menu` as part of the name because these files are already located in the `menu` directory. In case a component uses several menus in different places (via popup menus) then the resource name would be extended. For example, if the user profile activity has two popup menus for configuring the users settings and one for the handling group assignments then the file names for the menus would be: `activity_user_profile_user_settings.xml` and `activity_user_profile_group_assignments.xml`.
## Translations
We manage translations via [Transifex](https://www.transifex.com/nextcloud/nextcloud/android/). So just request joining the translation team for Android on the site and start translating. All translations will then be automatically pushed to this repository, there is no need for any pull request for translations.
If you need to change a translation, do not change it, but give it new key. This way the translation stays backward compatible as we automatically backport translated strings to last versions.
When submitting PRs with changed translations, please only submit changes to values/strings.xml and not changes to translated files. These will be overwritten by next merge of transifex-but and increase PR review.
## Engineering practices
This section contains some general guideliens for new contributors, based on common issues flagged during code review.
### Approach to technical debt
TL;DR Non-Stop Litter Picking Party!
We recognize the importance of technical debt that can slow down development, make bufixing difficult and
discourage future contributors.
We are mindful of the [Broken Windows Theory](https://en.wikipedia.org/wiki/Broken_windows_theory) and we'd like
actively promote and encourage contributors to apply The Scout's Rule: *"Always leave the campground cleaner than
you found it"*. Simple, little improvements will sum up and will be very appreciated by Nextcloud team.
We also promise to actively support and mentor contributors that help us to improve code quality, as we understand
that this process is challenging and requires deep understanding of the application codebase.
### Dependency injection
TL;DR Avoid calling constructors inside constructors.
In effort to modernize the codebase we are applying [Dependency Injection](https://en.wikipedia.org/wiki/Dependency_injection)
whenever possible. We use 2 approaches: automatic and manual.
We are using [Dagger 2](https://dagger.dev/) to inject dependencies into major Android components only:
* `Activity`
* `Fragment`
* `Service`
* `BroadcastReceiver`
* `ContentProvider`
This process is fairly automatic, with `@Inject` annotation being sufficient to supply properly initialized
objects. Android lifecycle callbacks allow us to do most of the work without effort.
For other application sub-components we prefer to use constructor injection and manually provide required dependencies.
This combination allows us to benefit from automation when it provides most value, does not tie rest of the code
to any specific framework and stimulates continuous code modernization through iterative refactoring of all minor
elements.
### Custom platform APIs
TL;DR Avoid Android platform APIs.
Nextcloud Android application provides some replacements for native Android APIs to facilitate testing
and expose higher-level, business-specific APIs.
Generally, whenever you need:
* account management
* application preferences
* background task scheduling
* device hardware information
* media playback
* networking
* logging
we have something more suitable.
Our transition to new APIs is a continuous process. Contributors might be asked by code reviewers to
refrain from using specific Android APIs considered problematic and to use Nextcloud APIs instead.
In extreme cases we might decide to put specific features on hold until we provide platform API
replacement.
If in doubt, ask Nextcloud developers. App undergoes a process of intense refactoring and situation
changes frequently.
### Testing
TL;DR If we can't write a test for it, it's not good.
Test automation is challenging in mobile applications in general. We try to improve in this area
and thereof we'd ask contributors to be mindful of their code testability:
1. new code submitted to Nextcloud project should be provided with automatic tests
2. contributions to existing code that is currently not covered by automatic tests
should at least not make future efforts more challenging
3. whenever possible, testability should be improved even if the code is not covered by tests
# Releases
At the moment we are releasing the app in two app stores:
+41 -57
View File
@@ -7,7 +7,7 @@
import com.github.spotbugs.SpotBugsTask
buildscript {
ext.kotlin_version = '1.3.72'
ext.kotlin_version = '1.3.61'
repositories {
google()
jcenter()
@@ -20,13 +20,13 @@ buildscript {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.6.3'
classpath 'com.android.tools.build:gradle:3.5.3'
classpath('com.dicedmelon.gradle:jacoco-android:0.1.4') {
exclude group: 'org.codehaus.groovy', module: 'groovy-all'
}
classpath 'gradle.plugin.com.github.spotbugs:spotbugs-gradle-plugin:1.6.6'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath "io.gitlab.arturbosch.detekt:detekt-gradle-plugin:1.9.1"
classpath "io.gitlab.arturbosch.detekt:detekt-gradle-plugin:1.3.0"
classpath "commons-httpclient:commons-httpclient:3.1@jar" // remove after entire switch to lib v2
classpath 'com.karumi:shot:3.1.0'
}
@@ -60,10 +60,10 @@ configurations {
ext {
jacocoVersion = "0.8.2"
daggerVersion = "2.27"
markwonVersion = "4.4.0"
daggerVersion = "2.25.4"
markwonVersion = "4.2.0"
prismVersion = "2.0.0"
androidLibraryVersion ="94dc023761a285c9f5813f7bfe7872c61221f823"
androidLibraryVersion = "master-SNAPSHOT"
travisBuild = System.getenv("TRAVIS") == "true"
@@ -84,14 +84,14 @@ repositories {
// semantic versioning for version code
def versionMajor = 3
def versionMinor = 13
def versionMinor = 11
def versionPatch = 0
def versionBuild = 0 // 0-50=Alpha / 51-98=RC / 90-99=stable
for (TaskExecutionRequest tr : getGradle().getStartParameter().getTaskRequests()) {
for (String arg : tr.args) {
// any gplay, but only exact "build", as e.g. buildGeneric shall not apply gplay.grade
if (arg.contains("Gplay") || arg.contains("lint") || arg.contains("executeScreenshot") || arg == "build") {
if (arg.contains("Gplay") || arg.contains("lint") || arg == "build") {
apply from: 'gplay.gradle'
System.console().println("Applying gplay.gradle")
break
@@ -105,7 +105,7 @@ spotbugs {
shot {
appId = 'com.nextcloud.client'
instrumentationTestTask = 'connectedGplayDebugAndroidTest'
instrumentationTestTask = 'connectedGenericDebugAndroidTest'
}
android {
@@ -119,8 +119,7 @@ android {
'IconMissingDensityFolder',
'IconDensities',
'GoogleAppIndexingWarning',
'MissingDefaultResource',
'InvalidPeriodicWorkRequestInterval' // crashes due to a bug in lint itself
'MissingDefaultResource'
}
dexOptions {
@@ -130,7 +129,7 @@ android {
compileSdkVersion 29
defaultConfig {
minSdkVersion 17
minSdkVersion 16
targetSdkVersion 29
// arguments to be passed to functional tests
@@ -159,7 +158,7 @@ android {
buildTypes {
debug {
testCoverageEnabled (project.hasProperty('coverage'))
testCoverageEnabled true
}
}
@@ -178,8 +177,8 @@ android {
versionDev {
applicationId "com.nextcloud.android.beta"
dimension "default"
versionCode 20200529
versionName "20200529"
versionCode 20200110
versionName "20200110"
}
qa {
@@ -192,7 +191,7 @@ android {
testOptions {
unitTests.returnDefaultValues = true
animationsDisabled true
execution 'ANDROIDX_TEST_ORCHESTRATOR'
}
}
@@ -274,10 +273,6 @@ android {
dataBinding {
enabled true
}
viewBinding {
enabled true
}
}
dependencies {
@@ -288,45 +283,37 @@ dependencies {
gplayImplementation "com.github.nextcloud:android-library:$androidLibraryVersion"
versionDevImplementation "com.github.nextcloud:android-library:$androidLibraryVersion"
qaImplementation "com.github.nextcloud:android-library:$androidLibraryVersion"
kapt 'javax.xml.bind:jaxb-api:2.3.1'
kapt 'org.glassfish.jaxb:jaxb-core:2.3.0.1'
kapt 'org.glassfish.jaxb:jaxb-runtime:2.3.3'
annotationProcessor 'javax.xml.bind:jaxb-api:2.3.1'
annotationProcessor 'org.glassfish.jaxb:jaxb-core:2.3.0.1'
annotationProcessor 'org.glassfish.jaxb:jaxb-runtime:2.3.3'
compileOnly 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2' // remove after entire switch to lib v2
implementation "commons-httpclient:commons-httpclient:3.1@jar" // remove after entire switch to lib v2
implementation 'org.apache.jackrabbit:jackrabbit-webdav:2.13.1' // remove after entire switch to lib v2
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'com.google.android.material:material:1.1.0'
implementation 'com.google.android.material:material:1.1.0-beta02'
implementation 'com.jakewharton:disklrucache:2.0.2'
implementation 'androidx.appcompat:appcompat:1.2.0-rc01'
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.cardview:cardview:1.0.0'
implementation 'androidx.exifinterface:exifinterface:1.2.0'
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0"
implementation "androidx.work:work-runtime:2.3.4"
implementation "androidx.work:work-runtime-ktx:2.3.4"
implementation 'androidx.exifinterface:exifinterface:1.1.0'
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.1.0"
implementation "androidx.work:work-runtime:2.2.0"
implementation "androidx.work:work-runtime-ktx:2.2.0"
implementation 'com.github.albfernandez:juniversalchardet:2.0.3' // need this version for Android <7
compileOnly 'com.google.code.findbugs:annotations:2.0.1'
implementation 'commons-io:commons-io:2.7'
implementation 'commons-io:commons-io:2.6'
implementation 'com.github.tobiaskaminsky:android-job:v1.2.6.1' // 'com.github.evernote:android-job:v1.2.5'
implementation 'com.jakewharton:butterknife:10.2.1'
kapt 'com.jakewharton:butterknife-compiler:10.2.1'
implementation 'org.greenrobot:eventbus:3.2.0'
implementation 'com.googlecode.ez-vcard:ez-vcard:0.10.6'
implementation 'org.greenrobot:eventbus:3.1.1'
implementation 'com.googlecode.ez-vcard:ez-vcard:0.10.5'
implementation 'org.lukhnos:nnio:0.2'
implementation 'org.bouncycastle:bcpkix-jdk15on:1.65'
implementation 'com.madgag.spongycastle:pkix:1.54.0.0'
implementation 'com.google.code.gson:gson:2.8.6'
implementation 'com.afollestad:sectioned-recyclerview:0.5.0'
implementation 'com.github.chrisbanes:PhotoView:2.3.0'
implementation 'pl.droidsonroids.gif:android-gif-drawable:1.2.20'
implementation 'pl.droidsonroids.gif:android-gif-drawable:1.2.15'
implementation 'com.github.tobiaskaminsky:qrcodescanner:0.1.2.2' // 'com.github.blikoon:QRCodeScanner:0.1.2'
implementation 'com.google.android:flexbox:2.0.1'
implementation 'org.parceler:parceler-api:1.1.13'
kapt 'org.parceler:parceler:1.1.13'
implementation 'com.google.android:flexbox:2.0.0'
implementation 'org.parceler:parceler-api:1.1.12'
kapt 'org.parceler:parceler:1.1.12'
implementation('com.github.bumptech.glide:glide:3.8.0') {
exclude group: "com.android.support"
}
@@ -345,11 +332,11 @@ dependencies {
kapt "com.google.dagger:dagger-compiler:$daggerVersion"
kapt "com.google.dagger:dagger-android-processor:$daggerVersion"
ktlint "com.pinterest:ktlint:0.36.0"
implementation 'org.conscrypt:conscrypt-android:2.4.0'
compileOnly "org.projectlombok:lombok:1.18.10"
annotationProcessor "org.projectlombok:lombok:1.18.10"
// Shimmer animation
implementation 'com.elyeproj.libraries:loaderviewlibrary:2.0.0'
ktlint "com.pinterest:ktlint:0.36.0"
implementation 'org.conscrypt:conscrypt-android:2.2.1'
// dependencies for markdown rendering
implementation "io.noties.markwon:core:$markwonVersion"
@@ -364,12 +351,12 @@ dependencies {
// dependencies for local unit tests
testImplementation 'junit:junit:4.13'
testImplementation 'org.mockito:mockito-core:3.3.3'
testImplementation 'org.mockito:mockito-core:3.2.4'
testImplementation 'androidx.test:core:1.2.0'
testImplementation 'org.powermock:powermock-core:2.0.7'
testImplementation 'org.powermock:powermock-module-junit4:2.0.7'
testImplementation 'org.powermock:powermock-api-mockito2:2.0.7'
testImplementation 'org.json:json:20200518'
testImplementation 'org.powermock:powermock-core:2.0.4'
testImplementation 'org.powermock:powermock-module-junit4:2.0.4'
testImplementation 'org.powermock:powermock-api-mockito2:2.0.4'
testImplementation 'org.json:json:20190722'
testImplementation "com.nhaarman.mockitokotlin2:mockito-kotlin:2.2.0"
testImplementation "androidx.arch.core:core-testing:2.1.0"
@@ -384,14 +371,14 @@ dependencies {
// Espresso core
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
androidTestImplementation 'androidx.test.espresso:espresso-contrib:3.2.0'
androidTestImplementation 'org.mockito:mockito-core:3.3.1'
androidTestImplementation 'org.mockito:mockito-core:3.2.4'
// UIAutomator - for cross-app UI tests, and to grant screen is turned on in Espresso tests
// androidTestImplementation 'androidx.test.uiautomator:uiautomator:2.2.0'
// fix conflict in dependencies; see http://g.co/androidstudio/app-test-app-conflict for details
//androidTestImplementation "com.android.support:support-annotations:${supportLibraryVersion}"
androidTestImplementation 'tools.fastlane:screengrab:2.0.0'
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
androidTestImplementation('com.android.support.test.espresso:espresso-intents:3.0.2')
androidTestCompile('com.android.support.test.espresso:espresso-intents:3.0.2')
// jacocoAnt "org.jacoco:org.jacoco.ant:${jacocoVersion}"
// jacocoAgent "org.jacoco:org.jacoco.agent:${jacocoVersion}"
@@ -402,9 +389,6 @@ dependencies {
// androidJacocoAnt "org.jacoco:org.jacoco.agent:${jacocoVersion}"
implementation "com.github.stateless4j:stateless4j:2.6.0"
androidTestImplementation "com.nhaarman.mockitokotlin2:mockito-kotlin:2.2.0"
androidTestImplementation "org.mockito:mockito-android:3.3.3"
androidTestImplementation 'net.bytebuddy:byte-buddy:1.10.10'
}
configurations.all {
+59 -5
View File
@@ -1,3 +1,30 @@
autoCorrect: true
test-pattern: # Configure exclusions for test sources
active: true
patterns: # Test file regexes
- '.*/test/.*'
- '.*/androidTest/.*'
- '.*Test.kt'
- '.*Spec.kt'
- '.*Spek.kt'
exclude-rule-sets:
- 'comments'
exclude-rules:
- 'NamingRules'
- 'WildcardImport'
- 'MagicNumber'
- 'MaxLineLength'
- 'LateinitUsage'
- 'StringLiteralDuplication'
- 'SpreadOperator'
- 'TooManyFunctions'
- 'ForEachOnRange'
- 'FunctionMaxLength'
- 'TooGenericExceptionCaught'
- 'TooGenericExceptionThrown'
- 'InstanceOfCheckForException'
build:
maxIssues: 10
weights:
@@ -111,7 +138,7 @@ empty-blocks:
active: true
EmptyFunctionBlock:
active: true
ignoreOverridden: false
ignoreOverriddenFunctions: false
EmptyIfBlock:
active: true
EmptyInitBlock:
@@ -175,18 +202,23 @@ exceptions:
formatting:
active: true
android: false
autoCorrect: true
ChainWrapping:
active: true
autoCorrect: true
CommentSpacing:
active: true
autoCorrect: true
Filename:
active: true
FinalNewline:
active: true
autoCorrect: true
ImportOrdering:
active: false
Indentation:
active: true
autoCorrect: true
indentSize: 4
continuationIndentSize: 4
MaximumLineLength:
@@ -194,49 +226,73 @@ formatting:
maxLineLength: 120
ModifierOrdering:
active: true
autoCorrect: true
NoBlankLineBeforeRbrace:
active: true
autoCorrect: true
NoConsecutiveBlankLines:
active: true
autoCorrect: true
NoEmptyClassBody:
active: true
autoCorrect: true
NoItParamInMultilineLambda:
active: false
NoLineBreakAfterElse:
active: true
autoCorrect: true
NoLineBreakBeforeAssignment:
active: true
autoCorrect: true
NoMultipleSpaces:
active: true
autoCorrect: true
NoSemicolons:
active: true
autoCorrect: true
NoTrailingSpaces:
active: true
autoCorrect: true
NoUnitReturn:
active: true
autoCorrect: true
NoUnusedImports:
active: true
autoCorrect: true
NoWildcardImports:
active: true
autoCorrect: true
PackageName:
active: true
autoCorrect: true
ParameterListWrapping:
active: true
autoCorrect: true
indentSize: 4
SpacingAroundColon:
active: true
autoCorrect: true
SpacingAroundComma:
active: true
autoCorrect: true
SpacingAroundCurly:
active: true
autoCorrect: true
SpacingAroundKeyword:
active: true
autoCorrect: true
SpacingAroundOperators:
active: true
autoCorrect: true
SpacingAroundParens:
active: true
autoCorrect: true
SpacingAroundRangeOperator:
active: true
autoCorrect: true
StringTemplate:
active: true
autoCorrect: true
naming:
active: true
@@ -265,17 +321,16 @@ naming:
functionPattern: '^([a-z$][a-zA-Z$0-9]*)|(`.*`)$'
excludeClassPattern: '$^'
ignoreOverridden: true
excludes: "**/*Test.kt"
FunctionParameterNaming:
active: true
parameterPattern: '[a-z][A-Za-z0-9]*'
excludeClassPattern: '$^'
ignoreOverridden: true
ignoreOverriddenFunctions: true
MatchingDeclarationName:
active: true
MemberNameEqualsClassName:
active: false
ignoreOverridden: true
ignoreOverriddenFunction: true
ObjectPropertyNaming:
active: true
constantPattern: '[A-Za-z][_A-Za-z0-9]*'
@@ -387,7 +442,6 @@ style:
ignoreAnnotation: false
ignoreNamedArgument: true
ignoreEnums: false
excludes: "**/*Test.kt"
MandatoryBracesIfStatements:
active: false
MaxLineLength:
+1 -11
View File
@@ -1,11 +1 @@
<svg width="16" height="16" version="1.1" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg">
<path d="m2.5 1c-0.28 0-0.5 0.22-0.5 0.5v13c0 0.28 0.22 0.5 0.5 0.5h11c0.28 0 0.5-0.22 0.5-0.5v-10.5l-3-3z"
fill="#dc5047" />
<g fill="#fff" aria-label="PDF">
<path
d="m4.9093 8.443v1.057h-0.61813v-3h1.1703q0.33791 0 0.59341 0.12363 0.25755 0.12363 0.3956 0.35234 0.13805 0.22665 0.13805 0.51717 0 0.44093-0.30288 0.69643-0.30082 0.25343-0.83448 0.25343zm0-0.50069h0.5522q0.24519 0 0.37294-0.11538 0.12981-0.11538 0.12981-0.32967 0-0.22047-0.12981-0.35646t-0.35852-0.14011h-0.56662z" />
<path
d="m7.011 9.5v-3h0.92308q0.3956 0 0.70673 0.17926 0.31319 0.1772 0.48832 0.50687 0.17514 0.32761 0.17514 0.74588v0.13805q0 0.41827-0.17308 0.74382-0.17102 0.32555-0.4842 0.50481-0.31319 0.17926-0.70673 0.18132zm0.61813-2.4993v2.0027h0.29876q0.36264 0 0.55426-0.23695 0.19162-0.23695 0.19574-0.67788v-0.15865q0-0.45742-0.18956-0.69231-0.18956-0.23695-0.55426-0.23695z" />
<path d="m11.56 8.274h-1.1868v1.226h-0.61813v-3h1.9533v0.50069h-1.3352v0.77473h1.1868z" />
</g>
</svg>
<svg xmlns="http://www.w3.org/2000/svg" height="16" viewBox="0 0 16 16" width="16" version="1.1"><path fill="#dc5047" d="m2.5 1c-0.28 0-0.5 0.22-0.5 0.5v13c0 0.28 0.22 0.5 0.5 0.5h11c0.28 0 0.5-0.22 0.5-0.5v-10.5l-3-3zm5.8 3.9s0.07 0.95-0.15 2.3c0.715 2.053 1.5 2.33 1.85 2.5 0.74-0.06 1.565-0.1 2.3 0.3 0.5 0.286 0.894 1.5-0.3 1.5-0.54-0.034-1.537-0.346-2.25-0.7-1.066 0.12-2.39 0.32-3.5 0.8-1.25 2.1-1.81 2.4-2.25 2.4-1.215-0.32-0.56-1.93-0.1-2.2 0.55-0.47 1.195-0.74 1.4-0.8 0.09-0.15 1.384-2.69 1.7-3.75-0.3-1.024-0.37-2.106-0.2-2.75 0.78-1.018 1.5-0.35 1.5 0.4zm-0.7 3.1c-0.27 1.057-1.348 3.084-1.3 3 1.105-0.485 2.1-0.63 3.2-0.8-0.526-0.235-1.146-0.25-1.9-2.2z"/></svg>

Before

Width:  |  Height:  |  Size: 1.1 KiB

After

Width:  |  Height:  |  Size: 676 B

-27
View File
@@ -1,27 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" viewBox="0 0 57 57" width="64" height="64"
version="1.1" id="svg10" sodipodi:docname="circles.svg" inkscape:version="0.92.4 5da689c313, 2019-01-14">
<metadata id="metadata16">
<rdf:RDF>
<cc:Work rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
</cc:Work>
</rdf:RDF>
</metadata>
<defs id="defs14" />
<sodipodi:namedview pagecolor="#ffffff" bordercolor="#666666" borderopacity="1" objecttolerance="10"
gridtolerance="10" guidetolerance="10" inkscape:pageopacity="0" inkscape:pageshadow="2"
inkscape:window-width="1920" inkscape:window-height="1141" id="namedview12" showgrid="false"
inkscape:zoom="7.375" inkscape:cx="33.445579" inkscape:cy="41.701636" inkscape:window-x="0"
inkscape:window-y="0" inkscape:window-maximized="1" inkscape:current-layer="svg10" />
<path d="M7.1 28.5A21.4 21.4 0 0 1 28.5 7.1m10.7 40A21.4 21.4 0 0 1 10 39M39.2 10A21.4 21.4 0 0 1 47 39.2"
fill="none" stroke="#fff" stroke-width="4" stroke-linecap="round" stroke-linejoin="round" id="path2"
style="stroke:#000000;stroke-opacity:1;stroke-width:3.99979687;stroke-miterlimit:4;stroke-dasharray:none;fill:none;fill-opacity:1" />
<circle cx="28.5" cy="7.1" r="6.5" fill="#fff" id="circle4" style="fill:#000000" />
<circle cx="39.2" cy="-10" r="6.5" transform="rotate(90)" fill="#fff" id="circle6" style="fill:#000000" />
<circle cx="39.2" cy="-47" r="6.5" transform="rotate(90)" fill="#fff" id="circle8" style="fill:#000000" />
</svg>

Before

Width:  |  Height:  |  Size: 2.0 KiB

+5
View File
@@ -0,0 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" height="16" width="16" version="1">
<path
d="M1.46 2c-.25 0-.46.21-.46.46v11.08c0 .257.203.46.46.46h13.08c.257 0 .46-.203.46-.46V4.462a.47.47 0 0 0-.46-.465H8L6 2H1.46zm7.583 3.82c.671 0 1.24.49 1.24 1.123v.014c-.007.197-.007.424-.142.969l-.012.011a.914.914 0 0 1-.156.26c-.067.086-.145.173-.22.258l-.089.104c-.013.05-.03.104-.039.154-.038.187-.019.308 0 .35.333.141.668.267.955.388.314.133.584.264.764.479a.208.208 0 0 1 .05.103c.02.155.036.417.053.684.017.267.035.54.051.66a.212.212 0 0 1-.103.207c-.566.301-1.457.434-2.352.437-.895.004-1.793-.121-2.377-.437a.212.212 0 0 1-.104-.207c.022-.171.044-.385.069-.598l-.022.002c-.614.003-1.23-.084-1.63-.3a.146.146 0 0 1-.07-.143c.033-.264.076-.656.105-.922a.111.111 0 0 1 0-.018c.03-.129.12-.173.213-.23.091-.057.204-.105.328-.158.22-.096.466-.179.664-.248a.69.69 0 0 0-.018-.248l-.035-.153-.018-.017a3.558 3.558 0 0 1-.168-.186c-.05-.059-.088-.102-.115-.178l-.01-.007v-.01a3.08 3.08 0 0 1-.097-.664c0-.435.391-.772.851-.772.46 0 .852.337.852.772v.01c-.005.135-.005.29-.098.664l-.01.01a.61.61 0 0 1-.105.175c-.045.059-.1.12-.15.178l-.063.07c-.009.036-.02.074-.027.108a.448.448 0 0 0 0 .238c.228.097.46.183.656.266.15.063.277.134.387.216.144-.051.297-.114.424-.158a1.03 1.03 0 0 0-.026-.361c-.015-.07-.036-.149-.053-.22l-.025-.026a5.503 5.503 0 0 1-.246-.272c-.074-.085-.13-.148-.168-.258l-.012-.013v-.014c-.12-.522-.138-.768-.142-.969 0-.633.569-1.123 1.24-1.123z"
fill="#0082c9" fill-rule="evenodd" />
</svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" height="16" viewBox="0 0 16 16" width="16" version="1.1"><path fill="#0082c9" d="m1.5 2c-0.25 0-0.5 0.25-0.5 0.5v11c0 0.26 0.24 0.5 0.5 0.5h13c0.26 0 0.5-0.241 0.5-0.5v-9c0-0.25-0.25-0.5-0.5-0.5h-6.5l-2-2h-4.5zm8.75 3.5a1.25 1.25 0 0 1 1.25 1.25 1.25 1.25 0 0 1 -1.25 1.25 1.25 1.25 0 0 1 -0.8008 -0.291l-2.4512 1.2265a1.25 1.25 0 0 1 0.002 0.0645 1.25 1.25 0 0 1 -0.0039 0.0645l2.4531 1.2265a1.25 1.25 0 0 1 0.8008 -0.291 1.25 1.25 0 0 1 1.25 1.25 1.25 1.25 0 0 1 -1.25 1.25 1.25 1.25 0 0 1 -1.25 -1.25 1.25 1.25 0 0 1 0.0039 -0.064l-2.4531-1.227a1.25 1.25 0 0 1 -0.8008 0.291 1.25 1.25 0 0 1 -1.25 -1.25 1.25 1.25 0 0 1 1.25 -1.25 1.25 1.25 0 0 1 0.8008 0.291l2.4512-1.2265a1.25 1.25 0 0 1 -0.002 -0.0645 1.25 1.25 0 0 1 1.25 -1.25z"/></svg>

After

Width:  |  Height:  |  Size: 784 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" height="16" viewBox="0 0 16 16" width="16" version="1.1"><path fill="#0082c9" d="m1.5 2c-0.25 0-0.5 0.25-0.5 0.5v11c0 0.26 0.24 0.5 0.5 0.5h13c0.26 0 0.5-0.241 0.5-0.5v-9c0-0.25-0.25-0.5-0.5-0.5h-6.5l-2-2h-4.5zm6.5 3.25l1.1 2.6504 2.9 0.2246-2.25 1.875 0.75 2.75-2.5-1.551-2.5 1.551 0.75-2.75-2.25-1.875 2.9-0.2246 1.1-2.6504z"/></svg>

After

Width:  |  Height:  |  Size: 376 B

+56 -1
View File
@@ -1 +1,56 @@
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="24" height="24" viewBox="0 0 24 24"><path d="M10,4H4C2.89,4 2,4.89 2,6V18A2,2 0 0,0 4,20H20A2,2 0 0,0 22,18V8C22,6.89 21.1,6 20,6H12L10,4Z" /></svg>
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
height="17.066668"
width="17.066668"
version="1"
id="svg2"
inkscape:version="0.92.2 2405546, 2018-03-11"
sodipodi:docname="folder.svg"
inkscape:export-filename="C:\DEV\src\Android\Nextcloud\colorFolderNew\src\main\res\drawable-xxxhdpi\ic_list_empty_folder.png"
inkscape:export-xdpi="1620"
inkscape:export-ydpi="1620">
<metadata
id="metadata10">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage"/>
</cc:Work>
</rdf:RDF>
</metadata>
<defs
id="defs8"/>
<sodipodi:namedview
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1"
objecttolerance="10"
gridtolerance="10"
guidetolerance="10"
inkscape:pageopacity="0"
inkscape:pageshadow="2"
inkscape:window-width="1600"
inkscape:window-height="871"
id="namedview6"
showgrid="false"
inkscape:zoom="14.75"
inkscape:cx="19.423729"
inkscape:cy="8"
inkscape:window-x="1600"
inkscape:window-y="0"
inkscape:window-maximized="1"
inkscape:current-layer="svg2"/>
<path
d="m 1.5541333,2.1301333 c -0.2666666,0 -0.4906666,0.224 -0.4906666,0.4906667 v 11.818667 c 0,0.277333 0.2154666,0.490666 0.4906666,0.490666 H 15.506133 c 0.2752,0 0.490667,-0.213333 0.490667,-0.490666 V 4.7573333 c 0,-0.2666666 -0.224,-0.4938666 -0.490667,-0.4938666 H 8.5301333 L 6.3968,2.1301333 Z"
id="path4"
style="fill:#0082c9;fill-opacity:1;fill-rule:evenodd;stroke-width:1.06666672;opacity:1"
inkscape:connector-curvature="0"/>
</svg>

Before

Width:  |  Height:  |  Size: 388 B

After

Width:  |  Height:  |  Size: 2.1 KiB

-67
View File
@@ -1,67 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
version="1.1"
width="24"
height="24"
viewBox="0 0 24 24"
id="svg3738"
sodipodi:docname="folder-group.svg"
inkscape:version="0.92.4 (5da689c313, 2019-01-14)">
<metadata
id="metadata3744">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title></dc:title>
</cc:Work>
</rdf:RDF>
</metadata>
<defs
id="defs3742" />
<sodipodi:namedview
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1"
objecttolerance="10"
gridtolerance="10"
guidetolerance="10"
inkscape:pageopacity="0"
inkscape:pageshadow="2"
inkscape:window-width="2520"
inkscape:window-height="1481"
id="namedview3740"
showgrid="false"
showguides="true"
inkscape:guide-bbox="true"
inkscape:zoom="27.812867"
inkscape:cx="20.589505"
inkscape:cy="10.4013"
inkscape:window-x="2869"
inkscape:window-y="-11"
inkscape:window-maximized="1"
inkscape:current-layer="svg3738">
<sodipodi:guide
position="12.025424,12.737288"
orientation="1,0"
id="guide3746"
inkscape:locked="false" />
<sodipodi:guide
position="1.0606602,11.020079"
orientation="0,1"
id="guide3748"
inkscape:locked="false" />
</sodipodi:namedview>
<path
d="M 4 4 C 2.89 4 2 4.89 2 6 L 2 18 C 2 19.104569 2.8954305 20 4 20 L 20 20 C 21.104569 20 22 19.104569 22 18 L 22 8 C 22 6.89 21.1 6 20 6 L 12 6 L 10 4 L 4 4 z M 12.025391 8.6132812 A 2.0714286 2.0714286 0 0 1 14.097656 10.685547 L 14.097656 11.513672 L 14.511719 11.513672 A 0.82857142 0.82857142 0 0 1 15.339844 12.341797 L 15.339844 16.484375 A 0.82857142 0.82857142 0 0 1 14.511719 17.314453 L 9.5390625 17.314453 A 0.82857142 0.82857142 0 0 1 8.7109375 16.484375 L 8.7109375 12.341797 C 8.7109375 11.88194 9.0833475 11.513672 9.5390625 11.513672 L 9.953125 11.513672 L 9.953125 10.685547 A 2.0714286 2.0714286 0 0 1 12.025391 8.6132812 z M 12.025391 9.4414062 A 1.2428571 1.2428571 0 0 0 10.783203 10.685547 L 10.783203 11.513672 L 13.267578 11.513672 L 13.267578 10.685547 A 1.2428571 1.2428571 0 0 0 12.025391 9.4414062 z M 12.025391 13.585938 A 0.82857142 0.82857142 0 0 0 11.197266 14.414062 A 0.82857142 0.82857142 0 0 0 12.025391 15.242188 A 0.82857142 0.82857142 0 0 0 12.853516 14.414062 C 12.853516 13.954206 12.481105 13.585937 12.025391 13.585938 z "
id="path3736" />
</svg>

Before

Width:  |  Height:  |  Size: 2.9 KiB

+4 -4
View File
@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="100%" height="100%" viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve" xmlns:serif="http://www.serif.com/" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2;">
<path d="M10,4L4,4C2.89,4 2,4.89 2,6L2,18C2,19.097 2.903,20 4,20L20,20C21.097,20 22,19.097 22,18L22,8C22,6.89 21.1,6 20,6L12,6L10,4ZM8.453,9.652L10.823,9.652L11.616,10.403L8.453,10.403L8.453,16.403L14.776,16.403L14.776,13.402L15.569,14.151L15.569,16.403C15.569,16.817 15.216,17.152 14.778,17.152L8.451,17.152C8.013,17.152 7.661,16.817 7.661,16.403L7.661,10.403C7.661,9.987 8.014,9.652 8.453,9.652ZM11.616,8.903L16.361,8.903L16.361,13.402L14.776,11.902L12.404,14.152L10.823,12.651L13.196,10.405L11.616,8.903Z" style="fill-rule:nonzero;"/>
<svg xmlns="http://www.w3.org/2000/svg" height="16" width="16" version="1">
<path
d="M1.46 2c-.25 0-.46.21-.46.46v11.08c0 .258.202.46.46.46h13.08c.258 0 .46-.202.46-.46V4.462c0-.25-.21-.463-.46-.463H8L6 2H1.46zm6.517 3.793h3.57v3.385L10.355 8.05 8.57 9.743l-1.19-1.13 1.786-1.69-1.19-1.13zm-2.38.564H7.38l.597.565h-2.38v4.514h4.758V9.178l.596.564v1.694c0 .312-.265.564-.595.564h-4.76c-.33 0-.595-.252-.595-.564V6.922c0-.313.266-.565.596-.565z"
fill-rule="evenodd" fill="#0082c9"/>
</svg>

Before

Width:  |  Height:  |  Size: 992 B

After

Width:  |  Height:  |  Size: 508 B

-67
View File
@@ -1,67 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
version="1.1"
width="24"
height="24"
viewBox="0 0 24 24"
id="svg3738"
sodipodi:docname="folder-group.svg"
inkscape:version="0.92.4 (5da689c313, 2019-01-14)">
<metadata
id="metadata3744">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title></dc:title>
</cc:Work>
</rdf:RDF>
</metadata>
<defs
id="defs3742" />
<sodipodi:namedview
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1"
objecttolerance="10"
gridtolerance="10"
guidetolerance="10"
inkscape:pageopacity="0"
inkscape:pageshadow="2"
inkscape:window-width="2520"
inkscape:window-height="1481"
id="namedview3740"
showgrid="false"
showguides="true"
inkscape:guide-bbox="true"
inkscape:zoom="39.333333"
inkscape:cx="5.613764"
inkscape:cy="12.065596"
inkscape:window-x="2869"
inkscape:window-y="-11"
inkscape:window-maximized="1"
inkscape:current-layer="svg3738">
<sodipodi:guide
position="12.025424,12.737288"
orientation="1,0"
id="guide3746"
inkscape:locked="false" />
<sodipodi:guide
position="1.0606602,11.020079"
orientation="0,1"
id="guide3748"
inkscape:locked="false" />
</sodipodi:namedview>
<path
d="M 4 4 C 2.89 4 2 4.89 2 6 L 2 18 C 2 19.104569 2.8954305 20 4 20 L 20 20 C 21.104569 20 22 19.104569 22 18 L 22 8 C 22 6.89 21.1 6 20 6 L 12 6 L 10 4 L 4 4 z M 10.224609 8.6347656 A 2.0299929 2.0299929 0 0 1 12.3125 10.664062 A 2.0299929 2.0299929 0 0 1 10.283203 12.693359 A 2.0299929 2.0299929 0 0 1 10.224609 8.6347656 z M 13.763672 8.6347656 A 2.0299932 2.0299932 0 0 1 13.763672 12.693359 A 1.9661931 1.9661931 0 0 1 12.644531 12.351562 A 2.8999899 2.8999899 0 0 0 12.644531 8.9765625 A 1.9661931 1.9661931 0 0 1 13.763672 8.6347656 z M 10.283203 13.853516 C 14.343189 13.853516 14.34375 16.173828 14.34375 16.173828 L 14.34375 17.333984 L 6.2226562 17.333984 L 6.2226562 16.173828 C 6.2226562 16.173828 6.2232172 13.853516 10.283203 13.853516 z M 14.308594 13.853516 C 17.823381 14.068115 17.822266 16.173828 17.822266 16.173828 L 17.822266 17.333984 L 15.503906 17.333984 L 15.503906 16.173828 A 3.0855892 3.0855892 0 0 0 14.308594 13.853516 z "
id="path3736" />
</svg>

Before

Width:  |  Height:  |  Size: 2.8 KiB

+4
View File
@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" height="16" viewBox="0 0 16 16" width="16" version="1.1">
<path fill="#0082c9"
d="m1.5 2c-0.25 0-0.5 0.25-0.5 0.5v11c0 0.26 0.24 0.5 0.5 0.5h13c0.26 0 0.5-0.241 0.5-0.5v-9c0-0.25-0.25-0.5-0.5-0.5h-6.5l-2-2h-4.5zm8.334 3.5c0.434-0.0019 0.866 0.1545 1.186 0.4746 0.64 0.6407 0.64 1.742 0 2.3828l-0.85 0.8496c0.027-0.4496-0.019-0.7497-0.3067-1.1562l0.4237-0.4258c0.275-0.2752 0.252-0.6283 0.002-0.916-0.27-0.2699-0.644-0.2702-0.916 0.0019l-1.6464 1.6465c-0.2829 0.283-0.2956 0.6223-0.002 0.916l-0.7305 0.7326c-0.2872-0.2874-0.4858-0.6731-0.5117-1.1076-0.0256-0.4344 0.1457-0.9071 0.5117-1.2734l1.6465-1.6484c0.3245-0.3147 0.7598-0.4747 1.1934-0.4766zm-0.8262 2.4902c0.2882 0.2871 0.4869 0.6743 0.5117 1.1094 0.0254 0.4352-0.1449 0.9064-0.5117 1.2734l-1.6484 1.647c-0.6396 0.639-1.7395 0.639-2.3789 0-0.6396-0.64-0.6415-1.738 0-2.3794l0.8613-0.8633c-0.0263 0.4493 0.0227 0.7505 0.3105 1.1563l-0.4394 0.4394c-0.2588 0.259-0.3242 0.59 0 0.914 0.2438 0.244 0.5557 0.307 0.916 0l1.6465-1.6464c0.2647-0.2648 0.2866-0.6331 0.0019-0.9179l0.7305-0.7325z"/>
</svg>

After

Width:  |  Height:  |  Size: 1.1 KiB

-67
View File
@@ -1,67 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
version="1.1"
width="24"
height="24"
viewBox="0 0 24 24"
id="svg3738"
sodipodi:docname="folder_public.svg"
inkscape:version="0.92.4 (5da689c313, 2019-01-14)">
<metadata
id="metadata3744">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title></dc:title>
</cc:Work>
</rdf:RDF>
</metadata>
<defs
id="defs3742" />
<sodipodi:namedview
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1"
objecttolerance="10"
gridtolerance="10"
guidetolerance="10"
inkscape:pageopacity="0"
inkscape:pageshadow="2"
inkscape:window-width="2520"
inkscape:window-height="1481"
id="namedview3740"
showgrid="false"
showguides="true"
inkscape:guide-bbox="true"
inkscape:zoom="27.812867"
inkscape:cx="19.008573"
inkscape:cy="7.4638855"
inkscape:window-x="2869"
inkscape:window-y="-11"
inkscape:window-maximized="1"
inkscape:current-layer="svg3738">
<sodipodi:guide
position="12.025424,12.737288"
orientation="1,0"
id="guide3746"
inkscape:locked="false" />
<sodipodi:guide
position="1.0606602,11.020079"
orientation="0,1"
id="guide3748"
inkscape:locked="false" />
</sodipodi:namedview>
<path
d="M 4 4 C 2.89 4 2 4.89 2 6 L 2 18 C 2 19.104569 2.8954305 20 4 20 L 20 20 C 21.104569 20 22 19.104569 22 18 L 22 8 C 22 6.89 21.1 6 20 6 L 12 6 L 10 4 L 4 4 z M 14.3125 8.7167969 C 14.834031 8.7167969 15.355444 8.9140378 15.75 9.3085938 C 16.539112 10.097706 16.539112 11.393256 15.75 12.183594 L 14.466797 13.466797 C 14.520098 12.985243 14.444634 12.498869 14.236328 12.054688 L 14.929688 11.361328 C 15.278905 11.013335 15.27768 10.480077 14.929688 10.130859 C 14.581694 9.7816405 14.04526 9.7816405 13.697266 10.130859 L 11.644531 12.183594 A 0.8577305 0.8577305 0 0 0 11.886719 13.582031 L 11.041016 14.429688 C 10.961982 14.371484 10.893336 14.308618 10.822266 14.236328 A 2.0413986 2.0413986 0 0 1 10.822266 11.361328 L 12.875 9.3085938 C 13.269556 8.9140377 13.790969 8.7167969 14.3125 8.7167969 z M 13.068359 11.580078 A 1.9151897 1.9151897 0 0 1 13.285156 11.771484 A 2.0413986 2.0413986 0 0 1 13.285156 14.646484 L 13.285156 14.648438 L 11.232422 16.701172 C 10.44331 17.491509 9.146534 17.490284 8.3574219 16.701172 C 7.5683099 15.91206 7.5683099 14.616509 8.3574219 13.826172 L 9.640625 12.542969 A 2.627106 2.627106 0 0 0 9.8730469 13.955078 L 9.1796875 14.648438 C 8.8316939 14.996431 8.8310813 15.530912 9.1796875 15.878906 C 9.5282936 16.226925 10.062891 16.228125 10.412109 15.878906 L 12.464844 13.826172 A 0.8577305 0.8577305 0 0 0 12.220703 12.427734 L 13.068359 11.580078 z "
id="path3736" />
</svg>

Before

Width:  |  Height:  |  Size: 3.2 KiB

@@ -1,66 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
version="1.1"
width="24"
height="24"
viewBox="0 0 24 24"
id="svg3738"
sodipodi:docname="folder-shared.svg"
inkscape:version="0.92.4 (5da689c313, 2019-01-14)">
<metadata
id="metadata3744">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
</cc:Work>
</rdf:RDF>
</metadata>
<defs
id="defs3742" />
<sodipodi:namedview
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1"
objecttolerance="10"
gridtolerance="10"
guidetolerance="10"
inkscape:pageopacity="0"
inkscape:pageshadow="2"
inkscape:window-width="2520"
inkscape:window-height="1481"
id="namedview3740"
showgrid="false"
showguides="true"
inkscape:guide-bbox="true"
inkscape:zoom="27.812867"
inkscape:cx="-0.64166953"
inkscape:cy="11.271299"
inkscape:window-x="2869"
inkscape:window-y="-11"
inkscape:window-maximized="1"
inkscape:current-layer="svg3738">
<sodipodi:guide
position="12.025424,12.737288"
orientation="1,0"
id="guide3746"
inkscape:locked="false" />
<sodipodi:guide
position="1.0606602,11.020079"
orientation="0,1"
id="guide3748"
inkscape:locked="false" />
</sodipodi:namedview>
<path
d="M 4 4 C 2.89 4 2 4.89 2 6 L 2 18 A 2 2 0 0 0 4 20 L 20 20 A 2 2 0 0 0 22 18 L 22 8 C 22 6.89 21.1 6 20 6 L 12 6 L 10 4 L 4 4 z M 14.933594 8.1679688 A 1.449999 1.449999 0 0 1 16.382812 9.6191406 A 1.449999 1.449999 0 0 1 14.933594 11.068359 C 14.55176 11.068359 14.208265 10.9194 13.947266 10.677734 L 10.539062 12.664062 C 10.563222 12.77523 10.583984 12.885951 10.583984 13.001953 C 10.583984 13.117952 10.563223 13.228676 10.539062 13.339844 L 13.986328 15.345703 C 14.237662 15.118536 14.566259 14.974609 14.933594 14.974609 A 1.4113325 1.4113325 0 0 1 16.345703 16.384766 C 16.345703 17.162932 15.711761 17.791016 14.933594 17.791016 C 14.155428 17.791016 13.521484 17.162932 13.521484 16.384766 C 13.521484 16.273599 13.536387 16.167908 13.560547 16.066406 L 10.119141 14.060547 C 9.8581421 14.302213 9.5146455 14.451172 9.1328125 14.451172 A 1.449999 1.449999 0 0 1 7.6835938 13.001953 A 1.449999 1.449999 0 0 1 9.1328125 11.552734 C 9.5146455 11.552734 9.8581421 11.701692 10.119141 11.943359 L 13.527344 9.9570312 C 13.503184 9.8458632 13.484375 9.7351412 13.484375 9.6191406 A 1.449999 1.449999 0 0 1 14.933594 8.1679688 z "
id="path3736" />
</svg>

Before

Width:  |  Height:  |  Size: 2.9 KiB

-5
View File
@@ -1,5 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="100%" height="100%" viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve" xmlns:serif="http://www.serif.com/" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2;">
<path d="M10,4L4,4C2.89,4 2,4.89 2,6L2,18C2,19.097 2.903,20 4,20L20,20C21.097,20 22,19.097 22,18L22,8C22,6.89 21.1,6 20,6L12,6L10,4ZM11.988,8.52L13.26,11.583L16.611,11.843L14.011,14.01L14.878,17.188L11.988,15.395L9.099,17.188L9.966,14.01L7.365,11.843L10.717,11.583L11.988,8.52Z" style="fill-rule:nonzero;"/>
</svg>

Before

Width:  |  Height:  |  Size: 762 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" height="16" width="16" version="1"><path fill-rule="evenodd" fill="#0082c9" d="m1.4609 2c-0.25 0-0.4609 0.2109-0.4609 0.4609v11.078c0 0.258 0.2029 0.461 0.4609 0.461h13.078c0.258 0 0.461-0.203 0.461-0.461v-9.0761c0-0.25-0.211-0.4649-0.461-0.4649h-6.539l-2-1.998h-4.5391zm6.5391 3.8008c0.8836 0 1.5996 0.7159 1.5996 1.5996v0.7988h0.4004v2.8008h-4v-2.8008h0.4004v-0.7988c0-0.8837 0.716-1.5996 1.5996-1.5996zm0 0.7988c-0.4419 0-0.8008 0.3589-0.8008 0.8008v0.7988h1.6016v-0.7988c0-0.4419-0.3589-0.8008-0.8008-0.8008z"/></svg>

After

Width:  |  Height:  |  Size: 562 B

-18
View File
@@ -1,18 +0,0 @@
<?xml version="1.0" encoding="utf-8"?><!-- Generator: Adobe Illustrator 23.0.1, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" width="24px" height="24px" viewBox="0 0 24 24"
enable-background="new 0 0 24 24" xml:space="preserve">
<g id="Bounding_Box">
<rect fill="none" width="24" height="24" />
</g>
<g id="Flat">
<g id="ui_x5F_spec_x5F_header_copy_2">
</g>
<g>
<path d="M17,19.22H5V7h7V5H5C3.9,5,3,5.9,3,7v12c0,1.1,0.9,2,2,2h12c1.1,0,2-0.9,2-2v-7h-2V19.22z" />
<path d="M19,2h-2v3h-3c0.01,0.01,0,2,0,2h3v2.99c0.01,0.01,2,0,2,0V7h3V5h-3V2z" />
<rect x="7" y="9" width="8" height="2" />
<polygon points="7,12 7,14 15,14 15,12 12,12 " />
<rect x="7" y="15" width="8" height="2" />
</g>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 845 B

+1 -1
View File
@@ -1,3 +1,3 @@
dependencies {
implementation "com.google.firebase:firebase-messaging:20.1.3"
implementation "com.google.firebase:firebase-messaging:17.3.0"
}
+1
View File
@@ -5,3 +5,4 @@ NC_TEST_SERVER_PASSWORD=test
android.enableJetifier=true
android.useAndroidX=true
android.debug.obsoleteApi=true
+1 -1
View File
@@ -3,4 +3,4 @@ distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.4-all.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-5.4.1-all.zip
+2 -6
View File
@@ -5,9 +5,9 @@
<ignore regexp="autofillHints"/>
</issue>
<issue id="InvalidPackage">
<ignore path="**/freemarker-2.*.*.jar" />
<ignore path="**/freemarker-2.3.28.jar" />
<ignore path="**/nnio-0.2.jar"/>
<ignore path="**/bcpkix-jdk15on-1.65.jar" />
<ignore path="**/pkix-1.54.0.0.jar"/>
</issue>
<issue id="UnusedResources">
@@ -44,8 +44,4 @@
<ignore path="**/values-**/strings.xml" />
</issue>
<issue id="TrustAllX509TrustManager">
<ignore path="**/bouncycastle/est/jcajce/*.class" />
</issue>
</lint>
Binary file not shown.

Before

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 38 KiB

After

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 34 KiB

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

+28 -1
View File
@@ -17,6 +17,13 @@ lintValue=$?
ruby scripts/analysis/findbugs-up.rb $1 $2 $3
findbugsValue=$?
./gradlew ktlint
ktlintValue=$?
./gradlew detekt
detektValue=$?
# exit codes:
# 0: count was reduced
# 1: count was increased
@@ -120,6 +127,17 @@ else
findbugsMessage="<h1>SpotBugs increased!</h1>"
fi
if ( [ $ktlintValue -eq 1 ] ) ; then
sed -i ':a;N;$!ba;s#\n#<br />#g;s#^<br />##g' build/ktlint.txt
curl -u $4:$5 -X PUT https://nextcloud.kaminsky.me/remote.php/webdav/android-ktlint/$6.html --upload-file build/ktlint.txt
ktlintMessage="<h1>Kotlin lint found errors</h1><a href='https://www.kaminsky.me/nc-dev/android-ktlint/$6.html'>Lint</a>"
fi
if ( [ $detektValue -eq 1 ] ) ; then
curl -u $4:$5 -X PUT https://nextcloud.kaminsky.me/remote.php/webdav/android-detekt/$6.html --upload-file build/reports/detekt/detekt.html
detektMessage="<h1>Detekt errors found</h1><a href='https://www.kaminsky.me/nc-dev/android-detekt/$6.html'>Lint</a>"
fi
# check gplay limitation: all changelog files must only have 500 chars
gplayLimitation=$(scripts/checkGplayLimitation.sh)
@@ -127,7 +145,7 @@ else
gplayLimitation="<h1>Following files are beyond 500 char limit:</h1><br><br>"$gplayLimitation
fi
curl -u $1:$2 -X POST https://api.github.com/repos/nextcloud/android/issues/$7/comments -d "{ \"body\" : \"$codacyResult $lintResult $findbugsResultNew $findbugsResultOld $checkLibraryMessage $lintMessage $findbugsMessage $gplayLimitation \" }"
curl -u $1:$2 -X POST https://api.github.com/repos/nextcloud/android/issues/$7/comments -d "{ \"body\" : \"$codacyResult $lintResult $findbugsResultNew $findbugsResultOld $checkLibraryMessage $lintMessage $findbugsMessage $ktlintMessage $detektMessage $gplayLimitation \" }"
if [ ! -z "$gplayLimitation" ]; then
exit 1
@@ -141,6 +159,15 @@ else
exit $lintValue
fi
if [ $ktlintValue -eq 1 ]; then
exit 1
fi
if [ $detektValue -eq 1 ]; then
exit 1
fi
if [ $findbugsValue -eq 2 ]; then
exit 0
else
+1 -1
View File
@@ -1 +1 @@
370
414
-8
View File
@@ -48,14 +48,6 @@ require 'xmlsimple'
# run FindBugs
puts "running FindBugs..."
system './gradlew assembleGplayDebug'
# confirm that assemble ran w/out error
result = $?.to_i
if result != 0
puts "FAIL: failed to run ./gradlew assembleGplayDebug"
exit 1
end
system './gradlew spotbugsGplayDebug'
# find FindBugs report file
+1 -1
View File
@@ -1,2 +1,2 @@
DO NOT TOUCH; GENERATED BY DRONE
<span class="mdl-layout-title">Lint Report: 95 warnings</span>
<span class="mdl-layout-title">Lint Report: 74 warnings</span>
+9 -31
View File
@@ -1,15 +1,10 @@
#!/bin/bash
date=$(date +%Y%m%d)
oldLibraryCommit=$(grep "androidLibraryVersion\ =" build.gradle)
libraryCommit=$(curl https://api.github.com/repos/nextcloud/android-library/commits/master | jq .sha | sed s'/\"//g')
# use current date for version code/name
sed -i "/versionDev/,/\}/ s/versionCode .*/versionCode $date/" build.gradle
sed -i "/versionDev/,/\}/ s/versionName .*/versionName \"$date\"/" build.gradle
# change library
sed -i s"#androidLibraryVersion\ =.*#androidLibraryVersion =\"$libraryCommit\"#" build.gradle
# build signed apk
./gradlew assembleVersionDevRelease >> /tmp/dev.log 2>&1
@@ -37,37 +32,20 @@ mv latest.apk ~/apks/
# remove all but the latest 5 apks
/bin/ls -t ~/apks/*.apk | awk 'NR>6' | xargs rm -f
lastBuildTag=$(git tag | grep dev | tail -n1)
# Show only the commit subject in the changelog and filter out:
# * Merges
# * Dependabot commits
# * Commits touching only non-user-facing stuff like tests
# * Version bump commits
# * Anything reachable from the previous dev edition tag
changelog=$(git log --no-merges --invert-grep --author=dependabot --pretty='format:%s' HEAD "^$lastBuildTag" -- ':!src/androidTest' ':!.*' ':!scripts/' ':!screenshots' ':!CHANGELOG.md' | grep -vE '^daily dev [[:digit:]]{8}$')
# Make Transifex updates have a nicer description
if echo "$changelog" | grep -q 'tx-robot'; then
changelog=$(echo "$changelog" | grep -v 'tx-robot')
# This is a funky bashism - preceding a single-quote string with $ lets you put escape chars in it
changelog="${changelog}"$'\nUpdate translations'
fi
lastBuildTime=$(date --date="$(git log -1 --format=%ai $(git tag | grep dev | tail -n1))" +%s)
changelog=$(git log --after=$lastBuildTime --pretty=oneline --abbrev-commit)
# Check if the library was updated
if ! echo $oldLibraryCommit | grep -q $libraryCommit; then
changelog="${changelog}"$'\nUpdate Nextcloud Android library'
fi
# Collapse dependency updates into a single "Update dependencies" entry
if git log --pretty='format:%an' HEAD "^$lastBuildTag" | grep -q dependabot; then
changelog="${changelog}"$'\nUpdate 3rd-party dependencies'
fi
# changelog
echo "$changelog" > src/versionDev/fastlane/metadata/android/en-US/changelogs/$date.txt
echo "library commit: $(curl https://api.github.com/repos/nextcloud/android-library/commits/master | jq .sha | sed s'/\"//g')" >> src/versionDev/fastlane/metadata/android/en-US/changelogs/$date.txt
git add .
git add build.gradle
git add src/versionDev/fastlane/metadata/android/en-US/changelogs/$date.txt
git commit -m "daily dev $date" -m "$changelog"
git push
git tag dev-$date
git push origin dev-$date
# remove all but the latest 5 tags
git tag|grep dev | sort -r | awk 'NR>5' | xargs -n 1 git push --delete origin
git tag|grep dev | sort -r | awk 'NR>5' | xargs -n 1 git tag -d
+4 -55
View File
@@ -1,25 +1,15 @@
#!/usr/bin/env bash
if ( [[ $(grep NC_TEST_SERVER_BASEURL ~/.gradle/gradle.properties | grep -v "#" -c) -gt 0 ]] ); then
echo "This will not use server in docker. Please comment in .gradle/gradle.properties. Aborting!"
exit 1
fi
## emulator
if ( [[ ! $(emulator -list-avds | grep uiComparison -c) -eq 0 ]] ); then
avdmanager delete avd -n uiComparison
if ( [[ $(emulator -list-avds | grep uiComparison -c) -eq 0 ]] ); then
(sleep 5; echo "no") | avdmanager create avd -n uiComparison -c 100M -k "system-images;android-27;google_apis;x86" --abi "google_apis/x86"
fi
if [ $1 == "debug" ]; then
emulator -avd uiComparison -no-snapshot -gpu swiftshader_indirect -no-audio -skin 500x833 1>/dev/null &
else
emulator -avd uiComparison -no-snapshot -gpu swiftshader_indirect -no-window -no-audio -skin 500x833 1>/dev/null &
fi
emulator -avd uiComparison -no-snapshot -gpu swiftshader_indirect -no-window -no-audio -skin 500x833 1>/dev/null &
PID=$(echo $!)
## server
docker run --name=uiComparison nextcloudci/server --entrypoint '/usr/local/bin/initnc.sh' 1>/dev/null &
docker run --name=uiComparison nextcloudci/server:server-3 1>/dev/null &
sleep 5
IP=$(docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' uiComparison)
@@ -28,55 +18,14 @@ if [[ $IP = "" ]]; then
exit 1
fi
## wait for server to finish
scripts/wait_for_server.sh $IP
## run on server
cp gradle.properties gradle.properties_
sed -i s"/server/$IP/" gradle.properties
scripts/wait_for_emulator.sh
# setup test server
docker exec uiComparison /bin/sh -c "su www-data -c \"OC_PASS=user1 php /var/www/html/occ user:add --password-from-env --display-name='User One' user1\""
docker exec uiComparison /bin/sh -c "su www-data -c \"OC_PASS=user2 php /var/www/html/occ user:add --password-from-env --display-name='User Two' user2\""
docker exec uiComparison /bin/sh -c "su www-data -c \"OC_PASS=user3 php /var/www/html/occ user:add --password-from-env --display-name='User Three' user3\""
docker exec uiComparison /bin/sh -c "su www-data -c \"php /var/www/html/occ user:setting user2 files quota 1G\""
docker exec uiComparison /bin/sh -c "su www-data -c \"php /var/www/html/occ group:add users\""
docker exec uiComparison /bin/sh -c "su www-data -c \"php /var/www/html/occ group:adduser users user1\""
docker exec uiComparison /bin/sh -c "su www-data -c \"php /var/www/html/occ group:adduser users user2\""
docker exec uiComparison /bin/sh -c "su www-data -c \"git clone -b master https://github.com/nextcloud/text.git /var/www/html/apps/text/\""
docker exec uiComparison /bin/sh -c "su www-data -c \"php /var/www/html/occ app:enable text\""
docker exec uiComparison /bin/sh -c "su www-data -c \"git clone -b master https://github.com/nextcloud/circles.git /var/www/html/apps/circles/\""
docker exec uiComparison /bin/sh -c "apt-get update; apt-get -y install composer"
docker exec uiComparison /bin/sh -c "su www-data -c \"cd /var/www/html/apps/circles; composer install\""
docker exec uiComparison /bin/sh -c "su www-data -c \"php /var/www/html/occ app:enable -f circles\""
docker exec uiComparison /bin/sh -c "su www-data -c \"php /var/www/html/occ config:app:set circles --value 1 allow_non_ssl_links\""
docker exec uiComparison /bin/sh -c "su www-data -c \"php /var/www/html/occ config:app:set circles --value 1 local_is_non_ssl\""
docker exec uiComparison /bin/sh -c "su www-data -c \"php /var/www/html/occ config:system:set allow_local_remote_servers --value true --type bool\""
docker exec uiComparison /bin/sh -c "su www-data -c \"php /var/www/html/occ circles:manage:create test public publicCircle\""
docker exec uiComparison /bin/sh -c "/usr/local/bin/run.sh"
## update/create all screenshots
scripts/wait_for_server.sh ${IP}
./gradlew executeScreenshotTests -Precord
## update screenshots in a class
#./gradlew executeScreenshotTests \
#-Precord \
#-Pandroid.testInstrumentationRunnerArguments.class=\
#com.owncloud.android.ui.dialog.SyncFileNotEnoughSpaceDialogFragmentTest
## update single screenshot within a class
#./gradlew executeScreenshotTests \
#-Precord \
#-Pandroid.testInstrumentationRunnerArguments.class=\
#com.owncloud.android.ui.dialog.SyncFileNotEnoughSpaceDialogFragmentTest#showNotEnoughSpaceDialogForFile
mv gradle.properties_ gradle.properties
if [ $1 == "debug" ]; then
exit
fi
# tidy up
kill $PID
docker stop uiComparison
+9 -42
View File
@@ -1,19 +1,5 @@
#!/usr/bin/env bash
upload() {
cd $1
find . -type d -exec curl -u $USER:$PASS -X MKCOL $URL/$REMOTE_FOLDER/$(echo {} | sed s#\./##) \;
find . -type f -exec curl -u $USER:$PASS -X PUT $URL/$REMOTE_FOLDER/$(echo {} | sed s#\./##) --upload-file {} \;
echo "Uploaded failing tests to https://www.kaminsky.me/nc-dev/android-integrationTests/$REMOTE_FOLDER"
curl -u $GITHUB_USER:$GITHUB_PASSWORD -X POST https://api.github.com/repos/nextcloud/android/issues/$PR/comments \
-d "{ \"body\" : \"$TYPE test failed: https://www.kaminsky.me/nc-dev/android-integrationTests/$REMOTE_FOLDER \" }"
exit 1
}
#1: LOG_USERNAME
#2: LOG_PASSWORD
#3: DRONE_BUILD_NUMBER
@@ -27,42 +13,23 @@ ID=$3
USER=$1
PASS=$2
TYPE=$4
PR=$5
GITHUB_USER=$6
GITHUB_PASSWORD=$7
REMOTE_FOLDER=$ID-$TYPE
FOLDER=$ID-$TYPE
set -e
if [ $TYPE = "IT" ]; then
FOLDER=build/reports/androidTests/connected/flavors/GPLAY
cd build/reports/androidTests/connected/flavors/GPLAY
elif [ $TYPE = "Unit" ]; then
FOLDER=build/reports/tests/testGplayDebugUnitTest
cd build/reports/tests/testGplayDebugUnitTest
else
FOLDER=build/reports/shot/verification
cd build/reports/shot/verification/
fi
if [ -e $FOLDER ]; then
upload $FOLDER
else
echo "$TYPE test failed, but no output was generated. Maybe a preliminary stage failed."
find . -type d -exec curl -u $USER:$PASS -X MKCOL $URL/$FOLDER/$(echo {} | sed s#\./##) \;
find . -type f -exec curl -u $USER:$PASS -X PUT $URL/$FOLDER/$(echo {} | sed s#\./##) --upload-file {} \;
curl -u $GITHUB_USER:$GITHUB_PASSWORD \
-X POST https://api.github.com/repos/nextcloud/android/issues/$PR/comments \
-d "{ \"body\" : \"$TYPE test failed, but no output was generated. Maybe a preliminary stage failed. \" }"
echo "Uploaded failing tests to https://www.kaminsky.me/nc-dev/android-integrationTests/$FOLDER"
if [ -e build/reports/androidTests/connected/flavors/GPLAY ] ; then
TYPE="IT"
upload "build/reports/androidTests/connected/flavors/GPLAY"
fi
curl -u $6:$7 -X POST https://api.github.com/repos/nextcloud/android/issues/$5/comments -d "{ \"body\" : \"$TYPE test failed: https://www.kaminsky.me/nc-dev/android-integrationTests/$FOLDER \" }"
if [ -e build/reports/tests/testGplayDebugUnitTest ] ; then
TYPE="Unit"
upload "build/reports/tests/testGplayDebugUnitTest"
fi
if [ -e build/reports/shot/verification ] ; then
TYPE="Screenshot"
upload "build/reports/shot/verification"
fi
fi
exit 1
+2 -7
View File
@@ -1,23 +1,18 @@
#!/usr/bin/env bash
status=""
counter=0
checkcounter=0
status=""
until [[ $status = "false" ]]; do
status=$(curl 2>/dev/null "http://$1/status.php" | jq .maintenance)
echo "($checkcounter) $status"
if [[ "$status" =~ "false" || "$status" = "" ]]; then
let "counter += 1"
if [[ $counter -gt 30 ]]; then
if [[ $counter -gt 2 ]]; then
echo "Failed to wait for server"
exit 1
fi
fi
let "checkcounter += 1"
sleep 10
done
echo "($checkcounter) Done"
+1 -2
View File
@@ -31,7 +31,7 @@
<Match>
<Or>
<Class name="~.*BindingImpl"/>
<Class name="~.*\.DataBinderMapperImpl" />
<Class name="~.*\.DataBinderMapperImpl"/>
</Or>
</Match>
@@ -53,7 +53,6 @@
<Bug pattern="PATH_TRAVERSAL_IN" />
<Bug pattern="ANDROID_EXTERNAL_FILE_ACCESS" />
<Bug pattern="BAS_BLOATED_ASSIGNMENT_SCOPE" />
<Bug pattern="IMC_IMMATURE_CLASS_BAD_SERIALVERSIONUID" />
<!-- This is unmanageable for now due to large amount of interconnected static state -->
<Bug pattern="FCCD_FIND_CLASS_CIRCULAR_DEPENDENCY" />
Binary file not shown.

Before

Width:  |  Height:  |  Size: 73 KiB

-23
View File
@@ -1,23 +0,0 @@
Java:
```java
private String getAppProcessName() {
String processName = "";
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
ActivityManager manager = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE);
final int ownPid = android.os.Process.myPid();
final List<ActivityManager.RunningAppProcessInfo> processes = manager.getRunningAppProcesses();
if (processes != null) {
for (ActivityManager.RunningAppProcessInfo info : processes) {
if (info.pid == ownPid) {
processName = info.processName;
break;
}
}
}
} else {
processName = Application.getProcessName();
}
return processName;
}
```
@@ -1,50 +0,0 @@
/*
*
* Nextcloud Android client application
*
* @author Tobias Kaminsky
* Copyright (C) 2020 Tobias Kaminsky
* Copyright (C) 2020 Nextcloud GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.nextcloud.client;
import android.Manifest;
import com.owncloud.android.AbstractIT;
import com.owncloud.android.ui.activities.ActivitiesActivity;
import org.junit.Rule;
import org.junit.Test;
import androidx.test.espresso.intent.rule.IntentsTestRule;
import androidx.test.rule.GrantPermissionRule;
public class ActivitiesActivityIT extends AbstractIT {
@Rule public IntentsTestRule<ActivitiesActivity> activityRule = new IntentsTestRule<>(ActivitiesActivity.class,
true,
false);
@Rule
public final GrantPermissionRule permissionRule = GrantPermissionRule.grant(
Manifest.permission.WRITE_EXTERNAL_STORAGE);
@Test
public void openDrawer() throws InterruptedException {
super.openDrawer(activityRule);
}
}
@@ -1,398 +0,0 @@
/*
*
* Nextcloud Android client application
*
* @author Tobias Kaminsky
* Copyright (C) 2020 Tobias Kaminsky
* Copyright (C) 2020 Nextcloud GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.nextcloud.client;
import android.accounts.AccountManager;
import com.owncloud.android.AbstractIT;
import com.owncloud.android.datamodel.ArbitraryDataProvider;
import com.owncloud.android.datamodel.OCFile;
import com.owncloud.android.db.OCUpload;
import com.owncloud.android.lib.common.accounts.AccountUtils;
import com.owncloud.android.lib.common.operations.RemoteOperationResult;
import com.owncloud.android.lib.common.utils.Log_OC;
import com.owncloud.android.lib.resources.e2ee.ToggleEncryptionRemoteOperation;
import com.owncloud.android.lib.resources.users.GetPrivateKeyOperation;
import com.owncloud.android.lib.resources.users.GetPublicKeyOperation;
import com.owncloud.android.lib.resources.users.SendCSROperation;
import com.owncloud.android.lib.resources.users.StorePrivateKeyOperation;
import com.owncloud.android.operations.RemoveFileOperation;
import com.owncloud.android.utils.CsrHelper;
import com.owncloud.android.utils.EncryptionUtils;
import com.owncloud.android.utils.FileStorageUtils;
import net.bytebuddy.utility.RandomString;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.util.ArrayList;
import java.util.Random;
import static com.owncloud.android.lib.resources.status.OwnCloudVersion.nextcloud_19;
import static junit.framework.TestCase.assertNotNull;
import static junit.framework.TestCase.assertTrue;
import static org.junit.Assume.assumeTrue;
public class EndToEndRandomIT extends AbstractIT {
public enum Action {
CREATE_FOLDER,
GO_INTO_FOLDER,
GO_UP,
UPLOAD_FILE
}
private static ArbitraryDataProvider arbitraryDataProvider;
private OCFile currentFolder;
private int actionCount = 20;
private String rootEncFolder = "/e/";
@BeforeClass
public static void initClass() {
arbitraryDataProvider = new ArbitraryDataProvider(targetContext.getContentResolver());
}
@Before
public void before() {
// tests only for NC19+
assumeTrue(getStorageManager()
.getCapability(account.name)
.getVersion()
.isNewerOrEqual(nextcloud_19)
);
}
@Test
public void run() throws Exception {
init();
for (int i = 0; i < actionCount; i++) {
Action nextAction = Action.values()[new Random().nextInt(Action.values().length)];
switch (nextAction) {
case CREATE_FOLDER:
createFolder(i);
break;
case GO_INTO_FOLDER:
goIntoFolder(i);
break;
case GO_UP:
goUp(i);
break;
case UPLOAD_FILE:
uploadFile(i);
break;
default:
Log_OC.d(this, "[" + i + "/" + actionCount + "]" + " Unknown action: " + nextAction);
break;
}
}
}
@Test
public void uploadOneFile() throws Exception {
init();
uploadFile(0);
}
@Test
public void createFolder() throws Exception {
init();
currentFolder = createFolder(0);
assertNotNull(currentFolder);
}
@Test
public void createSubFolders() throws Exception {
init();
currentFolder = createFolder(0);
assertNotNull(currentFolder);
currentFolder = createFolder(1);
assertNotNull(currentFolder);
currentFolder = createFolder(2);
assertNotNull(currentFolder);
}
@Test
public void createSubFoldersWithFiles() throws Exception {
init();
currentFolder = createFolder(0);
assertNotNull(currentFolder);
uploadFile(1);
uploadFile(1);
uploadFile(2);
currentFolder = createFolder(1);
assertNotNull(currentFolder);
uploadFile(11);
uploadFile(12);
uploadFile(13);
currentFolder = createFolder(2);
assertNotNull(currentFolder);
uploadFile(21);
uploadFile(22);
uploadFile(23);
}
@Test
public void pseudoRandom() throws Exception {
init();
uploadFile(1);
createFolder(2);
goIntoFolder(3);
goUp(4);
createFolder(5);
uploadFile(6);
goUp(7);
goIntoFolder(8);
goIntoFolder(9);
uploadFile(10);
}
@Test
public void deleteFile() throws Exception {
init();
uploadFile(1);
deleteFile(1);
}
private void init() throws Exception {
// create folder
createFolder(rootEncFolder);
OCFile encFolder = createFolder(rootEncFolder + RandomString.make(5) + "/");
// encrypt it
assertTrue(new ToggleEncryptionRemoteOperation(encFolder.getLocalId(),
encFolder.getRemotePath(),
true)
.execute(client).isSuccess());
encFolder.setEncrypted(true);
getStorageManager().saveFolder(encFolder, new ArrayList<>(), new ArrayList<>());
useExistingKeys();
rootEncFolder = encFolder.getDecryptedRemotePath();
currentFolder = encFolder;
}
private OCFile createFolder(int i) {
String path = currentFolder.getDecryptedRemotePath() + RandomString.make(5) + "/";
Log_OC.d(this, "[" + i + "/" + actionCount + "] " + "Create folder: " + path);
return createFolder(path);
}
private void goIntoFolder(int i) {
ArrayList<OCFile> folders = new ArrayList<>();
for (OCFile file : getStorageManager().getFolderContent(currentFolder, false)) {
if (file.isFolder()) {
folders.add(file);
}
}
if (folders.isEmpty()) {
Log_OC.d(this, "[" + i + "/" + actionCount + "] " + "Go into folder: No folders");
return;
}
currentFolder = folders.get(new Random().nextInt(folders.size()));
Log_OC.d(this,
"[" + i + "/" + actionCount + "] " + "Go into folder: " + currentFolder.getDecryptedRemotePath());
}
private void goUp(int i) {
if (currentFolder.getRemotePath().equals(rootEncFolder)) {
Log_OC.d(this,
"[" + i + "/" + actionCount + "] " + "Go up to folder: " + currentFolder.getDecryptedRemotePath());
return;
}
currentFolder = getStorageManager().getFileById(currentFolder.getParentId());
if (currentFolder == null) {
throw new RuntimeException("Current folder is null");
}
Log_OC.d(this,
"[" + i + "/" + actionCount + "] " + "Go up to folder: " + currentFolder.getDecryptedRemotePath());
}
private void uploadFile(int i) throws IOException {
String fileName = RandomString.make(5) + ".txt";
createFile(fileName, new Random().nextInt(50000));
String path = currentFolder.getRemotePath() + fileName;
Log_OC.d(this,
"[" + i + "/" + actionCount + "] " +
"Upload file to: " + currentFolder.getDecryptedRemotePath() + fileName);
OCUpload ocUpload = new OCUpload(FileStorageUtils.getSavePath(account.name) + File.separator + fileName,
path,
account.name);
uploadOCUpload(ocUpload);
}
private void deleteFile(int i) {
ArrayList<OCFile> files = new ArrayList<>();
for (OCFile file : getStorageManager().getFolderContent(currentFolder, false)) {
if (!file.isFolder()) {
files.add(file);
}
}
OCFile fileToDelete = files.get(new Random().nextInt(files.size()));
Log_OC.d(this,
"[" + i + "/" + actionCount + "] " +
"Delete file: " + currentFolder.getDecryptedRemotePath() + fileToDelete.getDecryptedFileName());
assertTrue(new RemoveFileOperation(fileToDelete,
false,
account,
false,
targetContext)
.execute(client, getStorageManager())
.isSuccess());
}
@Test
public void reInit() throws Exception {
// create folder
OCFile encFolder = createFolder(rootEncFolder);
// encrypt it
assertTrue(new ToggleEncryptionRemoteOperation(encFolder.getLocalId(),
encFolder.getRemotePath(),
true)
.execute(client).isSuccess());
encFolder.setEncrypted(true);
getStorageManager().saveFolder(encFolder, new ArrayList<>(), new ArrayList<>());
createKeys();
// delete keys
arbitraryDataProvider.deleteKeyForAccount(account.name, EncryptionUtils.PRIVATE_KEY);
arbitraryDataProvider.deleteKeyForAccount(account.name, EncryptionUtils.PUBLIC_KEY);
arbitraryDataProvider.deleteKeyForAccount(account.name, EncryptionUtils.MNEMONIC);
useExistingKeys();
}
private void useExistingKeys() throws Exception {
// download them from server
GetPublicKeyOperation publicKeyOperation = new GetPublicKeyOperation();
RemoteOperationResult publicKeyResult = publicKeyOperation.execute(account, targetContext);
assertTrue(publicKeyResult.isSuccess());
String publicKeyFromServer = (String) publicKeyResult.getData().get(0);
arbitraryDataProvider.storeOrUpdateKeyValue(account.name,
EncryptionUtils.PUBLIC_KEY,
publicKeyFromServer);
GetPrivateKeyOperation privateKeyOperation = new GetPrivateKeyOperation();
RemoteOperationResult privateKeyResult = privateKeyOperation.execute(account, targetContext);
assertTrue(privateKeyResult.isSuccess());
String privateKey = (String) privateKeyResult.getData().get(0);
String mnemonic = generateMnemonicString();
String decryptedPrivateKey = EncryptionUtils.decryptPrivateKey(privateKey, mnemonic);
arbitraryDataProvider.storeOrUpdateKeyValue(account.name,
EncryptionUtils.PRIVATE_KEY, decryptedPrivateKey);
Log_OC.d(this, "Private key successfully decrypted and stored");
arbitraryDataProvider.storeOrUpdateKeyValue(account.name, EncryptionUtils.MNEMONIC, mnemonic);
}
/*
TODO do not c&p code
*/
private void createKeys() throws Exception {
String publicKey;
// Create public/private key pair
KeyPair keyPair = EncryptionUtils.generateKeyPair();
// create CSR
AccountManager accountManager = AccountManager.get(targetContext);
String userId = accountManager.getUserData(account, AccountUtils.Constants.KEY_USER_ID);
String urlEncoded = CsrHelper.generateCsrPemEncodedString(keyPair, userId);
SendCSROperation operation = new SendCSROperation(urlEncoded);
RemoteOperationResult result = operation.execute(account, targetContext);
if (result.isSuccess()) {
publicKey = (String) result.getData().get(0);
} else {
throw new Exception("failed to send CSR", result.getException());
}
PrivateKey privateKey = keyPair.getPrivate();
String privateKeyString = EncryptionUtils.encodeBytesToBase64String(privateKey.getEncoded());
String privatePemKeyString = EncryptionUtils.privateKeyToPEM(privateKey);
String encryptedPrivateKey = EncryptionUtils.encryptPrivateKey(privatePemKeyString,
generateMnemonicString());
// upload encryptedPrivateKey
StorePrivateKeyOperation storePrivateKeyOperation = new StorePrivateKeyOperation(encryptedPrivateKey);
RemoteOperationResult storePrivateKeyResult = storePrivateKeyOperation.execute(account, targetContext);
if (storePrivateKeyResult.isSuccess()) {
arbitraryDataProvider.storeOrUpdateKeyValue(account.name, EncryptionUtils.PRIVATE_KEY,
privateKeyString);
arbitraryDataProvider.storeOrUpdateKeyValue(account.name, EncryptionUtils.PUBLIC_KEY, publicKey);
arbitraryDataProvider.storeOrUpdateKeyValue(account.name, EncryptionUtils.MNEMONIC,
generateMnemonicString());
} else {
throw new RuntimeException("Error uploading private key!");
}
}
private String generateMnemonicString() {
return "1 2 3 4 5 6";
}
}
@@ -28,33 +28,18 @@ import android.app.Activity;
import com.facebook.testing.screenshot.Screenshot;
import com.owncloud.android.AbstractIT;
import com.owncloud.android.R;
import com.owncloud.android.datamodel.OCFile;
import com.owncloud.android.lib.resources.files.CreateFolderRemoteOperation;
import com.owncloud.android.lib.resources.files.ExistenceCheckRemoteOperation;
import com.owncloud.android.lib.resources.files.SearchRemoteOperation;
import com.owncloud.android.lib.resources.shares.CreateShareRemoteOperation;
import com.owncloud.android.lib.resources.shares.OCShare;
import com.owncloud.android.lib.resources.shares.ShareType;
import com.owncloud.android.operations.CreateFolderOperation;
import com.owncloud.android.ui.activity.FileDisplayActivity;
import com.owncloud.android.ui.events.SearchEvent;
import org.greenrobot.eventbus.EventBus;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import androidx.test.espresso.contrib.DrawerActions;
import androidx.test.espresso.contrib.NavigationViewActions;
import androidx.test.espresso.intent.rule.IntentsTestRule;
import androidx.test.rule.GrantPermissionRule;
import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.action.ViewActions.click;
import static androidx.test.espresso.matcher.ViewMatchers.withId;
import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;
import static junit.framework.TestCase.assertEquals;
import static junit.framework.TestCase.assertTrue;
public class FileDisplayActivityIT extends AbstractIT {
@@ -67,10 +52,10 @@ public class FileDisplayActivityIT extends AbstractIT {
Manifest.permission.WRITE_EXTERNAL_STORAGE);
@Test
public void open() {
public void open() throws InterruptedException {
Activity sut = activityRule.launchActivity(null);
shortSleep();
Thread.sleep(3000);
Screenshot.snapActivity(sut).record();
}
@@ -84,69 +69,6 @@ public class FileDisplayActivityIT extends AbstractIT {
Screenshot.snapActivity(sut).record();
}
@Test
public void showShares() {
assertTrue(new ExistenceCheckRemoteOperation("/shareToAdmin/", true).execute(client).isSuccess());
assertTrue(new CreateFolderRemoteOperation("/shareToAdmin/", true).execute(client).isSuccess());
assertTrue(new CreateFolderRemoteOperation("/shareToGroup/", true).execute(client).isSuccess());
assertTrue(new CreateFolderRemoteOperation("/shareViaLink/", true).execute(client).isSuccess());
assertTrue(new CreateFolderRemoteOperation("/noShare/", true).execute(client).isSuccess());
// assertTrue(new CreateFolderRemoteOperation("/shareToCircle/", true).execute(client).isSuccess());
// share folder to user "admin"
assertTrue(new CreateShareRemoteOperation("/shareToAdmin/",
ShareType.USER,
"admin",
false,
"",
OCShare.MAXIMUM_PERMISSIONS_FOR_FOLDER)
.execute(client).isSuccess());
// share folder via public link
assertTrue(new CreateShareRemoteOperation("/shareViaLink/",
ShareType.PUBLIC_LINK,
"",
true,
"",
OCShare.READ_PERMISSION_FLAG)
.execute(client).isSuccess());
// share folder to group
Assert.assertTrue(new CreateShareRemoteOperation("/shareToGroup/",
ShareType.GROUP,
"users",
false,
"",
OCShare.DEFAULT_PERMISSION)
.execute(client).isSuccess());
// share folder to circle
// get share
// RemoteOperationResult searchResult = new GetShareesRemoteOperation("publicCircle", 1, 50).execute(client);
// assertTrue(searchResult.getLogMessage(), searchResult.isSuccess());
//
// JSONObject resultJson = (JSONObject) searchResult.getData().get(0);
// String circleId = resultJson.getJSONObject("value").getString("shareWith");
//
// assertTrue(new CreateShareRemoteOperation("/shareToCircle/",
// ShareType.CIRCLE,
// circleId,
// false,
// "",
// OCShare.DEFAULT_PERMISSION)
// .execute(client).isSuccess());
Activity sut = activityRule.launchActivity(null);
getInstrumentation().waitForIdleSync();
EventBus.getDefault().post(new SearchEvent("", SearchRemoteOperation.SearchType.SHARED_FILTER));
getInstrumentation().waitForIdleSync();
Screenshot.snapActivity(sut).record();
}
@Test
public void showAccounts() {
Activity sut = activityRule.launchActivity(null);
@@ -156,32 +78,4 @@ public class FileDisplayActivityIT extends AbstractIT {
Screenshot.snapActivity(sut).record();
}
@Test
public void allFiles() {
FileDisplayActivity sut = activityRule.launchActivity(null);
// given test folder
assertTrue(new CreateFolderOperation("/test/", account, targetContext)
.execute(client, getStorageManager())
.isSuccess());
// navigate into it
OCFile test = getStorageManager().getFileByPath("/test/");
sut.setFile(test);
sut.startSyncFolderOperation(test, false);
assertEquals(getStorageManager().getFileByPath("/test/"), sut.getCurrentDir());
// open drawer
onView(withId(R.id.drawer_layout)).perform(DrawerActions.open());
// click "all files"
onView(withId(R.id.nav_view))
.perform(NavigationViewActions.navigateTo(R.id.nav_all_files));
// then should be in root again
shortSleep();
assertEquals(getStorageManager().getFileByPath("/"), sut.getCurrentDir());
}
}
@@ -1,50 +0,0 @@
/*
*
* Nextcloud Android client application
*
* @author Tobias Kaminsky
* Copyright (C) 2020 Tobias Kaminsky
* Copyright (C) 2020 Nextcloud GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.nextcloud.client;
import android.Manifest;
import com.owncloud.android.AbstractIT;
import com.owncloud.android.ui.activity.NotificationsActivity;
import org.junit.Rule;
import org.junit.Test;
import androidx.test.espresso.intent.rule.IntentsTestRule;
import androidx.test.rule.GrantPermissionRule;
public class NotificationsActivityIT extends AbstractIT {
@Rule public IntentsTestRule<NotificationsActivity> activityRule = new IntentsTestRule<>(NotificationsActivity.class,
true,
false);
@Rule
public final GrantPermissionRule permissionRule = GrantPermissionRule.grant(
Manifest.permission.WRITE_EXTERNAL_STORAGE);
@Test
public void openDrawer() throws InterruptedException {
super.openDrawer(activityRule);
}
}
@@ -1,68 +0,0 @@
/*
*
* Nextcloud Android client application
*
* @author Tobias Kaminsky
* Copyright (C) 2020 Tobias Kaminsky
* Copyright (C) 2020 Nextcloud GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.nextcloud.client
import android.util.Log
import org.junit.rules.TestRule
import org.junit.runner.Description
import org.junit.runners.model.Statement
/**
* C&p from https://stackoverflow.com/questions/45635833/how-can-i-use-flakytest-annotation-now on 18.03.2020
*/
class RetryTestRule(val retryCount: Int = 5) : TestRule {
companion object {
private val TAG = RetryTestRule::class.java.simpleName
}
override fun apply(base: Statement, description: Description): Statement {
return statement(base, description)
}
@Suppress("TooGenericExceptionCaught") // and this exactly what we want here
private fun statement(base: Statement, description: Description): Statement {
return object : Statement() {
override fun evaluate() {
Log.e(TAG, "Evaluating ${description.methodName}")
var caughtThrowable: Throwable? = null
for (i in 0 until retryCount) {
try {
base.evaluate()
return
} catch (t: Throwable) {
caughtThrowable = t
Log.e(TAG, description.methodName + ": run " + (i + 1) + " failed")
}
}
Log.e(TAG, description.methodName + ": giving up after " + retryCount + " failures")
if (caughtThrowable != null)
throw caughtThrowable
}
}
}
}
@@ -1,50 +0,0 @@
/*
*
* Nextcloud Android client application
*
* @author Tobias Kaminsky
* Copyright (C) 2020 Tobias Kaminsky
* Copyright (C) 2020 Nextcloud GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.nextcloud.client;
import android.Manifest;
import com.owncloud.android.AbstractIT;
import com.owncloud.android.ui.activity.SyncedFoldersActivity;
import org.junit.Rule;
import org.junit.Test;
import androidx.test.espresso.intent.rule.IntentsTestRule;
import androidx.test.rule.GrantPermissionRule;
public class SyncedFoldersActivityIT extends AbstractIT {
@Rule public IntentsTestRule<SyncedFoldersActivity> activityRule = new IntentsTestRule<>(SyncedFoldersActivity.class,
true,
false);
@Rule
public final GrantPermissionRule permissionRule = GrantPermissionRule.grant(
Manifest.permission.WRITE_EXTERNAL_STORAGE);
@Test
public void openDrawer() throws InterruptedException {
super.openDrawer(activityRule);
}
}
@@ -1,50 +0,0 @@
/*
*
* Nextcloud Android client application
*
* @author Tobias Kaminsky
* Copyright (C) 2020 Tobias Kaminsky
* Copyright (C) 2020 Nextcloud GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.nextcloud.client;
import android.Manifest;
import com.owncloud.android.AbstractIT;
import com.owncloud.android.ui.activity.UploadListActivity;
import org.junit.Rule;
import org.junit.Test;
import androidx.test.espresso.intent.rule.IntentsTestRule;
import androidx.test.rule.GrantPermissionRule;
public class UploadListActivityActivityIT extends AbstractIT {
@Rule public IntentsTestRule<UploadListActivity> activityRule = new IntentsTestRule<>(UploadListActivity.class,
true,
false);
@Rule
public final GrantPermissionRule permissionRule = GrantPermissionRule.grant(
Manifest.permission.WRITE_EXTERNAL_STORAGE);
@Test
public void openDrawer() throws InterruptedException {
super.openDrawer(activityRule);
}
}
@@ -1,53 +0,0 @@
/*
* Nextcloud Android client application
*
* @author Chris Narkiewicz <[email protected]>
* Copyright (C) 2020 Chris Narkiewicz
* Copyright (C) 2020 Nextcloud GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.nextcloud.client.account
import android.os.Parcel
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class AnonymousUserTest {
@Test
fun anonymousUserImplementsParcelable() {
// GIVEN
// anonymous user instance
val original = AnonymousUser("test_account")
// WHEN
// instance is serialized into Parcel
// instance is retrieved from Parcel
val parcel = Parcel.obtain()
parcel.setDataPosition(0)
parcel.writeParcelable(original, 0)
parcel.setDataPosition(0)
val retrieved = parcel.readParcelable<User>(User::class.java.classLoader)
// THEN
// retrieved instance in distinct
// instances are equal
Assert.assertNotSame(original, retrieved)
Assert.assertTrue(retrieved is AnonymousUser)
Assert.assertEquals(original, retrieved)
}
}
@@ -1,119 +0,0 @@
/*
* Nextcloud Android client application
*
* @author Chris Narkiewicz <[email protected]>
* Copyright (C) 2020 Chris Narkiewicz
* Copyright (C) 2020 Nextcloud GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.nextcloud.client.account
import android.accounts.Account
import android.net.Uri
import android.os.Parcel
import com.owncloud.android.lib.common.OwnCloudAccount
import com.owncloud.android.lib.common.OwnCloudBasicCredentials
import com.owncloud.android.lib.resources.status.OwnCloudVersion
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotSame
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import java.net.URI
class RegisteredUserTest {
private companion object {
fun buildTestUser(accountName: String): RegisteredUser {
val uri = Uri.parse("https://nextcloud.localhost.localdomain")
val credentials = OwnCloudBasicCredentials("user", "pass")
val account = Account(accountName, "test-type")
val ownCloudAccount = OwnCloudAccount(uri, credentials)
val server = Server(
uri = URI(uri.toString()),
version = OwnCloudVersion.nextcloud_17
)
return RegisteredUser(
account = account,
ownCloudAccount = ownCloudAccount,
server = server
)
}
}
private lateinit var user: RegisteredUser
@Before
fun setUp() {
user = buildTestUser("[email protected]")
}
@Test
fun registeredUserImplementsParcelable() {
// GIVEN
// registered user instance
// WHEN
// instance is serialized into Parcel
// instance is retrieved from Parcel
val parcel = Parcel.obtain()
parcel.setDataPosition(0)
parcel.writeParcelable(user, 0)
parcel.setDataPosition(0)
val deserialized = parcel.readParcelable<User>(User::class.java.classLoader)
// THEN
// retrieved instance in distinct
// instances are equal
assertNotSame(user, deserialized)
assertTrue(deserialized is RegisteredUser)
assertEquals(user, deserialized)
}
@Test
fun accountNamesEquality() {
// GIVEN
// registered user instance with lower-case account name
// registered user instance with mixed-case account name
val user1 = buildTestUser("account_name")
val user2 = buildTestUser("Account_Name")
// WHEN
// account names are checked for equality
val equal = user1.nameEquals(user2)
// THEN
// account names are equal
assertTrue(equal)
}
@Test
fun accountNamesEqualityCheckIsNullSafe() {
// GIVEN
// registered user instance with lower-case account name
// null account
val user1 = buildTestUser("account_name")
val user2: User? = null
// WHEN
// account names are checked for equality against null
val equal = user1.nameEquals(user2)
// THEN
// account names are not equal
assertFalse(equal)
}
}
@@ -1,63 +0,0 @@
/*
*
* Nextcloud Android client application
*
* @author Tobias Kaminsky
* Copyright (C) 2020 Tobias Kaminsky
* Copyright (C) 2020 Nextcloud GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.nextcloud.client.etm
import android.app.Activity
import androidx.test.espresso.intent.rule.IntentsTestRule
import androidx.test.internal.runner.junit4.statement.UiThreadStatement
import com.facebook.testing.screenshot.Screenshot
import com.owncloud.android.AbstractIT
import org.junit.Rule
import org.junit.Test
class EtmActivityTest : AbstractIT() {
@get:Rule
var activityRule = IntentsTestRule(EtmActivity::class.java, true, false)
@Test
fun overview() {
val sut: Activity = activityRule.launchActivity(null)
waitForIdleSync()
Screenshot.snapActivity(sut).record()
}
@Test
fun preferences() {
val sut: EtmActivity = activityRule.launchActivity(null)
UiThreadStatement.runOnUiThread { sut.vm.onPageSelected(0) }
Screenshot.snapActivity(sut).record()
}
@Test
fun accounts() {
val sut: EtmActivity = activityRule.launchActivity(null)
UiThreadStatement.runOnUiThread { sut.vm.onPageSelected(1) }
Screenshot.snapActivity(sut).record()
}
}
@@ -1,177 +0,0 @@
/*
* Nextcloud Android client application
*
* @author Chris Narkiewicz
* Copyright (C) 2020 Chris Narkiewicz <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.nextcloud.client.integration.deck
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.content.pm.ResolveInfo
import androidx.test.platform.app.InstrumentationRegistry
import com.nextcloud.client.account.User
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.anyOrNull
import com.nhaarman.mockitokotlin2.never
import com.nhaarman.mockitokotlin2.times
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.whenever
import com.owncloud.android.lib.resources.notifications.models.Notification
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import org.junit.runners.Suite
import org.mockito.Mock
import org.mockito.MockitoAnnotations
@RunWith(Suite::class)
@Suite.SuiteClasses(
DeckApiTest.DeckIsInstalled::class,
DeckApiTest.DeckIsNotInstalled::class
)
class DeckApiTest {
abstract class Fixture {
@Mock
lateinit var packageManager: PackageManager
lateinit var context: Context
@Mock
lateinit var user: User
lateinit var deck: DeckApiImpl
@Before
fun setUpFixture() {
MockitoAnnotations.initMocks(this)
context = InstrumentationRegistry.getInstrumentation().targetContext
deck = DeckApiImpl(context, packageManager)
}
}
@RunWith(Parameterized::class)
class DeckIsInstalled : Fixture() {
@Parameterized.Parameter(0)
lateinit var installedDeckPackage: String
companion object {
@Parameterized.Parameters
@JvmStatic
fun initParametrs(): Array<String> {
return DeckApiImpl.DECK_APP_PACKAGES
}
}
@Before
fun setUp() {
whenever(packageManager.resolveActivity(any(), any())).thenAnswer {
val intent = it.getArgument<Intent>(0)
return@thenAnswer if (intent.component?.packageName == installedDeckPackage) {
ResolveInfo()
} else {
null
}
}
}
@Test
fun can_forward_deck_notification() {
// GIVEN
// notification to deck arrives
val notification = Notification().apply { app = "deck" }
// WHEN
// deck action is created
val forwardActionIntent = deck.createForwardToDeckActionIntent(notification, user)
// THEN
// open action is created
assertTrue("Failed for $installedDeckPackage", forwardActionIntent.isPresent)
}
@Test
fun notifications_from_other_apps_are_ignored() {
// GIVEN
// notification from other app arrives
val deckNotification = Notification().apply {
app = "some_other_app"
}
// WHEN
// deck action is created
val openDeckActionIntent = deck.createForwardToDeckActionIntent(deckNotification, user)
// THEN
// deck application is not being resolved
// open action is not created
verify(packageManager, never()).resolveActivity(anyOrNull(), anyOrNull())
assertFalse(openDeckActionIntent.isPresent)
}
}
class DeckIsNotInstalled : Fixture() {
@Before
fun setUp() {
whenever(packageManager.resolveActivity(any(), any())).thenReturn(null)
}
@Test
fun cannot_forward_deck_notification() {
// GIVEN
// notification is coming from deck app
val notification = Notification().apply {
app = DeckApiImpl.APP_NAME
}
// WHEN
// creating open in deck action
val openDeckActionIntent = deck.createForwardToDeckActionIntent(notification, user)
// THEN
// deck application is being resolved using all known packages
// open action is not created
verify(packageManager, times(DeckApiImpl.DECK_APP_PACKAGES.size)).resolveActivity(anyOrNull(), anyOrNull())
assertFalse(openDeckActionIntent.isPresent)
}
@Test
fun notifications_from_other_apps_are_ignored() {
// GIVEN
// notification is coming from other app
val notification = Notification().apply {
app = "some_other_app"
}
// WHEN
// creating open in deck action
val openDeckActionIntent = deck.createForwardToDeckActionIntent(notification, user)
// THEN
// deck application is not being resolved
// open action is not created
verify(packageManager, never()).resolveActivity(anyOrNull(), anyOrNull())
assertFalse(openDeckActionIntent.isPresent)
}
}
}
@@ -1,430 +0,0 @@
/*
* Nextcloud Android client application
*
* @author Chris Narkiewicz
* Copyright (C) 2020 Chris Narkiewicz <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.nextcloud.client.jobs
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import androidx.test.annotation.UiThreadTest
import androidx.work.Data
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.ExistingWorkPolicy
import androidx.work.OneTimeWorkRequest
import androidx.work.PeriodicWorkRequest
import androidx.work.WorkInfo
import androidx.work.WorkManager
import com.nextcloud.client.account.User
import com.nextcloud.client.core.Clock
import com.nhaarman.mockitokotlin2.KArgumentCaptor
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.argThat
import com.nhaarman.mockitokotlin2.argumentCaptor
import com.nhaarman.mockitokotlin2.eq
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.whenever
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Suite
import org.mockito.ArgumentMatcher
import java.util.Date
import java.util.UUID
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeoutException
/**
* When using IDE to run enire Suite, make sure tests are run using Android Instrumentation Test
* runner. By default IDE runs normal JUnit - this is AS problem. One must configure the
* test run manually.
*/
@RunWith(Suite::class)
@Suite.SuiteClasses(
BackgroundJobManagerTest.Manager::class,
BackgroundJobManagerTest.ContentObserver::class,
BackgroundJobManagerTest.PeriodicContactsBackup::class,
BackgroundJobManagerTest.ImmediateContactsBackup::class,
BackgroundJobManagerTest.ImmediateContactsImport::class,
BackgroundJobManagerTest.Tags::class
)
class BackgroundJobManagerTest {
/**
* Used to help with ambiguous type inference
*/
class IsOneTimeWorkRequest : ArgumentMatcher<OneTimeWorkRequest> {
override fun matches(argument: OneTimeWorkRequest?): Boolean = true
}
/**
* Used to help with ambiguous type inference
*/
class IsPeriodicWorkRequest : ArgumentMatcher<PeriodicWorkRequest> {
override fun matches(argument: PeriodicWorkRequest?): Boolean = true
}
abstract class Fixture {
companion object {
internal const val USER_ACCOUNT_NAME = "user@nextcloud"
internal val TIMESTAMP = System.currentTimeMillis()
}
internal lateinit var user: User
internal lateinit var workManager: WorkManager
internal lateinit var clock: Clock
internal lateinit var backgroundJobManager: BackgroundJobManagerImpl
@Before
fun setUpFixture() {
user = mock()
whenever(user.accountName).thenReturn(USER_ACCOUNT_NAME)
workManager = mock()
clock = mock()
whenever(clock.currentTime).thenReturn(TIMESTAMP)
whenever(clock.currentDate).thenReturn(Date(TIMESTAMP))
backgroundJobManager = BackgroundJobManagerImpl(workManager, clock)
}
fun assertHasRequiredTags(tags: Set<String>, jobName: String, user: User? = null) {
assertTrue("""'all' tag is mandatory""", tags.contains("*"))
assertTrue("name tag is mandatory", tags.contains(BackgroundJobManagerImpl.formatNameTag(jobName, user)))
assertTrue("timestamp tag is mandatory", tags.contains(BackgroundJobManagerImpl.formatTimeTag(TIMESTAMP)))
if (user != null) {
assertTrue("user tag is mandatory", tags.contains(BackgroundJobManagerImpl.formatUserTag(user)))
}
}
fun buildWorkInfo(index: Long): WorkInfo = WorkInfo(
UUID.randomUUID(),
WorkInfo.State.RUNNING,
Data.Builder().build(),
listOf(BackgroundJobManagerImpl.formatTimeTag(1581820284000)),
Data.Builder().build(),
1
)
}
class Manager : Fixture() {
class SyncObserver<T> : Observer<T> {
val latch = CountDownLatch(1)
var value: T? = null
override fun onChanged(t: T) {
value = t
latch.countDown()
}
fun getValue(timeout: Long = 3, timeUnit: TimeUnit = TimeUnit.SECONDS): T? {
val result = latch.await(timeout, timeUnit)
if (!result) {
throw TimeoutException()
}
return value
}
}
@Test
@UiThreadTest
fun get_all_job_info() {
// GIVEN
// work manager has 2 registered workers
val platformWorkInfo = listOf(
buildWorkInfo(0),
buildWorkInfo(1),
buildWorkInfo(2)
)
val lv = MutableLiveData<List<WorkInfo>>()
lv.value = platformWorkInfo
whenever(workManager.getWorkInfosByTagLiveData(eq("*"))).thenReturn(lv)
// WHEN
// job info for all jobs is requested
val jobs = backgroundJobManager.jobs
// THEN
// live data with job info is returned
// live data contains 2 job info instances
// job info is sorted by timestamp from newest to oldest
assertNotNull(jobs)
val observer = SyncObserver<List<JobInfo>>()
jobs.observeForever(observer)
val jobInfo = observer.getValue()
assertNotNull(jobInfo)
assertEquals(platformWorkInfo.size, jobInfo?.size)
jobInfo?.let {
assertEquals(platformWorkInfo[2].id, it[0].id)
assertEquals(platformWorkInfo[1].id, it[1].id)
assertEquals(platformWorkInfo[0].id, it[2].id)
}
}
@Test
fun cancel_all_jobs() {
// WHEN
// all jobs are cancelled
backgroundJobManager.cancelAllJobs()
// THEN
// all jobs with * tag are cancelled
verify(workManager).cancelAllWorkByTag(BackgroundJobManagerImpl.TAG_ALL)
}
}
class ContentObserver : Fixture() {
private lateinit var request: OneTimeWorkRequest
@Before
fun setUp() {
val requestCaptor: KArgumentCaptor<OneTimeWorkRequest> = argumentCaptor()
backgroundJobManager.scheduleContentObserverJob()
verify(workManager).enqueueUniqueWork(
any(),
any(),
requestCaptor.capture()
)
assertEquals(1, requestCaptor.allValues.size)
request = requestCaptor.firstValue
}
@Test
fun job_is_unique_and_replaces_previous_job() {
verify(workManager).enqueueUniqueWork(
eq(BackgroundJobManagerImpl.JOB_CONTENT_OBSERVER),
eq(ExistingWorkPolicy.REPLACE),
argThat(IsOneTimeWorkRequest())
)
}
@Test
fun job_request_has_mandatory_tags() {
assertHasRequiredTags(request.tags, BackgroundJobManagerImpl.JOB_CONTENT_OBSERVER)
}
}
class PeriodicContactsBackup : Fixture() {
private lateinit var request: PeriodicWorkRequest
@Before
fun setUp() {
val requestCaptor: KArgumentCaptor<PeriodicWorkRequest> = argumentCaptor()
backgroundJobManager.schedulePeriodicContactsBackup(user)
verify(workManager).enqueueUniquePeriodicWork(
any(),
any(),
requestCaptor.capture()
)
assertEquals(1, requestCaptor.allValues.size)
request = requestCaptor.firstValue
}
@Test
fun job_is_unique_for_user() {
verify(workManager).enqueueUniquePeriodicWork(
eq(BackgroundJobManagerImpl.JOB_PERIODIC_CONTACTS_BACKUP),
eq(ExistingPeriodicWorkPolicy.KEEP),
argThat(IsPeriodicWorkRequest())
)
}
@Test
fun job_request_has_mandatory_tags() {
assertHasRequiredTags(request.tags, BackgroundJobManagerImpl.JOB_PERIODIC_CONTACTS_BACKUP, user)
}
}
class ImmediateContactsBackup : Fixture() {
private lateinit var workInfo: MutableLiveData<WorkInfo>
private lateinit var jobInfo: LiveData<JobInfo?>
private lateinit var request: OneTimeWorkRequest
@Before
fun setUp() {
val requestCaptor: KArgumentCaptor<OneTimeWorkRequest> = argumentCaptor()
workInfo = MutableLiveData()
whenever(workManager.getWorkInfoByIdLiveData(any())).thenReturn(workInfo)
jobInfo = backgroundJobManager.startImmediateContactsBackup(user)
verify(workManager).enqueueUniqueWork(
any(),
any(),
requestCaptor.capture()
)
assertEquals(1, requestCaptor.allValues.size)
request = requestCaptor.firstValue
}
@Test
fun job_is_unique_for_user() {
verify(workManager).enqueueUniqueWork(
eq(BackgroundJobManagerImpl.JOB_IMMEDIATE_CONTACTS_BACKUP),
eq(ExistingWorkPolicy.KEEP),
argThat(IsOneTimeWorkRequest())
)
}
@Test
fun job_request_has_mandatory_tags() {
assertHasRequiredTags(request.tags, BackgroundJobManagerImpl.JOB_IMMEDIATE_CONTACTS_BACKUP, user)
}
@Test
@UiThreadTest
fun job_info_is_obtained_from_work_info() {
// GIVEN
// work info is available
workInfo.value = buildWorkInfo(0)
// WHEN
// job info has listener
jobInfo.observeForever {}
// THEN
// converted value is available
assertNotNull(jobInfo.value)
assertEquals(workInfo.value?.id, jobInfo.value?.id)
}
}
class ImmediateContactsImport : Fixture() {
private lateinit var workInfo: MutableLiveData<WorkInfo>
private lateinit var jobInfo: LiveData<JobInfo?>
private lateinit var request: OneTimeWorkRequest
@Before
fun setUp() {
val requestCaptor: KArgumentCaptor<OneTimeWorkRequest> = argumentCaptor()
workInfo = MutableLiveData()
whenever(workManager.getWorkInfoByIdLiveData(any())).thenReturn(workInfo)
jobInfo = backgroundJobManager.startImmediateContactsImport(
contactsAccountName = "name",
contactsAccountType = "type",
vCardFilePath = "/path/to/vcard/file",
selectedContacts = intArrayOf(1, 2, 3)
)
verify(workManager).enqueueUniqueWork(
any(),
any(),
requestCaptor.capture()
)
assertEquals(1, requestCaptor.allValues.size)
request = requestCaptor.firstValue
}
@Test
fun job_is_unique() {
verify(workManager).enqueueUniqueWork(
eq(BackgroundJobManagerImpl.JOB_IMMEDIATE_CONTACTS_IMPORT),
eq(ExistingWorkPolicy.KEEP),
argThat(IsOneTimeWorkRequest())
)
}
@Test
fun job_request_has_mandatory_tags() {
assertHasRequiredTags(request.tags, BackgroundJobManagerImpl.JOB_IMMEDIATE_CONTACTS_IMPORT)
}
@Test
@UiThreadTest
fun job_info_is_obtained_from_work_info() {
// GIVEN
// work info is available
workInfo.value = buildWorkInfo(0)
// WHEN
// job info has listener
jobInfo.observeForever {}
// THEN
// converted value is available
assertNotNull(jobInfo.value)
assertEquals(workInfo.value?.id, jobInfo.value?.id)
}
}
class Tags {
@Test
fun split_tag_key_and_value() {
// GIVEN
// valid tag
// tag has colons in value part
val tag = "${BackgroundJobManagerImpl.TAG_PREFIX_NAME}:value:with:colons and spaces"
// WHEN
// tag is parsed
val parsedTag = BackgroundJobManagerImpl.parseTag(tag)
// THEN
// key-value pair is returned
// key is first
// value with colons is second
assertNotNull(parsedTag)
assertEquals(BackgroundJobManagerImpl.TAG_PREFIX_NAME, parsedTag?.first)
assertEquals("value:with:colons and spaces", parsedTag?.second)
}
@Test
fun tags_with_invalid_prefixes_are_rejected() {
// GIVEN
// tag prefix is not on allowed prefixes list
val tag = "invalidprefix:value"
BackgroundJobManagerImpl.PREFIXES.forEach {
assertFalse(tag.startsWith(it))
}
// WHEN
// tag is parsed
val parsedTag = BackgroundJobManagerImpl.parseTag(tag)
// THEN
// tag is rejected
assertNull(parsedTag)
}
@Test
fun strings_without_colon_are_rejected() {
// GIVEN
// strings that are not tags
val tags = listOf(
BackgroundJobManagerImpl.TAG_ALL,
BackgroundJobManagerImpl.TAG_PREFIX_NAME,
"simplestring",
""
)
tags.forEach {
// WHEN
// string is parsed
val parsedTag = BackgroundJobManagerImpl.parseTag(it)
// THEN
// tag is rejected
assertNull(parsedTag)
}
}
}
}
@@ -1,129 +0,0 @@
/*
* Nextcloud Android client application
*
* @author Chris Narkiewicz
* Copyright (C) 2020 Chris Narkiewicz <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.nextcloud.client.migrations
import android.content.Context
import android.content.SharedPreferences
import androidx.test.platform.app.InstrumentationRegistry
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.eq
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.whenever
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
class MigrationsDbTest {
private lateinit var context: Context
private lateinit var store: MockSharedPreferences
private lateinit var db: MigrationsDb
@Before
fun setUp() {
context = InstrumentationRegistry.getInstrumentation().context
store = MockSharedPreferences()
assertTrue("State from previous test run found?", store.all.isEmpty())
db = MigrationsDb(store)
}
@Test
fun applied_migrations_are_returned_in_order() {
// GIVEN
// some migrations are marked as applied
// migration ids are stored in random order
val mockStore: SharedPreferences = mock()
val storedMigrationIds = LinkedHashSet<String>()
storedMigrationIds.apply {
add("3")
add("0")
add("2")
add("1")
}
whenever(mockStore.getStringSet(eq(MigrationsDb.DB_KEY_APPLIED_MIGRATIONS), any()))
.thenReturn(storedMigrationIds)
// WHEN
// applied migration ids are retrieved
val db = MigrationsDb(mockStore)
val ids = db.getAppliedMigrations()
// THEN
// returned list is sorted
assertEquals(ids, ids.sorted())
}
@Test
@Suppress("MagicNumber")
fun registering_new_applied_migration_preserves_old_ids() {
// WHEN
// some applied migrations are registered
val appliedMigrationIds = setOf("0", "1", "2")
store.edit().putStringSet(MigrationsDb.DB_KEY_APPLIED_MIGRATIONS, appliedMigrationIds).apply()
// WHEN
// new set of migration ids are registered
// some ids are added again
db.addAppliedMigration(2, 3, 4)
// THEN
// new ids are appended to set of existing ids
val expectedIds = setOf("0", "1", "2", "3", "4")
val storedIds = store.getStringSet(MigrationsDb.DB_KEY_APPLIED_MIGRATIONS, mutableSetOf())
assertEquals(expectedIds, storedIds)
}
@Test
fun failed_status_sets_status_flag_and_error_message() {
// GIVEN
// failure flag is not set
assertFalse(db.isFailed)
// WHEN
// failure status is set
val failureReason = "error message"
db.setFailed(0, failureReason)
// THEN
// failed flag is set
// error message is set
assertTrue(db.isFailed)
assertEquals(failureReason, db.failureReason)
}
@Test
fun last_migrated_version_is_set() {
// GIVEN
// last migrated version is not set
val oldVersion = db.lastMigratedVersion
assertEquals(MigrationsDb.NO_LAST_MIGRATED_VERSION, oldVersion)
// WHEN
// migrated version is set to a new value
val newVersion = 200
db.lastMigratedVersion = newVersion
// THEN
// new value is stored
assertEquals(newVersion, db.lastMigratedVersion)
}
}
@@ -1,271 +0,0 @@
/*
* Nextcloud Android client application
*
* @author Chris Narkiewicz
* Copyright (C) 2020 Chris Narkiewicz <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.nextcloud.client.migrations
import androidx.test.annotation.UiThreadTest
import com.nextcloud.client.appinfo.AppInfo
import com.nextcloud.client.core.ManualAsyncRunner
import com.nhaarman.mockitokotlin2.inOrder
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.never
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.whenever
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.mockito.Mock
import org.mockito.MockitoAnnotations
class MigrationsManagerTest {
companion object {
const val OLD_APP_VERSION = 41
const val NEW_APP_VERSION = 42
}
lateinit var migrationStep1: Runnable
lateinit var migrationStep2: Runnable
lateinit var migrationStep3: Runnable
lateinit var migrations: List<Migrations.Step>
@Mock
lateinit var appInfo: AppInfo
lateinit var migrationsDbStore: MockSharedPreferences
lateinit var migrationsDb: MigrationsDb
lateinit var asyncRunner: ManualAsyncRunner
internal lateinit var migrationsManager: MigrationsManagerImpl
@Before
fun setUp() {
MockitoAnnotations.initMocks(this)
migrationStep1 = mock()
migrationStep2 = mock()
migrationStep3 = mock()
migrations = listOf(
object : Migrations.Step(0, "first migration", true) {
override fun run() {
migrationStep1.run()
}
},
object : Migrations.Step(1, "second optional migration", false) {
override fun run() {
migrationStep2.run()
}
},
object : Migrations.Step(2, "third migration", true) {
override fun run() {
migrationStep3.run()
}
}
)
asyncRunner = ManualAsyncRunner()
migrationsDbStore = MockSharedPreferences()
migrationsDb = MigrationsDb(migrationsDbStore)
whenever(appInfo.versionCode).thenReturn(NEW_APP_VERSION)
migrationsManager = MigrationsManagerImpl(
appInfo = appInfo,
migrationsDb = migrationsDb,
asyncRunner = asyncRunner,
migrations = migrations
)
}
private fun assertMigrationsRun(vararg migrationSteps: Runnable) {
inOrder(migrationSteps).apply {
migrationSteps.forEach {
verify(it.run())
}
}
}
@Test
fun inital_status_is_unknown() {
// GIVEN
// migration manager has not been used yets
// THEN
// status is not set
assertEquals(MigrationsManager.Status.UNKNOWN, migrationsManager.status.value)
}
@Test
@UiThreadTest
fun migrations_are_scheduled_on_background_thread() {
// GIVEN
// migrations can be applied
assertEquals(0, migrationsDb.getAppliedMigrations().size)
// WHEN
// migration is started
val count = migrationsManager.startMigration()
// THEN
// all migrations are scheduled on background thread
// single task is scheduled
assertEquals(migrations.size, count)
assertEquals(1, asyncRunner.size)
assertEquals(MigrationsManager.Status.RUNNING, migrationsManager.status.value)
}
@Test
@UiThreadTest
fun applied_migrations_are_recorded() {
// GIVEN
// no migrations are applied yet
// current app version is newer then last recorded migrated version
whenever(appInfo.versionCode).thenReturn(NEW_APP_VERSION)
migrationsDb.lastMigratedVersion = OLD_APP_VERSION
// WHEN
// migration is run
val count = migrationsManager.startMigration()
assertTrue(asyncRunner.runOne())
// THEN
// total migrations count is returned
// migration functions are called
// applied migrations are recorded
// new app version code is recorded
assertEquals(migrations.size, count)
inOrder(migrationStep1, migrationStep2, migrationStep3).apply {
verify(migrationStep1).run()
verify(migrationStep2).run()
verify(migrationStep3).run()
}
val allAppliedIds = migrations.map { it.id }
assertEquals(allAppliedIds, migrationsDb.getAppliedMigrations())
assertEquals(NEW_APP_VERSION, migrationsDb.lastMigratedVersion)
}
@Test
@UiThreadTest
fun migration_error_is_recorded() {
// GIVEN
// no migrations applied yet
// no prior failed migrations
assertFalse(migrationsDb.isFailed)
assertEquals(MigrationsDb.NO_FAILED_MIGRATION_ID, migrationsDb.failedMigrationId)
// WHEN
// migrations are applied
// one migration throws
val lastMigration = migrations.findLast { it.mandatory } ?: throw IllegalStateException("Test fixture error")
val errorMessage = "error message"
whenever(lastMigration.run()).thenThrow(RuntimeException(errorMessage))
migrationsManager.startMigration()
assertTrue(asyncRunner.runOne())
// THEN
// failure is marked in the migration db
// failure message is recorded
// failed migration id is recorded
assertEquals(MigrationsManager.Status.FAILED, migrationsManager.status.value)
assertTrue(migrationsDb.isFailed)
assertEquals(errorMessage, migrationsDb.failureReason)
assertEquals(lastMigration.id, migrationsDb.failedMigrationId)
}
@Test
@UiThreadTest
fun migrations_are_not_run_if_already_run_for_an_app_version() {
// GIVEN
// migrations were already run for the current app version
whenever(appInfo.versionCode).thenReturn(NEW_APP_VERSION)
migrationsDb.lastMigratedVersion = NEW_APP_VERSION
// WHEN
// app is migrated again
val migrationCount = migrationsManager.startMigration()
// THEN
// migration processing is skipped entirely
// status is set to applied
assertEquals(0, migrationCount)
listOf(migrationStep1, migrationStep2, migrationStep3).forEach {
verify(it, never()).run()
}
assertEquals(MigrationsManager.Status.APPLIED, migrationsManager.status.value)
}
@Test
@UiThreadTest
fun new_app_version_is_marked_as_migrated_if_no_new_migrations_are_available() {
// GIVEN
// migrations were applied in previous version
// new version has no new migrations
whenever(appInfo.versionCode).thenReturn(NEW_APP_VERSION)
migrationsDb.lastMigratedVersion = OLD_APP_VERSION
migrations.forEach {
migrationsDb.addAppliedMigration(it.id)
}
// WHEN
// migration is started
val startedCount = migrationsManager.startMigration()
// THEN
// no new migrations are run
// new version is marked as migrated
assertEquals(0, startedCount)
assertEquals(
NEW_APP_VERSION,
migrationsDb.lastMigratedVersion
)
}
@Test
@UiThreadTest
fun optional_migration_failure_does_not_trigger_a_migration_failure() {
// GIVEN
// pending migrations
// mandatory migrations are passing
// one migration is optional and fails
assertEquals("Fixture should provide 1 optional, failing migration",
1,
migrations.count { !it.mandatory }
)
val optionalFailingMigration = migrations.first { !it.mandatory }
whenever(optionalFailingMigration.run()).thenThrow(RuntimeException())
// WHEN
// migration is started
val startedCount = migrationsManager.startMigration()
asyncRunner.runOne()
assertEquals(migrations.size, startedCount)
// THEN
// mandatory migrations are marked as applied
// optional failed migration is not marked
// no error
// status is applied
// failed migration is available during next migration
val appliedMigrations = migrations.filter { it.mandatory }.map { it.id }
assertTrue("Fixture error", appliedMigrations.isNotEmpty())
assertEquals(appliedMigrations, migrationsDb.getAppliedMigrations())
assertFalse(migrationsDb.isFailed)
assertEquals(MigrationsManager.Status.APPLIED, migrationsManager.status.value)
}
}
@@ -1,111 +0,0 @@
/*
* Nextcloud Android client application
*
* @author Chris Narkiewicz
* Copyright (C) 2020 Chris Narkiewicz <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.nextcloud.client.migrations
import android.content.SharedPreferences
import java.lang.UnsupportedOperationException
import java.util.TreeMap
/**
* This shared preferences implementation uses in-memory value store
* and it can be used in tests without using global, file-backed storage,
* improving test isolation.
*
* The implementation is not thread-safe.
*/
@Suppress("TooManyFunctions")
class MockSharedPreferences : SharedPreferences {
class MockEditor(val store: MutableMap<String?, Any?>) : SharedPreferences.Editor {
val editorStore: MutableMap<String?, Any?> = TreeMap()
override fun clear(): SharedPreferences.Editor = throw UnsupportedOperationException()
override fun putLong(key: String?, value: Long): SharedPreferences.Editor =
throw UnsupportedOperationException("Implement as needed")
override fun putInt(key: String?, value: Int): SharedPreferences.Editor {
editorStore.put(key, value)
return this
}
override fun remove(key: String?): SharedPreferences.Editor = throw UnsupportedOperationException()
override fun putBoolean(key: String?, value: Boolean): SharedPreferences.Editor {
editorStore.put(key, value)
return this
}
override fun putStringSet(key: String?, values: MutableSet<String>?): SharedPreferences.Editor {
editorStore.put(key, values?.toMutableSet())
return this
}
override fun commit(): Boolean = true
override fun putFloat(key: String?, value: Float): SharedPreferences.Editor =
throw UnsupportedOperationException("Implement as needed")
override fun apply() = store.putAll(editorStore)
override fun putString(key: String?, value: String?): SharedPreferences.Editor {
editorStore.put(key, value)
return this
}
}
val store: MutableMap<String?, Any?> = TreeMap()
override fun contains(key: String?): Boolean = store.containsKey(key)
override fun getBoolean(key: String?, defValue: Boolean): Boolean = store.getOrDefault(key, defValue) as Boolean
override fun unregisterOnSharedPreferenceChangeListener(
listener: SharedPreferences.OnSharedPreferenceChangeListener?
) = throw UnsupportedOperationException()
override fun getInt(key: String?, defValue: Int): Int = store.getOrDefault(key, defValue) as Int
override fun getAll(): MutableMap<String?, Any?> {
return HashMap(store)
}
override fun edit(): SharedPreferences.Editor {
return MockEditor(store)
}
override fun getLong(key: String?, defValue: Long): Long {
throw UnsupportedOperationException()
}
override fun getFloat(key: String?, defValue: Float): Float {
throw UnsupportedOperationException()
}
override fun getStringSet(key: String?, defValues: MutableSet<String>?): MutableSet<String>? {
return store.getOrDefault(key, defValues) as MutableSet<String>?
}
override fun registerOnSharedPreferenceChangeListener(
listener: SharedPreferences.OnSharedPreferenceChangeListener?
) = throw UnsupportedOperationException()
override fun getString(key: String?, defValue: String?): String? = store.getOrDefault(key, defValue) as String?
}
@@ -1,100 +0,0 @@
/*
* Nextcloud Android client application
*
* @author Chris Narkiewicz
* Copyright (C) 2020 Chris Narkiewicz <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.nextcloud.client.migrations
import org.junit.Before
import org.junit.Test
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotSame
import org.junit.Assert.assertTrue
@Suppress("MagicNumber")
class MockSharedPreferencesTest {
private lateinit var mock: MockSharedPreferences
@Before
fun setUp() {
mock = MockSharedPreferences()
}
@Test
fun getSetStringSet() {
val value = setOf("alpha", "bravo", "charlie")
mock.edit().putStringSet("key", value).apply()
val copy = mock.getStringSet("key", mutableSetOf())
assertNotSame(value, copy)
assertEquals(value, copy)
}
@Test
fun getSetInt() {
val value = 42
val editor = mock.edit()
editor.putInt("key", value)
assertEquals(100, mock.getInt("key", 100))
editor.apply()
assertEquals(42, mock.getInt("key", 100))
}
@Test
fun getSetBoolean() {
val value = true
val editor = mock.edit()
editor.putBoolean("key", value)
assertFalse(mock.getBoolean("key", false))
editor.apply()
assertTrue(mock.getBoolean("key", false))
}
@Test
fun getSetString() {
val value = "a value"
val editor = mock.edit()
editor.putString("key", value)
assertEquals("default", mock.getString("key", "default"))
editor.apply()
assertEquals("a value", mock.getString("key", "default"))
}
@Test
fun getAll() {
// GIVEN
// few properties are stored in shared preferences
mock.edit()
.putInt("int", 1)
.putBoolean("bool", true)
.putString("string", "value")
.putStringSet("stringSet", setOf("alpha", "bravo"))
.apply()
assertEquals(4, mock.store.size)
// WHEN
// all properties are retrieved
val all = mock.all
// THEN
// returned map is a different instance
// map is equal to internal storage
assertNotSame(all, mock.store)
assertEquals(all, mock.store)
}
}
@@ -4,83 +4,45 @@ import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import com.facebook.testing.screenshot.Screenshot;
import com.nextcloud.client.RetryTestRule;
import com.nextcloud.client.account.UserAccountManager;
import com.nextcloud.client.account.UserAccountManagerImpl;
import com.nextcloud.client.device.BatteryStatus;
import com.nextcloud.client.device.PowerManagementService;
import com.nextcloud.client.network.Connectivity;
import com.nextcloud.client.network.ConnectivityService;
import com.owncloud.android.datamodel.FileDataStorageManager;
import com.owncloud.android.datamodel.OCFile;
import com.owncloud.android.datamodel.UploadsStorageManager;
import com.owncloud.android.db.OCUpload;
import com.owncloud.android.files.services.FileUploader;
import com.owncloud.android.datamodel.FileDataStorageManagerImpl;
import com.owncloud.android.lib.common.OwnCloudClient;
import com.owncloud.android.lib.common.OwnCloudClientFactory;
import com.owncloud.android.lib.common.accounts.AccountUtils;
import com.owncloud.android.lib.common.operations.RemoteOperationResult;
import com.owncloud.android.lib.resources.e2ee.ToggleEncryptionRemoteOperation;
import com.owncloud.android.lib.resources.files.ReadFolderRemoteOperation;
import com.owncloud.android.lib.resources.files.RemoveFileRemoteOperation;
import com.owncloud.android.lib.resources.files.model.RemoteFile;
import com.owncloud.android.operations.CreateFolderOperation;
import com.owncloud.android.operations.UploadFileOperation;
import com.owncloud.android.utils.FileStorageUtils;
import junit.framework.TestCase;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.io.FileUtils;
import org.jetbrains.annotations.NotNull;
import org.junit.After;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.runner.RunWith;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import androidx.test.espresso.contrib.DrawerActions;
import androidx.test.espresso.intent.rule.IntentsTestRule;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.runner.lifecycle.ActivityLifecycleMonitorRegistry;
import androidx.test.runner.lifecycle.Stage;
import static androidx.test.InstrumentationRegistry.getInstrumentation;
import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.matcher.ViewMatchers.withId;
import static org.junit.Assert.assertTrue;
/**
* Common base for all integration tests
*/
//@RunWith(AndroidJUnit4.class)
@RunWith(AndroidJUnit4.class)
public abstract class AbstractIT {
@Rule public RetryTestRule retryTestRule = new RetryTestRule();
protected static OwnCloudClient client;
protected static Account account;
static Account account;
protected static Context targetContext;
private Activity currentActivity;
protected FileDataStorageManager fileDataStorageManager =
new FileDataStorageManager(account, targetContext.getContentResolver());
@BeforeClass
public static void beforeAll() {
try {
@@ -115,8 +77,6 @@ public abstract class AbstractIT {
createDummyFiles();
waitForServer(client, baseUrl);
// deleteAllFiles(); // makes sure that no file/folder is in root
} catch (OperationCanceledException e) {
e.printStackTrace();
} catch (AuthenticatorException e) {
@@ -128,42 +88,8 @@ public abstract class AbstractIT {
}
}
@After
public void after() {
deleteAllFiles();
}
public static void deleteAllFiles() {
RemoteOperationResult result = new ReadFolderRemoteOperation("/").execute(client);
assertTrue(result.getLogMessage(), result.isSuccess());
for (Object object : result.getData()) {
RemoteFile remoteFile = (RemoteFile) object;
if (!remoteFile.getRemotePath().equals("/")) {
if (remoteFile.isEncrypted()) {
assertTrue(new ToggleEncryptionRemoteOperation(remoteFile.getLocalId(),
remoteFile.getRemotePath(),
false)
.execute(client)
.isSuccess());
}
assertTrue(new RemoveFileRemoteOperation(remoteFile.getRemotePath())
.execute(client)
.isSuccess()
);
}
}
}
protected FileDataStorageManager getStorageManager() {
return fileDataStorageManager;
}
protected Account[] getAllAccounts() {
return AccountManager.get(targetContext).getAccounts();
FileDataStorageManager getStorageManager() {
return new FileDataStorageManagerImpl(account, targetContext.getContentResolver());
}
private static void createDummyFiles() throws IOException {
@@ -174,7 +100,7 @@ public abstract class AbstractIT {
createFile("chunkedFile.txt", 500000);
}
public static void createFile(String name, int iteration) throws IOException {
private static void createFile(String name, int iteration) throws IOException {
File file = new File(FileStorageUtils.getSavePath(account.name) + File.separator + name);
file.createNewFile();
@@ -208,124 +134,4 @@ public abstract class AbstractIT {
e.printStackTrace();
}
}
protected File getFile(String filename) throws IOException {
InputStream inputStream = getInstrumentation().getContext().getAssets().open(filename);
File temp = File.createTempFile("file", "file");
FileUtils.copyInputStreamToFile(inputStream, temp);
return temp;
}
protected void waitForIdleSync() {
InstrumentationRegistry.getInstrumentation().waitForIdleSync();
}
protected void openDrawer(IntentsTestRule activityRule) throws InterruptedException {
Activity sut = activityRule.launchActivity(null);
shortSleep();
onView(withId(R.id.drawer_layout)).perform(DrawerActions.open());
waitForIdleSync();
Screenshot.snapActivity(sut).record();
}
protected Activity getCurrentActivity() {
InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> {
Collection<Activity> resumedActivities = ActivityLifecycleMonitorRegistry
.getInstance()
.getActivitiesInStage(Stage.RESUMED);
if (resumedActivities.iterator().hasNext()) {
currentActivity = resumedActivities.iterator().next();
}
});
return currentActivity;
}
protected void shortSleep() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
protected void longSleep() {
try {
Thread.sleep(20000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public OCFile createFolder(String remotePath) {
TestCase.assertTrue(new CreateFolderOperation(remotePath, account, targetContext)
.execute(client, getStorageManager())
.isSuccess());
return getStorageManager().getFileByDecryptedRemotePath(remotePath);
}
public void uploadOCUpload(OCUpload ocUpload) {
ConnectivityService connectivityServiceMock = new ConnectivityService() {
@Override
public boolean isInternetWalled() {
return false;
}
@Override
public Connectivity getConnectivity() {
return Connectivity.CONNECTED_WIFI;
}
};
PowerManagementService powerManagementServiceMock = new PowerManagementService() {
@NotNull
@Override
public BatteryStatus getBattery() {
return new BatteryStatus();
}
@Override
public boolean isPowerSavingEnabled() {
return false;
}
@Override
public boolean isPowerSavingExclusionAvailable() {
return false;
}
};
UserAccountManager accountManager = UserAccountManagerImpl.fromContext(targetContext);
UploadsStorageManager uploadsStorageManager = new UploadsStorageManager(accountManager,
targetContext.getContentResolver());
UploadFileOperation newUpload = new UploadFileOperation(
uploadsStorageManager,
connectivityServiceMock,
powerManagementServiceMock,
account,
null,
ocUpload,
FileUploader.NameCollisionPolicy.DEFAULT,
FileUploader.LOCAL_BEHAVIOUR_COPY,
targetContext,
false,
false
);
newUpload.addRenameUploadListener(() -> {
// dummy
});
newUpload.setRemoteFolderToBeCreated();
RemoteOperationResult result = newUpload.execute(client, getStorageManager());
assertTrue(result.getLogMessage(), result.isSuccess());
}
}
@@ -1,6 +1,5 @@
package com.owncloud.android;
import com.owncloud.android.datamodel.OCFile;
import com.owncloud.android.lib.common.operations.RemoteOperationResult;
import com.owncloud.android.operations.CreateFolderOperation;
import com.owncloud.android.operations.RemoveFileOperation;
@@ -27,17 +26,16 @@ public class FileIT extends AbstractIT {
// folder does not exist yet
assertNull(getStorageManager().getFileByPath(path));
SyncOperation syncOp = new CreateFolderOperation(path, account, targetContext);
SyncOperation syncOp = new CreateFolderOperation(path, true);
RemoteOperationResult result = syncOp.execute(client, getStorageManager());
assertTrue(result.toString(), result.isSuccess());
// folder exists
OCFile file = getStorageManager().getFileByPath(path);
assertTrue(file.isFolder());
assertTrue(getStorageManager().getFileByPath(path).isFolder());
// cleanup
new RemoveFileOperation(file, false, account, false, targetContext).execute(client, getStorageManager());
new RemoveFileOperation(path, false, account, false, targetContext).execute(client, getStorageManager());
}
@Test
@@ -46,20 +44,14 @@ public class FileIT extends AbstractIT {
// folder does not exist yet
assertNull(getStorageManager().getFileByPath(path));
SyncOperation syncOp = new CreateFolderOperation(path, account, targetContext);
SyncOperation syncOp = new CreateFolderOperation(path, true);
RemoteOperationResult result = syncOp.execute(client, getStorageManager());
assertTrue(result.toString(), result.isSuccess());
// folder exists
OCFile file = getStorageManager().getFileByPath(path);
assertTrue(file.isFolder());
assertTrue(getStorageManager().getFileByPath(path).isFolder());
// cleanup
new RemoveFileOperation(file,
false,
account,
false,
targetContext)
.execute(client, getStorageManager());
new RemoveFileOperation("/testFolder/", false, account, false, targetContext).execute(client, getStorageManager());
}
}
@@ -17,6 +17,8 @@ import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import androidx.test.core.app.ActivityScenario;
import androidx.test.espresso.Espresso;
import androidx.test.espresso.NoActivityResumedException;
import androidx.test.espresso.action.ViewActions;
import androidx.test.espresso.contrib.DrawerActions;
import androidx.test.espresso.contrib.RecyclerViewActions;
@@ -52,27 +54,39 @@ public class ScreenshotsIT extends AbstractIT {
}
@Test
public void gridViewScreenshot() {
public void gridViewScreenshot() throws InterruptedException {
ActivityScenario.launch(FileDisplayActivity.class);
onView(anyOf(withText(R.string.action_switch_grid_view), withId(R.id.switch_grid_view_button))).perform(click());
openOverflowMenu();
onView(anyOf(withText(R.string.action_switch_grid_view), withId(R.id.action_switch_view))).perform(click());
shortSleep();
Thread.sleep(1000);
Screengrab.screenshot("01_gridView");
onView(anyOf(withText(R.string.action_switch_list_view), withId(R.id.switch_grid_view_button))).perform(click());
openOverflowMenu();
onView(anyOf(withText(R.string.action_switch_list_view), withId(R.id.action_switch_view))).perform(click());
Assert.assertTrue(true); // if we reach this, everything is ok
}
private void openOverflowMenu() throws InterruptedException {
try {
Espresso.openContextualActionModeOverflowMenu();
} catch (NoActivityResumedException e) {
ActivityScenario.launch(FileDisplayActivity.class);
Thread.sleep(1000);
Espresso.openContextualActionModeOverflowMenu();
}
}
@Test
public void listViewScreenshot() {
String path = "/Camera/";
// folder does not exist yet
if (getStorageManager().getFileByPath(path) == null) {
SyncOperation syncOp = new CreateFolderOperation(path, account, targetContext);
SyncOperation syncOp = new CreateFolderOperation(path, true);
RemoteOperationResult result = syncOp.execute(client, getStorageManager());
assertTrue(result.isSuccess());
@@ -129,12 +143,12 @@ public class ScreenshotsIT extends AbstractIT {
}
@Test
public void davdroidScreenshot() {
public void davdroidScreenshot() throws InterruptedException {
ActivityScenario.launch(SettingsActivity.class);
onData(PreferenceMatchers.withTitle(R.string.prefs_category_more)).perform(ViewActions.scrollTo());
shortSleep();
Thread.sleep(1000);
Screengrab.screenshot("06_davdroid");
@@ -1,48 +1,26 @@
/*
* Nextcloud Android client application
*
* @author Tobias Kaminsky
* Copyright (C) 2020 Tobias Kaminsky
* Copyright (C) 2020 Nextcloud GmbH
* Copyright (C) 2020 Chris Narkiewicz <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.owncloud.android;
import android.content.ContentResolver;
import com.evernote.android.job.JobRequest;
import com.nextcloud.client.account.UserAccountManager;
import com.nextcloud.client.account.UserAccountManagerImpl;
import com.nextcloud.client.device.BatteryStatus;
import com.nextcloud.client.device.PowerManagementService;
import com.nextcloud.client.network.Connectivity;
import com.nextcloud.client.network.ConnectivityService;
import com.owncloud.android.datamodel.UploadsStorageManager;
import com.owncloud.android.db.OCUpload;
import com.owncloud.android.files.services.FileUploader;
import com.owncloud.android.lib.common.operations.RemoteOperationResult;
import com.owncloud.android.operations.RefreshFolderOperation;
import com.owncloud.android.operations.RemoveFileOperation;
import com.owncloud.android.operations.UploadFileOperation;
import com.owncloud.android.utils.FileStorageUtils;
import org.jetbrains.annotations.NotNull;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import static junit.framework.TestCase.assertFalse;
import static junit.framework.TestCase.assertTrue;
/**
@@ -51,11 +29,8 @@ import static junit.framework.TestCase.assertTrue;
@RunWith(AndroidJUnit4.class)
public class UploadIT extends AbstractIT {
private static final String FOLDER = "/testUpload/";
private UploadsStorageManager uploadsStorageManager =
new UploadsStorageManager(UserAccountManagerImpl.fromContext(targetContext),
targetContext.getContentResolver());
private UploadsStorageManager storageManager;
private ConnectivityService connectivityServiceMock = new ConnectivityService() {
@Override
@@ -64,8 +39,13 @@ public class UploadIT extends AbstractIT {
}
@Override
public Connectivity getConnectivity() {
return Connectivity.CONNECTED_WIFI;
public boolean isOnlineWithWifi() {
return true;
}
@Override
public JobRequest.NetworkType getActiveNetworkType() {
return JobRequest.NetworkType.ANY;
}
};
@@ -80,70 +60,67 @@ public class UploadIT extends AbstractIT {
return false;
}
@NotNull
@Override
public BatteryStatus getBattery() {
return new BatteryStatus(false, 0);
public boolean isBatteryCharging() {
return false;
}
};
@After
public void after() {
RemoteOperationResult result = new RefreshFolderOperation(getStorageManager().getFileByPath("/"),
System.currentTimeMillis() / 1000L,
false,
true,
getStorageManager(),
account,
targetContext)
.execute(client);
// cleanup only if folder exists
if (result.isSuccess() && getStorageManager().getFileByDecryptedRemotePath(FOLDER) != null) {
new RemoveFileOperation(getStorageManager().getFileByDecryptedRemotePath(FOLDER),
false,
account,
false,
targetContext)
.execute(client, getStorageManager());
}
@Before
public void setUp() {
final ContentResolver contentResolver = targetContext.getContentResolver();
final UserAccountManager accountManager = UserAccountManagerImpl.fromContext(targetContext);
storageManager = new UploadsStorageManager(accountManager, contentResolver);
}
@Test
public void testEmptyUpload() {
OCUpload ocUpload = new OCUpload(FileStorageUtils.getSavePath(account.name) + "/empty.txt",
FOLDER + "empty.txt",
account.name);
"/testUpload/empty.txt", account.name);
uploadOCUpload(ocUpload);
RemoteOperationResult result = testUpload(ocUpload);
assertTrue(result.toString(), result.isSuccess());
// cleanup
new RemoveFileOperation("/testUpload/", false, account, false, targetContext).execute(client, getStorageManager());
}
@Test
public void testNonEmptyUpload() {
OCUpload ocUpload = new OCUpload(FileStorageUtils.getSavePath(account.name) + "/nonEmpty.txt",
FOLDER + "nonEmpty.txt",
account.name);
"/testUpload/nonEmpty.txt", account.name);
uploadOCUpload(ocUpload);
RemoteOperationResult result = testUpload(ocUpload);
assertTrue(result.toString(), result.isSuccess());
// cleanup
new RemoveFileOperation("/testUpload/", false, account, false, targetContext).execute(client, getStorageManager());
}
@Test
public void testChunkedUpload() {
OCUpload ocUpload = new OCUpload(FileStorageUtils.getSavePath(account.name) + "/chunkedFile.txt",
FOLDER + "chunkedFile.txt", account.name);
"/testUpload/chunkedFile.txt", account.name);
uploadOCUpload(ocUpload);
RemoteOperationResult result = testUpload(ocUpload);
assertTrue(result.toString(), result.isSuccess());
// cleanup
new RemoveFileOperation("/testUpload/", false, account, false, targetContext).execute(client, getStorageManager());
}
public RemoteOperationResult testUpload(OCUpload ocUpload) {
UploadFileOperation newUpload = new UploadFileOperation(
uploadsStorageManager,
storageManager,
connectivityServiceMock,
powerManagementServiceMock,
account,
null,
ocUpload,
FileUploader.NameCollisionPolicy.DEFAULT,
false,
FileUploader.LOCAL_BEHAVIOUR_COPY,
targetContext,
false,
@@ -161,156 +138,30 @@ public class UploadIT extends AbstractIT {
@Test
public void testUploadInNonExistingFolder() {
OCUpload ocUpload = new OCUpload(FileStorageUtils.getSavePath(account.name) + "/empty.txt",
FOLDER + "2/3/4/1.txt", account.name);
uploadOCUpload(ocUpload);
}
@Test
public void testUploadOnChargingOnlyButNotCharging() {
OCUpload ocUpload = new OCUpload(FileStorageUtils.getSavePath(account.name) + "/empty.txt",
FOLDER + "notCharging.txt", account.name);
ocUpload.setWhileChargingOnly(true);
"/testUpload/2/3/4/1.txt", account.name);
UploadFileOperation newUpload = new UploadFileOperation(
uploadsStorageManager,
connectivityServiceMock,
powerManagementServiceMock,
account,
null,
ocUpload,
FileUploader.NameCollisionPolicy.DEFAULT,
FileUploader.LOCAL_BEHAVIOUR_COPY,
targetContext,
false,
true
storageManager,
connectivityServiceMock,
powerManagementServiceMock,
account,
null,
ocUpload,
false,
FileUploader.LOCAL_BEHAVIOUR_COPY,
targetContext,
false,
false
);
newUpload.setRemoteFolderToBeCreated();
newUpload.addRenameUploadListener(() -> {
// dummy
});
RemoteOperationResult result = newUpload.execute(client, getStorageManager());
assertFalse(result.toString(), result.isSuccess());
}
@Test
public void testUploadOnChargingOnlyAndCharging() {
PowerManagementService powerManagementServiceMock = new PowerManagementService() {
@Override
public boolean isPowerSavingEnabled() {
return false;
}
@Override
public boolean isPowerSavingExclusionAvailable() {
return false;
}
@NotNull
@Override
public BatteryStatus getBattery() {
return new BatteryStatus(true, 100);
}
};
OCUpload ocUpload = new OCUpload(FileStorageUtils.getSavePath(account.name) + "/empty.txt",
FOLDER + "charging.txt", account.name);
ocUpload.setWhileChargingOnly(true);
UploadFileOperation newUpload = new UploadFileOperation(
uploadsStorageManager,
connectivityServiceMock,
powerManagementServiceMock,
account,
null,
ocUpload,
FileUploader.NameCollisionPolicy.DEFAULT,
FileUploader.LOCAL_BEHAVIOUR_COPY,
targetContext,
false,
true
);
newUpload.setRemoteFolderToBeCreated();
newUpload.addRenameUploadListener(() -> {
// dummy
});
RemoteOperationResult result = newUpload.execute(client, getStorageManager());
assertTrue(result.toString(), result.isSuccess());
}
@Test
public void testUploadOnWifiOnlyButNoWifi() {
ConnectivityService connectivityServiceMock = new ConnectivityService() {
@Override
public boolean isInternetWalled() {
return false;
}
@Override
public Connectivity getConnectivity() {
return new Connectivity(true, false, false, true);
}
};
OCUpload ocUpload = new OCUpload(FileStorageUtils.getSavePath(account.name) + "/empty.txt",
FOLDER + "noWifi.txt", account.name);
ocUpload.setUseWifiOnly(true);
UploadFileOperation newUpload = new UploadFileOperation(
uploadsStorageManager,
connectivityServiceMock,
powerManagementServiceMock,
account,
null,
ocUpload,
FileUploader.NameCollisionPolicy.DEFAULT,
FileUploader.LOCAL_BEHAVIOUR_COPY,
targetContext,
true,
false
);
newUpload.setRemoteFolderToBeCreated();
newUpload.addRenameUploadListener(() -> {
// dummy
});
RemoteOperationResult result = newUpload.execute(client, getStorageManager());
assertFalse(result.toString(), result.isSuccess());
}
@Test
public void testUploadOnWifiOnlyAndWifi() {
OCUpload ocUpload = new OCUpload(FileStorageUtils.getSavePath(account.name) + "/empty.txt",
FOLDER + "wifi.txt", account.name);
ocUpload.setWhileChargingOnly(true);
UploadFileOperation newUpload = new UploadFileOperation(
uploadsStorageManager,
connectivityServiceMock,
powerManagementServiceMock,
account,
null,
ocUpload,
FileUploader.NameCollisionPolicy.DEFAULT,
FileUploader.LOCAL_BEHAVIOUR_COPY,
targetContext,
true,
false
);
newUpload.setRemoteFolderToBeCreated();
newUpload.addRenameUploadListener(() -> {
// dummy
});
RemoteOperationResult result = newUpload.execute(client, getStorageManager());
assertTrue(result.toString(), result.isSuccess());
// cleanup
new RemoveFileOperation(getStorageManager().getFileByDecryptedRemotePath(FOLDER),
false,
account,
false,
targetContext)
.execute(client, getStorageManager());
new RemoveFileOperation("/testUpload/", false, account, false, targetContext).execute(client, getStorageManager());
}
}
@@ -1,187 +1,75 @@
package com.owncloud.android.datamodel;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.Context;
import com.nextcloud.client.account.CurrentAccountProvider;
import com.nextcloud.client.account.UserAccountManager;
import com.nextcloud.client.account.UserAccountManagerImpl;
import com.owncloud.android.AbstractIT;
import com.owncloud.android.MainApp;
import com.owncloud.android.db.OCUpload;
import com.owncloud.android.db.UploadResult;
import com.owncloud.android.files.services.FileUploader;
import com.owncloud.android.lib.common.accounts.AccountUtils;
import com.owncloud.android.operations.UploadFileOperation;
import net.bytebuddy.utility.RandomString;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.io.File;
import java.util.ArrayList;
import java.util.Random;
import androidx.test.InstrumentationRegistry;
import androidx.test.filters.SmallTest;
import androidx.test.runner.AndroidJUnit4;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* Created by JARP on 6/7/17.
*/
@RunWith(AndroidJUnit4.class)
@SmallTest
public class UploadStorageManagerTest extends AbstractIT {
public class UploadStorageManagerTest {
private Account[] Accounts;
private UploadsStorageManager uploadsStorageManager;
private CurrentAccountProvider currentAccountProvider = () -> null;
private Account account2;
@Before
public void setUp() {
Context instrumentationCtx = InstrumentationRegistry.getTargetContext();
ContentResolver contentResolver = instrumentationCtx.getContentResolver();
uploadsStorageManager = new UploadsStorageManager(currentAccountProvider, contentResolver);
Account temp = new Account("[email protected]", MainApp.getAccountType(targetContext));
UserAccountManager accountManager = UserAccountManagerImpl.fromContext(targetContext);
if (!accountManager.exists(temp)) {
AccountManager platformAccountManager = AccountManager.get(targetContext);
platformAccountManager.addAccountExplicitly(temp, "testPassword", null);
platformAccountManager.setUserData(temp, AccountUtils.Constants.KEY_OC_ACCOUNT_VERSION,
Integer.toString(UserAccountManager.ACCOUNT_VERSION));
platformAccountManager.setUserData(temp, AccountUtils.Constants.KEY_OC_VERSION, "14.0.0.0");
platformAccountManager.setUserData(temp, AccountUtils.Constants.KEY_OC_BASE_URL, "test.com");
platformAccountManager.setUserData(temp, AccountUtils.Constants.KEY_USER_ID, "test"); // same as userId
}
final UserAccountManager userAccountManager = UserAccountManagerImpl.fromContext(targetContext);
account2 = userAccountManager.getAccountByName("[email protected]");
if (account2 == null) {
throw new ActivityNotFoundException();
}
Accounts = new Account[]{new Account("A", "A"), new Account("B", "B")};
}
@Test
public void testDeleteAllUploads() {
// Clean
for (Account account : getAllAccounts()) {
for (Account account : Accounts) {
uploadsStorageManager.removeAccountUploads(account);
}
int accountRowsA = 3;
int accountRowsB = 4;
insertUploads(account, accountRowsA);
insertUploads(account2, accountRowsB);
insertUploads(Accounts[0], accountRowsA);
insertUploads(Accounts[1], accountRowsB);
assertEquals("Expected 4 removed uploads files",
4,
uploadsStorageManager.removeAccountUploads(account2));
}
@Test
public void largeTest() {
int size = 3000;
ArrayList<OCUpload> uploads = new ArrayList<>();
assertEquals(0, uploadsStorageManager.getAllStoredUploads().length);
for (int i = 0; i < size; i++) {
OCUpload upload = createUpload(account);
uploads.add(upload);
uploadsStorageManager.storeUpload(upload);
}
OCUpload[] storedUploads = uploadsStorageManager.getAllStoredUploads();
assertEquals(size, uploadsStorageManager.getAllStoredUploads().length);
for (int i = 0; i < size; i++) {
assertTrue(contains(uploads, storedUploads[i]));
}
}
@Test
public void testIsSame() {
OCUpload upload1 = new OCUpload("/test", "/test", account.name);
upload1.setUseWifiOnly(true);
OCUpload upload2 = new OCUpload("/test", "/test", account.name);
upload2.setUseWifiOnly(true);
assertTrue(upload1.isSame(upload2));
upload2.setUseWifiOnly(false);
assertFalse(upload1.isSame(upload2));
assertFalse(upload1.isSame(null));
assertFalse(upload1.isSame(new OCFile("/test")));
}
private boolean contains(ArrayList<OCUpload> uploads, OCUpload storedUpload) {
for (int i = 0; i < uploads.size(); i++) {
if (storedUpload.isSame(uploads.get(i))) {
return true;
}
}
return false;
}
@Test(expected = IllegalArgumentException.class)
public void corruptedUpload() {
OCUpload corruptUpload = new OCUpload(File.separator + "LocalPath",
OCFile.PATH_SEPARATOR + "RemotePath",
account.name);
corruptUpload.setLocalPath(null);
uploadsStorageManager.storeUpload(corruptUpload);
uploadsStorageManager.getAllStoredUploads();
Assert.assertTrue("Expected 4 removed uploads files", uploadsStorageManager.removeAccountUploads(Accounts[1]) == 4);
}
private void insertUploads(Account account, int rowsToInsert) {
for (int i = 0; i < rowsToInsert; i++) {
uploadsStorageManager.storeUpload(createUpload(account));
}
}
private OCUpload createUpload(Account account) {
OCUpload upload = new OCUpload(File.separator + "very long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long LocalPath",
OCFile.PATH_SEPARATOR + "very long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long RemotePath",
account.name);
upload.setFileSize(new Random().nextInt(20000) * 10000);
upload.setUploadStatus(UploadsStorageManager.UploadStatus.UPLOAD_IN_PROGRESS);
upload.setLocalAction(2);
upload.setNameCollisionPolicy(FileUploader.NameCollisionPolicy.ASK_USER);
upload.setCreateRemoteFolder(false);
upload.setUploadEndTimestamp(System.currentTimeMillis());
upload.setLastResult(UploadResult.DELAYED_FOR_WIFI);
upload.setCreatedBy(UploadFileOperation.CREATED_BY_USER);
upload.setUseWifiOnly(true);
upload.setWhileChargingOnly(false);
upload.setFolderUnlockToken(RandomString.make(10));
return upload;
private OCUpload createUpload(Account acc) {
return new OCUpload(File.separator + "LocalPath",
OCFile.PATH_SEPARATOR + "RemotePath",
acc.name);
}
@After
public void tearDown() {
for (Account account : getAllAccounts()) {
for (Account account : Accounts) {
uploadsStorageManager.removeAccountUploads(account);
}
AccountManager platformAccountManager = AccountManager.get(targetContext);
platformAccountManager.removeAccountExplicitly(account2);
}
}
@@ -1,373 +0,0 @@
/*
*
* Nextcloud Android client application
*
* @author Tobias Kaminsky
* Copyright (C) 2020 Tobias Kaminsky
* Copyright (C) 2020 Nextcloud GmbH
* Copyright (C) 2020 Chris Narkiewicz <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.owncloud.android.files.services
import com.nextcloud.client.account.UserAccountManager
import com.nextcloud.client.account.UserAccountManagerImpl
import com.nextcloud.client.device.BatteryStatus
import com.nextcloud.client.device.PowerManagementService
import com.nextcloud.client.network.Connectivity
import com.nextcloud.client.network.ConnectivityService
import com.owncloud.android.AbstractIT
import com.owncloud.android.datamodel.OCFile
import com.owncloud.android.datamodel.UploadsStorageManager
import com.owncloud.android.db.OCUpload
import com.owncloud.android.lib.resources.files.ReadFileRemoteOperation
import com.owncloud.android.lib.resources.files.model.RemoteFile
import com.owncloud.android.operations.UploadFileOperation
import com.owncloud.android.utils.FileStorageUtils.getSavePath
import junit.framework.Assert.assertEquals
import junit.framework.Assert.assertFalse
import junit.framework.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import java.io.File
class FileUploaderIT : AbstractIT() {
var uploadsStorageManager: UploadsStorageManager? = null
val connectivityServiceMock: ConnectivityService = object : ConnectivityService {
override fun isInternetWalled(): Boolean = false
override fun getConnectivity(): Connectivity = Connectivity.CONNECTED_WIFI
}
private val powerManagementServiceMock: PowerManagementService = object : PowerManagementService {
override val isPowerSavingEnabled: Boolean
get() = false
override val isPowerSavingExclusionAvailable: Boolean
get() = false
override val battery: BatteryStatus
get() = BatteryStatus()
}
@Before
fun setUp() {
val contentResolver = targetContext.contentResolver
val accountManager: UserAccountManager = UserAccountManagerImpl.fromContext(targetContext)
uploadsStorageManager = UploadsStorageManager(accountManager, contentResolver)
}
/**
* uploads a file, overwrites it with an empty one, check if overwritten
*/
@Test
fun testKeepLocalAndOverwriteRemote() {
val file = File(getSavePath(account.name) + "/chunkedFile.txt")
val ocUpload = OCUpload(file.absolutePath, "/testFile.txt", account.name)
assertTrue(UploadFileOperation(
uploadsStorageManager,
connectivityServiceMock,
powerManagementServiceMock,
account,
null,
ocUpload,
FileUploader.NameCollisionPolicy.DEFAULT,
FileUploader.LOCAL_BEHAVIOUR_COPY,
targetContext,
false,
false)
.setRemoteFolderToBeCreated()
.execute(client, storageManager).isSuccess)
val result = ReadFileRemoteOperation("/testFile.txt").execute(client)
assertTrue(result.isSuccess)
assertEquals(file.length(), (result.data[0] as RemoteFile).length)
val ocUpload2 = OCUpload(getSavePath(account.name) + "/empty.txt", "/testFile.txt", account.name)
assertTrue(UploadFileOperation(
uploadsStorageManager,
connectivityServiceMock,
powerManagementServiceMock,
account,
null,
ocUpload2,
FileUploader.NameCollisionPolicy.OVERWRITE,
FileUploader.LOCAL_BEHAVIOUR_COPY,
targetContext,
false,
false)
.execute(client, storageManager).isSuccess)
val result2 = ReadFileRemoteOperation("/testFile.txt").execute(client)
assertTrue(result2.isSuccess)
assertEquals(0, (result2.data[0] as RemoteFile).length)
}
/**
* uploads a file, overwrites it with an empty one, check if overwritten
*/
@Test
fun testKeepLocalAndOverwriteRemoteStatic() {
val file = File(getSavePath(account.name) + "/chunkedFile.txt")
FileUploader.uploadNewFile(
targetContext,
account,
file.absolutePath,
"/testFile.txt",
FileUploader.LOCAL_BEHAVIOUR_COPY,
null,
true,
UploadFileOperation.CREATED_BY_USER,
false,
false,
FileUploader.NameCollisionPolicy.DEFAULT)
longSleep()
val result = ReadFileRemoteOperation("/testFile.txt").execute(client)
assertTrue(result.isSuccess)
assertEquals(file.length(), (result.data[0] as RemoteFile).length)
val ocFile2 = OCFile("/testFile.txt")
ocFile2.setStoragePath(getSavePath(account.name) + "/empty.txt")
FileUploader.uploadUpdateFile(
targetContext,
account,
ocFile2,
FileUploader.LOCAL_BEHAVIOUR_COPY,
FileUploader.NameCollisionPolicy.OVERWRITE)
shortSleep()
val result2 = ReadFileRemoteOperation("/testFile.txt").execute(client)
assertTrue(result2.isSuccess)
assertEquals(0, (result2.data[0] as RemoteFile).length)
}
/**
* uploads a file, uploads another one with automatically (2) added, check
*/
@Test
fun testKeepBoth() {
var renameListenerWasTriggered = false
val file = File(getSavePath(account.name) + "/chunkedFile.txt")
val ocUpload = OCUpload(file.absolutePath, "/testFile.txt", account.name)
assertTrue(UploadFileOperation(
uploadsStorageManager,
connectivityServiceMock,
powerManagementServiceMock,
account,
null,
ocUpload,
FileUploader.NameCollisionPolicy.DEFAULT,
FileUploader.LOCAL_BEHAVIOUR_COPY,
targetContext,
false,
false)
.setRemoteFolderToBeCreated()
.execute(client, storageManager).isSuccess)
val result = ReadFileRemoteOperation("/testFile.txt").execute(client)
assertTrue(result.isSuccess)
assertEquals(file.length(), (result.data[0] as RemoteFile).length)
val file2 = File(getSavePath(account.name) + "/empty.txt")
val ocUpload2 = OCUpload(file2.absolutePath, "/testFile.txt", account.name)
assertTrue(UploadFileOperation(
uploadsStorageManager,
connectivityServiceMock,
powerManagementServiceMock,
account,
null,
ocUpload2,
FileUploader.NameCollisionPolicy.RENAME,
FileUploader.LOCAL_BEHAVIOUR_COPY,
targetContext,
false,
false)
.addRenameUploadListener {
renameListenerWasTriggered = true
}
.execute(client, storageManager).isSuccess)
val result2 = ReadFileRemoteOperation("/testFile.txt").execute(client)
assertTrue(result2.isSuccess)
assertEquals(file.length(), (result2.data[0] as RemoteFile).length)
val result3 = ReadFileRemoteOperation("/testFile (2).txt").execute(client)
assertTrue(result3.isSuccess)
assertEquals(file2.length(), (result3.data[0] as RemoteFile).length)
assertTrue(renameListenerWasTriggered)
}
/**
* uploads a file, uploads another one with automatically (2) added, check
*/
@Test
fun testKeepBothStatic() {
val file = File(getSavePath(account.name) + "/chunkedFile.txt")
FileUploader.uploadNewFile(
targetContext,
account,
file.absolutePath,
"/testFile.txt",
FileUploader.LOCAL_BEHAVIOUR_COPY,
null,
true,
UploadFileOperation.CREATED_BY_USER,
false,
false,
FileUploader.NameCollisionPolicy.DEFAULT)
longSleep()
val result = ReadFileRemoteOperation("/testFile.txt").execute(client)
assertTrue(result.isSuccess)
assertEquals(file.length(), (result.data[0] as RemoteFile).length)
val ocFile2 = OCFile("/testFile.txt")
ocFile2.setStoragePath(getSavePath(account.name) + "/empty.txt")
FileUploader.uploadUpdateFile(
targetContext,
account,
ocFile2,
FileUploader.LOCAL_BEHAVIOUR_COPY,
FileUploader.NameCollisionPolicy.RENAME)
shortSleep()
val result2 = ReadFileRemoteOperation("/testFile.txt").execute(client)
assertTrue(result2.isSuccess)
assertEquals(file.length(), (result2.data[0] as RemoteFile).length)
val result3 = ReadFileRemoteOperation("/testFile (2).txt").execute(client)
assertTrue(result3.isSuccess)
assertEquals(ocFile2.fileLength, (result3.data[0] as RemoteFile).length)
}
/**
* uploads a file with "keep server" option set, so do nothing
*/
@Test
fun testKeepServer() {
val file = File(getSavePath(account.name) + "/chunkedFile.txt")
val ocUpload = OCUpload(file.absolutePath, "/testFile.txt", account.name)
assertTrue(UploadFileOperation(
uploadsStorageManager,
connectivityServiceMock,
powerManagementServiceMock,
account,
null,
ocUpload,
FileUploader.NameCollisionPolicy.DEFAULT,
FileUploader.LOCAL_BEHAVIOUR_COPY,
targetContext,
false,
false)
.setRemoteFolderToBeCreated()
.execute(client, storageManager).isSuccess)
val result = ReadFileRemoteOperation("/testFile.txt").execute(client)
assertTrue(result.isSuccess)
assertEquals(file.length(), (result.data[0] as RemoteFile).length)
val ocUpload2 = OCUpload(getSavePath(account.name) + "/empty.txt", "/testFile.txt", account.name)
assertFalse(UploadFileOperation(
uploadsStorageManager,
connectivityServiceMock,
powerManagementServiceMock,
account,
null,
ocUpload2,
FileUploader.NameCollisionPolicy.CANCEL,
FileUploader.LOCAL_BEHAVIOUR_COPY,
targetContext,
false,
false)
.execute(client, storageManager).isSuccess)
val result2 = ReadFileRemoteOperation("/testFile.txt").execute(client)
assertTrue(result2.isSuccess)
assertEquals(file.length(), (result2.data[0] as RemoteFile).length)
}
/**
* uploads a file with "keep server" option set, so do nothing
*/
@Test
fun testKeepServerStatic() {
val file = File(getSavePath(account.name) + "/chunkedFile.txt")
FileUploader.uploadNewFile(
targetContext,
account,
file.absolutePath,
"/testFile.txt",
FileUploader.LOCAL_BEHAVIOUR_COPY,
null,
true,
UploadFileOperation.CREATED_BY_USER,
false,
false,
FileUploader.NameCollisionPolicy.DEFAULT)
longSleep()
val result = ReadFileRemoteOperation("/testFile.txt").execute(client)
assertTrue(result.isSuccess)
assertEquals(file.length(), (result.data[0] as RemoteFile).length)
val ocFile2 = OCFile("/testFile.txt")
ocFile2.setStoragePath(getSavePath(account.name) + "/empty.txt")
FileUploader.uploadUpdateFile(
targetContext,
account,
ocFile2,
FileUploader.LOCAL_BEHAVIOUR_COPY,
FileUploader.NameCollisionPolicy.CANCEL)
shortSleep()
val result2 = ReadFileRemoteOperation("/testFile.txt").execute(client)
assertTrue(result2.isSuccess)
assertEquals(file.length(), (result2.data[0] as RemoteFile).length)
}
}
@@ -1,321 +0,0 @@
/*
*
* Nextcloud Android client application
*
* @author Tobias Kaminsky
* Copyright (C) 2020 Tobias Kaminsky
* Copyright (C) 2020 Nextcloud GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.owncloud.android.ui.activity;
import android.content.Intent;
import com.facebook.testing.screenshot.Screenshot;
import com.nextcloud.client.account.UserAccountManagerImpl;
import com.owncloud.android.AbstractIT;
import com.owncloud.android.R;
import com.owncloud.android.datamodel.FileDataStorageManager;
import com.owncloud.android.datamodel.OCFile;
import com.owncloud.android.db.OCUpload;
import com.owncloud.android.lib.resources.files.UploadFileRemoteOperation;
import com.owncloud.android.operations.RefreshFolderOperation;
import com.owncloud.android.ui.dialog.ConflictsResolveDialog;
import com.owncloud.android.utils.FileStorageUtils;
import org.junit.Rule;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import androidx.fragment.app.DialogFragment;
import androidx.test.espresso.intent.rule.IntentsTestRule;
import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.action.ViewActions.click;
import static androidx.test.espresso.matcher.ViewMatchers.withId;
import static androidx.test.espresso.matcher.ViewMatchers.withText;
import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;
import static junit.framework.TestCase.assertTrue;
import static org.junit.Assert.assertEquals;
public class ConflictsResolveActivityIT extends AbstractIT {
@Rule public IntentsTestRule<ConflictsResolveActivity> activityRule =
new IntentsTestRule<>(ConflictsResolveActivity.class, true, false);
private boolean returnCode;
@Test
public void screenshotTextFiles() {
OCFile newFile = new OCFile("/newFile.txt");
newFile.setFileLength(56000);
newFile.setModificationTimestamp(1522019340);
newFile.setStoragePath(FileStorageUtils.getSavePath(account.name) + "/nonEmpty.txt");
OCFile existingFile = new OCFile("/newFile.txt");
existingFile.setFileLength(1024000);
existingFile.setModificationTimestamp(1582019340);
FileDataStorageManager storageManager = new FileDataStorageManager(account, targetContext.getContentResolver());
storageManager.saveNewFile(existingFile);
Intent intent = new Intent(targetContext, ConflictsResolveActivity.class);
intent.putExtra(ConflictsResolveActivity.EXTRA_FILE, newFile);
intent.putExtra(ConflictsResolveActivity.EXTRA_EXISTING_FILE, existingFile);
ConflictsResolveActivity sut = activityRule.launchActivity(intent);
ConflictsResolveDialog dialog = ConflictsResolveDialog.newInstance(existingFile,
newFile,
UserAccountManagerImpl
.fromContext(targetContext)
.getUser()
);
dialog.showDialog(sut);
getInstrumentation().waitForIdleSync();
shortSleep();
Screenshot.snap(dialog.getDialog().getWindow().getDecorView()).record();
}
@Test
public void screenshotImages() throws IOException {
FileDataStorageManager storageManager = new FileDataStorageManager(account,
targetContext.getContentResolver());
OCFile newFile = new OCFile("/newFile.txt");
newFile.setFileLength(56000);
newFile.setModificationTimestamp(1522019340);
newFile.setStoragePath(FileStorageUtils.getSavePath(account.name) + "/nonEmpty.txt");
File image = getFile("image.jpg");
assertTrue(new UploadFileRemoteOperation(image.getAbsolutePath(),
"/image.jpg",
"image/jpg",
"10000000").execute(client).isSuccess());
assertTrue(new RefreshFolderOperation(storageManager.getFileByPath("/"),
System.currentTimeMillis(),
false,
true,
storageManager,
account,
targetContext
).execute(client).isSuccess());
OCFile existingFile = storageManager.getFileByPath("/image.jpg");
Intent intent = new Intent(targetContext, ConflictsResolveActivity.class);
intent.putExtra(ConflictsResolveActivity.EXTRA_FILE, newFile);
intent.putExtra(ConflictsResolveActivity.EXTRA_EXISTING_FILE, existingFile);
ConflictsResolveActivity sut = activityRule.launchActivity(intent);
ConflictsResolveDialog.OnConflictDecisionMadeListener listener = decision -> {
};
ConflictsResolveDialog dialog = ConflictsResolveDialog.newInstance(existingFile,
newFile,
UserAccountManagerImpl
.fromContext(targetContext)
.getUser()
);
dialog.showDialog(sut);
dialog.listener = listener;
getInstrumentation().waitForIdleSync();
shortSleep();
Screenshot.snap(dialog.getDialog().getWindow().getDecorView()).record();
}
@Test
public void cancel() {
returnCode = false;
OCUpload newUpload = new OCUpload(FileStorageUtils.getSavePath(account.name) + "/nonEmpty.txt",
"/newFile.txt",
account.name);
OCFile existingFile = new OCFile("/newFile.txt");
existingFile.setFileLength(1024000);
existingFile.setModificationTimestamp(1582019340);
OCFile newFile = new OCFile("/newFile.txt");
newFile.setFileLength(56000);
newFile.setModificationTimestamp(1522019340);
newFile.setStoragePath(FileStorageUtils.getSavePath(account.name) + "/nonEmpty.txt");
FileDataStorageManager storageManager = new FileDataStorageManager(account, targetContext.getContentResolver());
storageManager.saveNewFile(existingFile);
Intent intent = new Intent(targetContext, ConflictsResolveActivity.class);
intent.putExtra(ConflictsResolveActivity.EXTRA_FILE, newFile);
intent.putExtra(ConflictsResolveActivity.EXTRA_EXISTING_FILE, existingFile);
intent.putExtra(ConflictsResolveActivity.EXTRA_CONFLICT_UPLOAD, newUpload);
ConflictsResolveActivity sut = activityRule.launchActivity(intent);
sut.listener = decision -> {
assertEquals(decision, ConflictsResolveDialog.Decision.CANCEL);
returnCode = true;
};
getInstrumentation().waitForIdleSync();
shortSleep();
onView(withText("Cancel")).perform(click());
assertTrue(returnCode);
}
@Test
public void keepExisting() {
returnCode = false;
OCUpload newUpload = new OCUpload(FileStorageUtils.getSavePath(account.name) + "/nonEmpty.txt",
"/newFile.txt",
account.name);
OCFile existingFile = new OCFile("/newFile.txt");
existingFile.setFileLength(1024000);
existingFile.setModificationTimestamp(1582019340);
OCFile newFile = new OCFile("/newFile.txt");
newFile.setFileLength(56000);
newFile.setModificationTimestamp(1522019340);
newFile.setStoragePath(FileStorageUtils.getSavePath(account.name) + "/nonEmpty.txt");
FileDataStorageManager storageManager = new FileDataStorageManager(account, targetContext.getContentResolver());
storageManager.saveNewFile(existingFile);
Intent intent = new Intent(targetContext, ConflictsResolveActivity.class);
intent.putExtra(ConflictsResolveActivity.EXTRA_FILE, newFile);
intent.putExtra(ConflictsResolveActivity.EXTRA_EXISTING_FILE, existingFile);
intent.putExtra(ConflictsResolveActivity.EXTRA_CONFLICT_UPLOAD, newUpload);
ConflictsResolveActivity sut = activityRule.launchActivity(intent);
sut.listener = decision -> {
assertEquals(decision, ConflictsResolveDialog.Decision.KEEP_SERVER);
returnCode = true;
};
getInstrumentation().waitForIdleSync();
onView(withId(R.id.existing_checkbox)).perform(click());
DialogFragment dialog = (DialogFragment) sut.getSupportFragmentManager().findFragmentByTag("conflictDialog");
Screenshot.snap(dialog.getDialog().getWindow().getDecorView()).record();
onView(withText("OK")).perform(click());
assertTrue(returnCode);
}
@Test
public void keepNew() {
returnCode = false;
OCUpload newUpload = new OCUpload(FileStorageUtils.getSavePath(account.name) + "/nonEmpty.txt",
"/newFile.txt",
account.name);
OCFile existingFile = new OCFile("/newFile.txt");
existingFile.setFileLength(1024000);
existingFile.setModificationTimestamp(1582019340);
OCFile newFile = new OCFile("/newFile.txt");
newFile.setFileLength(56000);
newFile.setModificationTimestamp(1522019340);
newFile.setStoragePath(FileStorageUtils.getSavePath(account.name) + "/nonEmpty.txt");
FileDataStorageManager storageManager = new FileDataStorageManager(account, targetContext.getContentResolver());
storageManager.saveNewFile(existingFile);
Intent intent = new Intent(targetContext, ConflictsResolveActivity.class);
intent.putExtra(ConflictsResolveActivity.EXTRA_FILE, newFile);
intent.putExtra(ConflictsResolveActivity.EXTRA_EXISTING_FILE, existingFile);
intent.putExtra(ConflictsResolveActivity.EXTRA_CONFLICT_UPLOAD, newUpload);
ConflictsResolveActivity sut = activityRule.launchActivity(intent);
sut.listener = decision -> {
assertEquals(decision, ConflictsResolveDialog.Decision.KEEP_LOCAL);
returnCode = true;
};
getInstrumentation().waitForIdleSync();
onView(withId(R.id.new_checkbox)).perform(click());
DialogFragment dialog = (DialogFragment) sut.getSupportFragmentManager().findFragmentByTag("conflictDialog");
Screenshot.snap(dialog.getDialog().getWindow().getDecorView()).record();
onView(withText("OK")).perform(click());
assertTrue(returnCode);
}
@Test
public void keepBoth() {
returnCode = false;
OCUpload newUpload = new OCUpload(FileStorageUtils.getSavePath(account.name) + "/nonEmpty.txt",
"/newFile.txt",
account.name);
OCFile existingFile = new OCFile("/newFile.txt");
existingFile.setFileLength(1024000);
existingFile.setModificationTimestamp(1582019340);
OCFile newFile = new OCFile("/newFile.txt");
newFile.setFileLength(56000);
newFile.setModificationTimestamp(1522019340);
newFile.setStoragePath(FileStorageUtils.getSavePath(account.name) + "/nonEmpty.txt");
FileDataStorageManager storageManager = new FileDataStorageManager(account, targetContext.getContentResolver());
storageManager.saveNewFile(existingFile);
Intent intent = new Intent(targetContext, ConflictsResolveActivity.class);
intent.putExtra(ConflictsResolveActivity.EXTRA_FILE, newFile);
intent.putExtra(ConflictsResolveActivity.EXTRA_EXISTING_FILE, existingFile);
intent.putExtra(ConflictsResolveActivity.EXTRA_CONFLICT_UPLOAD, newUpload);
ConflictsResolveActivity sut = activityRule.launchActivity(intent);
sut.listener = decision -> {
assertEquals(decision, ConflictsResolveDialog.Decision.KEEP_BOTH);
returnCode = true;
};
getInstrumentation().waitForIdleSync();
onView(withId(R.id.existing_checkbox)).perform(click());
onView(withId(R.id.new_checkbox)).perform(click());
DialogFragment dialog = (DialogFragment) sut.getSupportFragmentManager().findFragmentByTag("conflictDialog");
Screenshot.snap(dialog.getDialog().getWindow().getDecorView()).record();
onView(withText("OK")).perform(click());
assertTrue(returnCode);
}
}
@@ -1,126 +0,0 @@
/*
*
* Nextcloud Android client application
*
* @author Tobias Kaminsky
* Copyright (C) 2020 Tobias Kaminsky
* Copyright (C) 2020 Nextcloud GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.owncloud.android.ui.activity;
import android.Manifest;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.net.Uri;
import android.os.Bundle;
import com.nextcloud.client.account.UserAccountManager;
import com.nextcloud.client.account.UserAccountManagerImpl;
import com.owncloud.android.AbstractIT;
import com.owncloud.android.MainApp;
import com.owncloud.android.R;
import com.owncloud.android.lib.common.accounts.AccountUtils;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import androidx.test.espresso.contrib.DrawerActions;
import androidx.test.espresso.intent.rule.IntentsTestRule;
import androidx.test.rule.GrantPermissionRule;
import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.action.ViewActions.click;
import static androidx.test.espresso.matcher.ViewMatchers.withId;
import static androidx.test.espresso.matcher.ViewMatchers.withText;
import static org.hamcrest.Matchers.anyOf;
import static org.junit.Assert.assertEquals;
public class DrawerActivityIT extends AbstractIT {
@Rule public IntentsTestRule<FileDisplayActivity> activityRule = new IntentsTestRule<>(FileDisplayActivity.class,
true,
false);
@Rule
public final GrantPermissionRule permissionRule = GrantPermissionRule.grant(
Manifest.permission.WRITE_EXTERNAL_STORAGE);
private static Account account2;
private static String account2Name;
private static String account2DisplayName;
@BeforeClass
public static void beforeClass() {
Bundle arguments = androidx.test.platform.app.InstrumentationRegistry.getArguments();
Uri baseUrl = Uri.parse(arguments.getString("TEST_SERVER_URL"));
String loginName = "user1";
String password = "user1";
Account temp = new Account(loginName + "@" + baseUrl, MainApp.getAccountType(targetContext));
UserAccountManager accountManager = UserAccountManagerImpl.fromContext(targetContext);
if (!accountManager.exists(temp)) {
AccountManager platformAccountManager = AccountManager.get(targetContext);
platformAccountManager.addAccountExplicitly(temp, password, null);
platformAccountManager.setUserData(temp, AccountUtils.Constants.KEY_OC_ACCOUNT_VERSION,
Integer.toString(UserAccountManager.ACCOUNT_VERSION));
platformAccountManager.setUserData(temp, AccountUtils.Constants.KEY_OC_VERSION, "14.0.0.0");
platformAccountManager.setUserData(temp, AccountUtils.Constants.KEY_OC_BASE_URL, baseUrl.toString());
platformAccountManager.setUserData(temp, AccountUtils.Constants.KEY_USER_ID, loginName); // same as userId
}
final UserAccountManager userAccountManager = UserAccountManagerImpl.fromContext(targetContext);
account2 = userAccountManager.getAccountByName(loginName + "@" + baseUrl);
account2Name = loginName + "@" + baseUrl;
account2DisplayName = "User One@" + baseUrl;
}
@Test
public void switchAccountViaAccountList() {
FileDisplayActivity sut = activityRule.launchActivity(null);
assertEquals(account, sut.getUser().get().toPlatformAccount());
onView(withId(R.id.drawer_layout)).perform(DrawerActions.open());
onView(withId(R.id.drawer_active_user)).perform(click());
onView(anyOf(withText(account2Name), withText(account2DisplayName))).perform(click());
waitForIdleSync();
assertEquals(account2, sut.getUser().get().toPlatformAccount());
onView(withId(R.id.drawer_layout)).perform(DrawerActions.open());
onView(withId(R.id.drawer_active_user)).perform(click());
onView(withText(account.name)).perform(click());
}
@Test
public void switchAccountViaAvatar() {
FileDisplayActivity sut = activityRule.launchActivity(null);
assertEquals(account, sut.getUser().get().toPlatformAccount());
onView(withId(R.id.drawer_layout)).perform(DrawerActions.open());
onView(withId(R.id.drawer_account_end)).perform(click());
waitForIdleSync();
assertEquals(account2, sut.getUser().get().toPlatformAccount());
onView(withId(R.id.drawer_layout)).perform(DrawerActions.open());
onView(withId(R.id.drawer_account_end)).perform(click());
}
}
Loaded 100 of 730 files, more files were not shown because too many files have changed in this diff. Show more