#3222 Merge Structured Data branch into master (#3553)

* #3222 Merge master into Structured Data branch, fix conflicts (#3447)

* [WIP] Fixes #2942. Set 'depicts' automatically for images uploaded via 'Nearby'

* Feature/refractor uploads [WIP] (#2887)

* Fix duplicate param information (#2515)

* Bug fix issue #2476 (#2526)

* Added wikidataEntityID in all db versions, handled db.execSql via method runQuery

* Versioning and changelog for v2.10.2 (#2531)

* Update changelog.md

* Versioning for v2.10.2

* Update changelog.md

* Bugfix/issue 2580 (#2584)

* Corrected string placedholders in certain string files

* Corrected string placedholders in certain string files[Bug fix #2580]

* Bug Fix #2585 (#2647)

* Bug Fix #2585
* Added null checks on view in SearchImageFragment when updating views from external sources
* Disposed the disposables in SearchActivity and SearchImageFragment when no longer in active lifecycle

* use FragmentUtils to verify fragment active state

* Bug Fix issue #2648 (#2678)

* Bug Fix issue #2648
* Handled external storage permission before file download

* * Removed redudant check for permission in MediaDetailPagerFragment (Dexter already does that)
* Removed duplicate code in PermissionUtil$checkPermissionsAndPerformAction, used the existing function with conditional extra parameters

* string name typo correction

* BugFix issue #2652 (#2706)

* Addded null check on bookmark before operating on it

* BugFix issue #2711 (#2712)

* Added null checks in OkHttpJsonApiClient$searchImages MwQueryResponse

* BugFix #2718 (#2719)

* Handled null auth cookies

* Fix #2791: NPE when nominating for deletion and leaving screen (#2792)

* Bug Fix issue #2789 (#2790)

* Handled Illegal State Exception for non existent appropriate view parents in ViewUtils$showShortSnackbar

* BugFix #2720 (#2831)

BugFix deprecated licenes #2720

* ui fixes, wip, upload

* *Issue #2886, BugFix #2832[wip]
* updated UploadActivity code
* modified ui
* Updated UploadPresenterTest

* * updated interfaces names to follow names suffixed with Contract
* added test cases

* card view elevation

* view pager disabled swipe

* bug fix, duplicate image

* used existing non-swipable view pager

* Avoid image view resize with keyboard, added adjustPan and stateVisible as softinputMode for UploadActivity

* retain UploadBaseFragment instances on orientation changes

* * Added test cases for UploadMediaPresenter
* Injected io and main thread schedulers

* categories presenter test cased wip

* Added CategoriesPresenter test

* * Added the logic to show open map (with to be uploaded image's coordinates while uploading image)

* codacy suggested changes * added java docs

* Added travis_wait fot android-wait-for-emulator

* ranamed interface onResponseCallback to Callback

* * Added api to delete picture in UploadModel
* cleanUp in UploadModel. once upload has been initiated
* Removed unused methods from UploadModel and the corresponding test class

* * Added tests for UploadPresenter
* Travis suggested changes
* Addded copy previous title and description

* * Made the upload add descriptions visible when keyboard visible
* add description request focus only when user manually requests it

* Added JavaDocs, review suggested changes

* Fix dagger injection

* use DialogUtil to show info in descriptions

* use activity context for DialogUtil

* Minor changes

* refactored title

* ui for depicts

* bug fix

* basic architecture for depicts

* adde architecture components for depicts

* [WIP] ApacheHttpClientMediaWikiApi.wikidataEditEntity: JSON param creation uses object instead of string

* resolved dagger errors

* multilingual captions and next button error resolved

* fixed next button issues in depicts fragment

* captions and depicts

* resolved previous button click issues

* fixed bindview error and added multi-captions

* replaced description and caption with uploadmediadetail

* refactored few classes

* modified ui of depicts

* minor fixes

* Bug fix, reduced the add description edit text clickable bound (#2973)

* moved depicts before categories

* replaced previous filename with captions

* removed time from filename

* added depicts suggestions

* [WIP] Wikidata Sandbox (Q4115189) test

* changes layout of layout_upload_depicts

* changed layout of upload_depicts

* code stuck at IO_SCHEDULER

* labels and description for depicts activity

* Bugfix/uploads (#3000)

* merged with master

* BugFix IllegalStateException
* setRetainState(true), not required with FragmentStatePagerAdapter
* Increase the ViewPager's Offscreen Limit, we want all the fragments to be active

* BugFix, clear selected categoris for previous upload session
* Clear Selected Categories
* Addded JavaDocs for CategoriesModel

* Code Formatting in app/src/main/java/fr/free/nrw/commons/upload/UploadModel.java

* Added class level JavaDoc UploadRemoteDataSource

* Added class level JavaDoc for UploadRepository

* Added JavaDocs for ThumbnailsAdapter

* Added JavaDocs for MediaLicensePresenter, CategoriesPresenter

* Removed null check on category query
* Show default catgeories based on image title and gps location when category text empty
* Allow search for empty category search

* Attached image scale listener to upload media image

* Bug fix, reduced the add description edit text clickable bound

* Fix memory leak (#3001)

* Bugfix/uploads (#3002)

* merged with master

* BugFix IllegalStateException
* setRetainState(true), not required with FragmentStatePagerAdapter
* Increase the ViewPager's Offscreen Limit, we want all the fragments to be active

* BugFix, clear selected categoris for previous upload session
* Clear Selected Categories
* Addded JavaDocs for CategoriesModel

* Code Formatting in app/src/main/java/fr/free/nrw/commons/upload/UploadModel.java

* Added class level JavaDoc UploadRemoteDataSource

* Added class level JavaDoc for UploadRepository

* Added JavaDocs for ThumbnailsAdapter

* Added JavaDocs for MediaLicensePresenter, CategoriesPresenter

* Removed null check on category query
* Show default catgeories based on image title and gps location when category text empty
* Allow search for empty category search

* Attached image scale listener to upload media image

* Bug fix, reduced the add description edit text clickable bound

* Added tooltip in Title in UploadMediaFragment

* BugFix recent categories

* Updated test methods

* Bugfix/uploads (#3011)

* merged with master

* BugFix IllegalStateException
* setRetainState(true), not required with FragmentStatePagerAdapter
* Increase the ViewPager's Offscreen Limit, we want all the fragments to be active

* BugFix, clear selected categoris for previous upload session
* Clear Selected Categories
* Addded JavaDocs for CategoriesModel

* Code Formatting in app/src/main/java/fr/free/nrw/commons/upload/UploadModel.java

* Added class level JavaDoc UploadRemoteDataSource

* Added class level JavaDoc for UploadRepository

* Added JavaDocs for ThumbnailsAdapter

* Added JavaDocs for MediaLicensePresenter, CategoriesPresenter

* Removed null check on category query
* Show default catgeories based on image title and gps location when category text empty
* Allow search for empty category search

* Attached image scale listener to upload media image

* Bug fix, reduced the add description edit text clickable bound

* Added tooltip in Title in UploadMediaFragment

* BugFix recent categories

* Updated test methods

* Avoid memory leak, free the adpater in MediaLicenseFragment.onDestroyView

* bugfix/uploads (#3012)

* merged with master

* BugFix IllegalStateException
* setRetainState(true), not required with FragmentStatePagerAdapter
* Increase the ViewPager's Offscreen Limit, we want all the fragments to be active

* BugFix, clear selected categoris for previous upload session
* Clear Selected Categories
* Addded JavaDocs for CategoriesModel

* Code Formatting in app/src/main/java/fr/free/nrw/commons/upload/UploadModel.java

* Added class level JavaDoc UploadRemoteDataSource

* Added class level JavaDoc for UploadRepository

* Added JavaDocs for ThumbnailsAdapter

* Added JavaDocs for MediaLicensePresenter, CategoriesPresenter

* Removed null check on category query
* Show default catgeories based on image title and gps location when category text empty
* Allow search for empty category search

* Attached image scale listener to upload media image

* Bug fix, reduced the add description edit text clickable bound

* Added tooltip in Title in UploadMediaFragment

* BugFix recent categories

* Updated test methods

* Avoid memory leak, free the adpater in MediaLicenseFragment.onDestroyView

* BugFix Illegal State Exception in ViewpPagerAdapter

* Remove irrelevant comment

* merge conflict with strings (#3016)

* [WIP] Fixed duplicated subscriprion for 'addPropertyP180'

* added documentation

* fixed issue #3006

* resolved issue #3004

* fixed issue with categoryPresenterTest.kt

* send captions as labels

* fixed issue with the captions

* optimised imports

* added upload for captions

* minor changes

* resolved issue with uploading captions

* resolved issue with api call

* uploading captions to wikibase

* added some tests and documentation

* undo formatting changes

* uploaded captions as labels to wikibase

* minor changes

* resolved error with spinner adpater

* adding captions to local database

* Fixed issue #3035

* fixed issue #3033

* fixed issue #3005

* fixed issue #3005

* added search for depicts

* fixed issue with compile time

* fixe issue with project build

* fixed issue #3044

* merged uploading depicts into branch

* uploading depicts

* rebased branch

* fixed crash due to depicts

* modified depicts interface

* Resolve merge conflicts

* Fix issues with API calls

* Use wikidata token

* searching depictions from depicts activity

* added some documentation and other changes

* fixed crash on selecting depictions

* sending wikidataentity id to upload depictions

* added changes after review

* Fixed issue with next button diabling in media detail activity

* added tests for depictions

* added all the unit tests and fixed few more issues

* showing captions in media details

* show captions in media details

* added documentations and worked upon review comments

* parsing response for depictions

* displaying captions and depiction QID in media detail

* added documentation

* fetching labels from QIDs

* captions working perfectly

* added documentations and code cleaning

* minor changes

* minor changes

* Showing items in explore

* added search via depicts in explore

* Added setOffscreenPageLimit in ViewPager

* show captions in explore

* show captions in home

* showing depict images under items

* added documentation and code refactoring

* enabled pagination in depiction search

* added some tests and media deatils in depiction detail activity

* fixed bug with back button in media

* fixed issue #3100

* fixed issue #3098

* fixed issue #3099

* fixed issue #3104 and #3098

* showing captions in place of title in home and explore:media

* show captions in explore:depiction image list activity

* showing depictions in media details

* showing depictions in media details in production flavor

* fixed issue #3108 and #3107

* fix isse #3108

* fixed issue #3110 and #3112

* fixed issue #3113

* added documentations

* fixed issue #3076 and #3109

* added depiction search test

* fixed issue #3113

* fixed issue #3111

* fixed issue #3106

* Showing items in explore

* minor change

* fixed issue #3118 and some other changes

* added MVP in searchdepictionsfragment

* added mvp architecture

* added MVP architecture to DepictedImagesDetailsActivity

* added documentation and some minor changes

* added image to depicted item in search depictions

* * Use callbacks from renderer to fetch thumbnails

* adding fresco to load image in depictions

* adding thumbnail image for depictions in upload and explore

* pagination issues

* fixed issue --(showing previous depiction thumbnail in explore)

* Fixed the logic for pagination

* hide progress on success of last page

* adding sub-items and parent items to search in explore

* minor changes for review comments

* fixed issue #3119

* fixed issue #3130

* changes after review comments

* showing child classes for depictions

* Showing child items

* showing parent classes for depicted items

* adding localised search for parent and child items

* clicking on any child class or parent class should call the corresponding class items

* fixed issue of showing wrong thumbnail for P18 item

* fixed issue #3132

* added test for DepictedImagesPresenter.java

* added unit tests for depicted items parent and child classes

* removed unused imports and code formatting

* fixed issue in search test

* deleting unnecessary .attach_pid9313 file

* deleting unnecessary .attach_pid9655 file

* added SearchDepictionsPresenterTest

* changes after review comments

* updates for review comments

* added more documentations

* removed unused code and classes and addressed spacing changes

* changes after review

* fixed build issues in the app

* worked on some review comments

* fixed issue:wrong thumbnail appears on wikidata item

* minor change

* worked on some review changes

* worked on review comments

* minor change

* addressed remaining review comments

* replaced hardcoded jpgs with pageIds to fetch captions

* added documentation

* removed hardcoded extensions and worked on review comments

* review comments

* [WIP] Added Depicts values for flavors

* [WIP] Minor fix

* [WIP] Minor fixes

* [WIP] Fixed URL

* [WIP] Fixed URLs and tokens

* Fixed MediaClient: added check for null in continuation store

* Fixed Media::from, changed return from null to new Media()

* [WIP] Merged with master

* Fix #3254 Displays a proper message in explore section when no result for caption

* Updated Mockito to org.mockito:mockito-inline:2.13.0

* [WIP] Fixed tests after merging

* [WIP] Fixed some JUnit tests

* Fixed 'accessing from wrong thread' error

* #3222 Delete manifest declaration of activity as fragment - stop casting MainActivity to CatgoryImagesCallback - fix tests

* Remove unit test not associated with any class - make CategoryPresenterTest more idiomatic

* fix compilation errors

Co-authored-by: Vitaly V. Pinchuk <vetal.978@gmail.com>
Co-authored-by: Ashish Kumar <ashishkumar468@gmail.com>
Co-authored-by: vanshikaarora <vanshikaa937@gmail.com>
Co-authored-by: Vivek Maskara <maskaravivek@gmail.com>
Co-authored-by: Vanshika Arora <34261945+vanshikaarora@users.noreply.github.com>
Co-authored-by: Somanshu and Himanshu <somanshS14@gmail.com>

* #3482 Use Room in Structured Data branch - remove unused code (#3483)

* #3482 Use Room in Structured Data branch - remove unused code

* #3482 Use Room in Structured Data branch - fix unit test compilation

* #3482 Use Room in Structured Data branch - add kdoc

* #3490 Depiction Search in upload shows No Results before it gets results (#3491)

* #3482 Use Room in Structured Data branch - remove unused code

* #3482 Use Room in Structured Data branch - fix unit test compilation

* #3490 Depiction Search in upload shows No Results before it gets results - stop showing error on subscription

* #3490 Depiction Search in upload shows No Results before it gets results - update test cases

* make labels nullable too

* fix unit test compilation

* #3222 remove lingering reference to depiction content provider

* Fix Crash

* #3222 Merge master into Structured Data branch, fix conflicts - review fixes

* Fix method invocations

* #3529 Captions/depictions are not saved to Commons (#3574)

* #3529 Captions/depictions are not saved to Commons - make copy of list of depictionEntityIds - uncomment editBaseDepictsProperty - refactor upload related classes

* #3529 Captions/depictions are not saved to Commons - fix wrong ArrayList usage

* #3529 Captions/depictions are not saved to Commons - fix test

* #3503 Remove Title/Caption From MediaUploadDetail and only use Caption/Description pairs  (#3578)

* #3529 Captions/depictions are not saved to Commons - make copy of list of depictionEntityIds - uncomment editBaseDepictsProperty - refactor upload related classes

* #3529 Captions/depictions are not saved to Commons - fix wrong ArrayList usage

* #3529 Captions/depictions are not saved to Commons - fix test

* #3503 Remove Title/Caption From MediaUploadDetail and only use Caption/Description pairs - replace title with the first MediaDetail

* #3503 Remove Title/Caption From MediaUploadDetail and only use Caption/Description pairs - restore button disabling

* #3503 Remove Title/Caption From MediaUploadDetail and only use Caption/Description pairs - fix nearby place

* fix thumbnail issue 3526 (#3617)

* #3222 Merge master into Structured Data branch, fix conflicts - fix bad merge

* #3529 Captions/depictions are not saved to Commons (#3588)

* #3529 Captions/depictions are not saved to Commons - update flow to update appropriate data

* #3529 Captions/depictions are not saved to Commons - fix invoking of setlabel

* #3529 Captions/depictions are not saved to Commons - fix unit tests

* #3529 Captions/depictions are not saved to Commons - use constant for @Named

* #3529 Captions/depictions are not saved to Commons - remove captions interface

* #3529 Captions/depictions are not saved to Commons - delete unused Contribution fields - enforce Single Responsibility by using PageContentsCreator

* #3529 Captions/depictions are not saved to Commons - prefix id with M - remove language from url and only add from Field

* #3529 Captions/depictions are not saved to Commons - make edits of depictions and captions sequential

* #3529 Captions/depictions are not saved to Commons - remove unused model fields

* #3529 Captions/depictions are not saved to Commons - weaken type of categories - copy list on Contribution creation

* #3529 Captions/depictions are not saved to Commons - mark Media fields private - weaken types - remove partly implemented fields

* #3529 Captions/depictions are not saved to Commons - add semi colon

* #3529 Captions/depictions are not saved to Commons - fix test

* Fix issue 3526 Unlike "Items" tab, "child classes" tab does not display description nor image thumbnail (#3619)

* fix thumbnail issue 3526

* Fix Description issue 3526

* revert changes on this file, not finished with it yet

* Fix Description for Child and Parent classes - issue 3526

* Remove conflict text in file

* Remove retrofit.HEAD import

* Incorporated review comments

* Fix issue 3137 (#3637)

* Fix issue 3137

* Remove import Timber

* Remove unnecessary space

* #3222 Merge master into Structured Data branch, fix conflicts - revert logging

* Fix build

* #3661 No Depictions Selected Dialog has reversed buttons - fix button order

* Revert "#3661 No Depictions Selected Dialog has reversed buttons - fix button order"

This reverts commit d8f9809584.

* #3222 Merge master into Structured Data branch, fix conflicts - remove unused methods/fields

* #3661 No Depictions Selected Dialog has reversed buttons - fix button order (#3662)

* #3653 Many Mnull requests - stop requesting captions for null ids (#3657)

* #3653 Many Mnull requests - stop requesting captions for null ids

* #3653 Many Mnull requests - move log line

* #3633 [structured-data branch] In depictions selection screen, suggest nearby items  (#3650)

* #3633 [structured-data branch] In depictions selection screen, suggest nearby items - for empty search terms show nearby items for depictions

* #3633 [structured-data branch] In depictions selection screen, suggest nearby items - use linear radii progression to search for places

* #3666 Crash when uploading on structured-data branch - revert cleanup of UploadController (#3670)

* #3222 Merge Structured Data branch into master - fix caption rendering in new UI

* #3222 Merge Structured Data branch into master - upgrade retrofit + okhttp

* #3664 Stop using JsonObject on StructuredData (#3672)

* #3664 Stop using JsonObject on StructuredData - remove usage in Media classes - remove from depicts client - create partial network models

* #3664 Stop using JsonObject on StructuredData - allow partial mapping of polymorphic models by returning null in typeadapter

* #3664 Stop using JsonObject on StructuredData - use models for editing depicts property

* #3664 Stop using JsonObject on StructuredData - use models for sparql parent query

* #3664 Stop using JsonObject on StructuredData - fix unit test compilation

* #3664 Stop using JsonObject on StructuredData - unify sparql responses

* #3664 Stop using JsonObject on StructuredData - minor cleanup of misnamed/unused/too broad visibility

* #3664 Stop using JsonObject on StructuredData - share variable names and logic for the Sarql queries

* #3664 Stop using JsonObject on StructuredData - add error logging

Co-authored-by: Vitaly V. Pinchuk <vetal.978@gmail.com>
Co-authored-by: Ashish Kumar <ashishkumar468@gmail.com>
Co-authored-by: vanshikaarora <vanshikaa937@gmail.com>
Co-authored-by: Vivek Maskara <maskaravivek@gmail.com>
Co-authored-by: Vanshika Arora <34261945+vanshikaarora@users.noreply.github.com>
Co-authored-by: Somanshu and Himanshu <somanshS14@gmail.com>
Co-authored-by: vvijayalakshmi21 <34595292+vvijayalakshmi21@users.noreply.github.com>
This commit is contained in:
Seán Mac Gillicuddy 2020-04-21 17:34:53 +01:00 committed by GitHub
parent 22c20687f3
commit 0f906b20c9
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
168 changed files with 7463 additions and 2123 deletions

View file

@ -45,8 +45,8 @@ class MediaDataExtractorTest {
`when`(mediaClient?.getPageHtml(ArgumentMatchers.anyString()))
.thenReturn(Single.just("Test"))
val fetchMediaDetails = mediaDataExtractor?.fetchMediaDetails("test.jpg")?.blockingGet()
//val fetchMediaDetails = mediaDataExtractor?.fetchMediaDetails("File:Test.jpg", null)
assertTrue(fetchMediaDetails is Media)
//assertTrue(fetchMediaDetails is Media)
}
}

View file

@ -1,48 +0,0 @@
package fr.free.nrw.commons.cache
import com.github.varunpant.quadtree.Point
import com.github.varunpant.quadtree.QuadTree
import fr.free.nrw.commons.caching.CacheController
import org.junit.Before
import org.junit.Test
import org.mockito.ArgumentMatchers
import org.mockito.Mock
import org.mockito.Mockito
import org.mockito.Mockito.verify
import org.mockito.MockitoAnnotations
class CacheControllerTest {
/**
* initial setup, test environment
*/
private lateinit var cacheController: CacheController
@Mock
private lateinit var quadTree: QuadTree<List<String>>
private lateinit var points: Array<Point<List<String>>>
var value = ArrayList<String>()
@Before
@Throws(Exception::class)
fun setUp() {
MockitoAnnotations.initMocks(this)
val point = Point<List<String>>(1.0, 1.0, value)
points = arrayOf(point)
value.add("1")
cacheController = CacheController(quadTree)
Mockito.`when`(quadTree.searchWithin(ArgumentMatchers.anyDouble(), ArgumentMatchers.anyDouble(), ArgumentMatchers.anyDouble(), ArgumentMatchers.anyDouble())).thenReturn(points)
}
/**
* Test find category
*/
@Test
fun testFindCategory() {
val findCategory = cacheController.findCategory()
verify(quadTree).searchWithin(ArgumentMatchers.anyDouble(), ArgumentMatchers.anyDouble(), ArgumentMatchers.anyDouble(), ArgumentMatchers.anyDouble())
assert(findCategory.size == 1)
}
}

View file

@ -1,105 +1,78 @@
package fr.free.nrw.commons.category
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.whenever
import fr.free.nrw.commons.kvstore.JsonKvStore
import fr.free.nrw.commons.upload.GpsCategoryModel
import io.reactivex.Observable
import junit.framework.Assert.*
import junit.framework.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.mockito.*
import org.wikipedia.dataclient.mwapi.MwQueryPage
import org.wikipedia.dataclient.mwapi.MwQueryResponse
import org.wikipedia.dataclient.mwapi.MwQueryResult
import android.content.Context
import com.google.gson.Gson
import fr.free.nrw.commons.kvstore.JsonKvStore
import org.mockito.ArgumentMatchers.anyString
import org.mockito.ArgumentMatchers.eq
import org.mockito.Mock
import org.mockito.MockitoAnnotations
//class for testing CategoriesModel class
class CategoriesModelTest {
@Mock
internal var categoryInterface: CategoryInterface? = null
@Mock
internal var categoryItem: CategoryItem? = null
@Spy
internal lateinit var gson: Gson
@Spy
internal lateinit var categoryItemForSubstringSearch: CategoryItem
internal lateinit var categoryDao: CategoryDao
@Mock
internal var categoryDao: CategoryDao? = null
@Mock
internal var context: Context? = null
@InjectMocks
var categoryClient: CategoryClient? = null
internal lateinit var categoryClient: CategoryClient
@Before
@Throws(Exception::class)
fun setUp() {
gson = Gson()
categoryItemForSubstringSearch = CategoryItem("",false)
MockitoAnnotations.initMocks(this)
}
// Test Case for verifying that Categories search (MW api calls) are case-insensitive
@Test
fun searchAllFoundCaseTest() {
val mwQueryPage = Mockito.mock(MwQueryPage::class.java)
Mockito.`when`(mwQueryPage.title()).thenReturn("Category:Test")
val mwQueryResult = Mockito.mock(MwQueryResult::class.java)
Mockito.`when`(mwQueryResult.pages()).thenReturn(listOf(mwQueryPage))
val mockResponse = Mockito.mock(MwQueryResponse::class.java)
Mockito.`when`(mockResponse.query()).thenReturn(mwQueryResult)
val categoriesModel: CategoriesModel = CategoriesModel(categoryClient,null,null)
val categoriesModel = CategoriesModel(categoryClient, null, null, mock())
Mockito.`when`(categoryInterface!!.searchCategoriesForPrefix(ArgumentMatchers.anyString(), ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt()))
.thenReturn(Observable.just(mockResponse))
whenever(categoryClient.searchCategoriesForPrefix(anyString(), eq(25)))
.thenReturn(Observable.just("Test"))
// Checking if both return "Test"
val actualCategoryName = categoriesModel!!.searchAll("tes",null).blockingFirst()
assertEquals("Test", actualCategoryName.getName())
val actualCategoryNameCaps = categoriesModel!!.searchAll("Tes",null).blockingFirst()
assertEquals("Test", actualCategoryNameCaps.getName())
val actualCategoryName = categoriesModel.searchAll("tes", null).blockingFirst()
assertEquals("Test", actualCategoryName.name)
val actualCategoryNameCaps = categoriesModel.searchAll("Tes", null).blockingFirst()
assertEquals("Test", actualCategoryNameCaps.name)
}
/**
* For testing the substring search algorithm for Categories search
* To be more precise it tests the In Between substring( ex: searching `atte`
* will give search suggestions: `Latte`, `Iced latte` e.t.c) which has been described
* on github repo wiki:
* https://github.com/commons-app/apps-android-commons/wiki/Category-suggestions-(readme)#user-content-3-category-search-when-typing-in-the-search-field-has-been-made-more-flexible
*/
* For testing the substring search algorithm for Categories search
* To be more precise it tests the In Between substring( ex: searching `atte`
* will give search suggestions: `Latte`, `Iced latte` e.t.c) which has been described
* on github repo wiki:
* https://github.com/commons-app/apps-android-commons/wiki/Category-suggestions-(readme)#user-content-3-category-search-when-typing-in-the-search-field-has-been-made-more-flexible
*/
@Test
fun searchAllFoundCaseTestForSubstringSearch() {
val mockDaoList = mutableListOf<String>("")
val mwQueryPage = Mockito.mock(MwQueryPage::class.java)
Mockito.`when`(mwQueryPage.title()).thenReturn("Category:Test")
val mwQueryResult = Mockito.mock(MwQueryResult::class.java)
Mockito.`when`(mwQueryResult.pages()).thenReturn(listOf(mwQueryPage))
val mockResponse = Mockito.mock(MwQueryResponse::class.java)
Mockito.`when`(mockResponse.query()).thenReturn(mwQueryResult)
Mockito.`when`(context!!.getSharedPreferences("",0))
.thenReturn(null)
val directKvStore = Mockito.spy(JsonKvStore(context,"",gson))
val categoriesModelForSubstringSearch = Mockito.spy(CategoriesModel(categoryClient,categoryDao,directKvStore))
Mockito.doReturn(Observable.just(categoryItemForSubstringSearch)).`when`(categoriesModelForSubstringSearch).gpsCategories()
Mockito.`when`(context!!.getSharedPreferences("",0))
.thenReturn(null)
Mockito.`when`(categoryInterface!!.searchCategories(ArgumentMatchers.anyString(), ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt()))
.thenReturn(Observable.just(mockResponse))
Mockito.doReturn(mockDaoList).`when`(categoryDao)?.recentCategories(25)
Mockito.doReturn("Random Value").`when`(directKvStore).getString("Category","")
Mockito.`when`(categoryInterface!!.searchCategories(ArgumentMatchers.anyString(), ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt()))
.thenReturn(Observable.just(mockResponse))
val gpsCategoryModel: GpsCategoryModel = mock()
val kvStore: JsonKvStore = mock()
// Checking if both return "Test"
val actualCategoryName = categoriesModelForSubstringSearch!!.searchAll(null, listOf<String>("tes")).blockingLast()
assertEquals("Test",actualCategoryName.getName())
val actualCategoryNameCaps = categoriesModelForSubstringSearch!!.searchAll(null, listOf<String>("Tes")).blockingLast()
assertEquals("Test",actualCategoryNameCaps.getName())
whenever(gpsCategoryModel.categoryList).thenReturn(listOf("gpsCategory"))
whenever(categoryClient.searchCategories("tes", 25))
.thenReturn(Observable.just("tes"))
whenever(kvStore.getString("Category", "")).thenReturn("Random Value")
whenever(categoryDao.recentCategories(25)).thenReturn(listOf("recentCategories"))
CategoriesModel(
categoryClient,
categoryDao,
kvStore,
gpsCategoryModel
).searchAll(null, listOf("tes"))
.test()
.assertValues(
CategoryItem("gpsCategory", false),
CategoryItem("tes", false),
CategoryItem("Random Value", false),
CategoryItem("recentCategories", false)
)
}
}
}

View file

@ -106,7 +106,7 @@ class CategoryDaoTest {
cursor.moveToFirst()
testObject.fromCursor(cursor).let {
assertEquals(uriForId(1), it.contentUri)
assertEquals("foo", it.name)
assertEquals("showImageWithItem", it.name)
assertEquals(123, it.lastUsed.time)
assertEquals(2, it.timesUsed)
}
@ -134,7 +134,7 @@ class CategoryDaoTest {
fun saveNewCategory() {
val contentUri = CategoryContentProvider.uriForId(111)
whenever(client.insert(isA(), isA())).thenReturn(contentUri)
val category = Category(null, "foo", Date(234L), 1)
val category = Category(null, "showImageWithItem", Date(234L), 1)
testObject.save(category)
@ -157,13 +157,13 @@ class CategoryDaoTest {
@Test
fun whenTheresNoDataFindReturnsNull_nullCursor() {
whenever(client.query(any(), any(), any(), any(), any())).thenReturn(null)
assertNull(testObject.find("foo"))
assertNull(testObject.find("showImageWithItem"))
}
@Test
fun whenTheresNoDataFindReturnsNull_emptyCursor() {
whenever(client.query(any(), any(), any(), any(), any())).thenReturn(createCursor(0))
assertNull(testObject.find("foo"))
assertNull(testObject.find("showImageWithItem"))
}
@Test
@ -172,7 +172,7 @@ class CategoryDaoTest {
whenever(client.query(any(), any(), any(), any(), anyOrNull())).thenReturn(mockCursor)
whenever(mockCursor.moveToFirst()).thenReturn(false)
testObject.find("foo")
testObject.find("showImageWithItem")
verify(mockCursor).close()
}
@ -181,11 +181,11 @@ class CategoryDaoTest {
fun findCategory() {
whenever(client.query(any(), any(), any(), any(), anyOrNull())).thenReturn(createCursor(1))
val category = testObject.find("foo")
val category = testObject.find("showImageWithItem")
assertNotNull(category)
assertEquals(uriForId(1), category?.contentUri)
assertEquals("foo", category?.name)
assertEquals("showImageWithItem", category?.name)
assertEquals(123L, category?.lastUsed?.time)
assertEquals(2, category?.timesUsed)
@ -196,13 +196,13 @@ class CategoryDaoTest {
queryCaptor.capture(),
isNull()
)
assertEquals("foo", queryCaptor.firstValue[0])
assertEquals("showImageWithItem", queryCaptor.firstValue[0])
}
@Test(expected = RuntimeException::class)
fun findCategoryTranslatesExceptions() {
whenever(client.query(any(), any(), any(), any(), anyOrNull())).thenThrow(RemoteException(""))
testObject.find("foo")
testObject.find("showImageWithItem")
}
@Test(expected = RuntimeException::class)
@ -241,7 +241,7 @@ class CategoryDaoTest {
val result = testObject.recentCategories(10)
assertEquals(1, result.size)
assertEquals("foo", result[0])
assertEquals("showImageWithItem", result[0])
verify(client).query(
eq(BASE_URI),
@ -264,7 +264,7 @@ class CategoryDaoTest {
private fun createCursor(rowCount: Int) = MatrixCursor(columns, rowCount).apply {
for (i in 0 until rowCount) {
addRow(listOf("1", "foo", "123", "2"))
addRow(listOf("1", "showImageWithItem", "123", "2"))
}
}

View file

@ -2,22 +2,19 @@ package fr.free.nrw.commons.delete
import android.content.Context
import com.nhaarman.mockitokotlin2.eq
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.whenever
import fr.free.nrw.commons.Media
import fr.free.nrw.commons.actions.PageEditClient
import fr.free.nrw.commons.notification.NotificationHelper
import fr.free.nrw.commons.utils.ViewUtilWrapper
import io.reactivex.Observable
import org.junit.Assert.*
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.mockito.ArgumentMatchers
import org.mockito.InjectMocks
import org.mockito.Mock
import org.mockito.Mockito.`when`
import org.mockito.MockitoAnnotations
import javax.inject.Inject
import javax.inject.Named
/**
* Tests for delete helper
@ -25,23 +22,15 @@ import javax.inject.Named
class DeleteHelperTest {
@Mock
@field:[Inject Named("commons-page-edit")]
internal var pageEditClient: PageEditClient? = null
internal lateinit var pageEditClient: PageEditClient
@Mock
internal var context: Context? = null
internal lateinit var context: Context
@Mock
internal var notificationHelper: NotificationHelper? = null
internal lateinit var media: Media
@Mock
internal var viewUtil: ViewUtilWrapper? = null
@Mock
internal var media: Media? = null
@InjectMocks
var deleteHelper: DeleteHelper? = null
lateinit var deleteHelper: DeleteHelper
/**
* Init mocks for test
@ -49,6 +38,7 @@ class DeleteHelperTest {
@Before
fun setup() {
MockitoAnnotations.initMocks(this)
deleteHelper = DeleteHelper(mock(), pageEditClient, mock(), "")
}
/**
@ -56,23 +46,23 @@ class DeleteHelperTest {
*/
@Test
fun makeDeletion() {
`when`(pageEditClient?.prependEdit(ArgumentMatchers.anyString(), ArgumentMatchers.anyString(), ArgumentMatchers.anyString()))
whenever(pageEditClient.prependEdit(ArgumentMatchers.anyString(), ArgumentMatchers.anyString(), ArgumentMatchers.anyString()))
.thenReturn(Observable.just(true))
`when`(pageEditClient?.appendEdit(ArgumentMatchers.anyString(), ArgumentMatchers.anyString(), ArgumentMatchers.anyString()))
whenever(pageEditClient.appendEdit(ArgumentMatchers.anyString(), ArgumentMatchers.anyString(), ArgumentMatchers.anyString()))
.thenReturn(Observable.just(true))
`when`(pageEditClient?.edit(ArgumentMatchers.anyString(), ArgumentMatchers.anyString(), ArgumentMatchers.anyString()))
whenever(pageEditClient.edit(ArgumentMatchers.anyString(), ArgumentMatchers.anyString(), ArgumentMatchers.anyString()))
.thenReturn(Observable.just(true))
`when`(media?.displayTitle).thenReturn("Test file")
media?.filename="Test file.jpg"
whenever(media.displayTitle).thenReturn("Test file")
val creatorName = "Creator"
`when`(media?.getCreator()).thenReturn("$creatorName (page does not exist)")
whenever(media.creator).thenReturn("$creatorName (page does not exist)")
whenever(media.filename).thenReturn("Test file.jpg")
val makeDeletion = deleteHelper?.makeDeletion(context, media, "Test reason")?.blockingGet()
val makeDeletion = deleteHelper.makeDeletion(context, media, "Test reason")?.blockingGet()
assertNotNull(makeDeletion)
assertTrue(makeDeletion!!)
verify(pageEditClient)?.appendEdit(eq("User_Talk:$creatorName"), ArgumentMatchers.anyString(), ArgumentMatchers.anyString())
verify(pageEditClient).appendEdit(eq("User_Talk:$creatorName"), ArgumentMatchers.anyString(), ArgumentMatchers.anyString())
}
/**
@ -80,63 +70,63 @@ class DeleteHelperTest {
*/
@Test(expected = RuntimeException::class)
fun makeDeletionForPrependEditFailure() {
`when`(pageEditClient?.prependEdit(ArgumentMatchers.anyString(), ArgumentMatchers.anyString(), ArgumentMatchers.anyString()))
whenever(pageEditClient.prependEdit(ArgumentMatchers.anyString(), ArgumentMatchers.anyString(), ArgumentMatchers.anyString()))
.thenReturn(Observable.just(false))
`when`(pageEditClient?.appendEdit(ArgumentMatchers.anyString(), ArgumentMatchers.anyString(), ArgumentMatchers.anyString()))
whenever(pageEditClient.appendEdit(ArgumentMatchers.anyString(), ArgumentMatchers.anyString(), ArgumentMatchers.anyString()))
.thenReturn(Observable.just(true))
`when`(pageEditClient?.edit(ArgumentMatchers.anyString(), ArgumentMatchers.anyString(), ArgumentMatchers.anyString()))
whenever(pageEditClient.edit(ArgumentMatchers.anyString(), ArgumentMatchers.anyString(), ArgumentMatchers.anyString()))
.thenReturn(Observable.just(true))
`when`(media?.displayTitle).thenReturn("Test file")
`when`(media?.filename).thenReturn("Test file.jpg")
`when`(media?.creator).thenReturn("Creator (page does not exist)")
whenever(media.displayTitle).thenReturn("Test file")
whenever(media.filename).thenReturn("Test file.jpg")
whenever(media.creator).thenReturn("Creator (page does not exist)")
deleteHelper?.makeDeletion(context, media, "Test reason")?.blockingGet()
deleteHelper.makeDeletion(context, media, "Test reason")?.blockingGet()
}
@Test(expected = RuntimeException::class)
fun makeDeletionForEditFailure() {
`when`(pageEditClient?.prependEdit(ArgumentMatchers.anyString(), ArgumentMatchers.anyString(), ArgumentMatchers.anyString()))
whenever(pageEditClient.prependEdit(ArgumentMatchers.anyString(), ArgumentMatchers.anyString(), ArgumentMatchers.anyString()))
.thenReturn(Observable.just(true))
`when`(pageEditClient?.appendEdit(ArgumentMatchers.anyString(), ArgumentMatchers.anyString(), ArgumentMatchers.anyString()))
whenever(pageEditClient.appendEdit(ArgumentMatchers.anyString(), ArgumentMatchers.anyString(), ArgumentMatchers.anyString()))
.thenReturn(Observable.just(true))
`when`(pageEditClient?.edit(ArgumentMatchers.anyString(), ArgumentMatchers.anyString(), ArgumentMatchers.anyString()))
whenever(pageEditClient.edit(ArgumentMatchers.anyString(), ArgumentMatchers.anyString(), ArgumentMatchers.anyString()))
.thenReturn(Observable.just(false))
`when`(media?.displayTitle).thenReturn("Test file")
`when`(media?.filename).thenReturn("Test file.jpg")
`when`(media?.creator).thenReturn("Creator (page does not exist)")
whenever(media.displayTitle).thenReturn("Test file")
whenever(media.filename).thenReturn("Test file.jpg")
whenever(media.creator).thenReturn("Creator (page does not exist)")
deleteHelper?.makeDeletion(context, media, "Test reason")?.blockingGet()
deleteHelper.makeDeletion(context, media, "Test reason")?.blockingGet()
}
@Test(expected = RuntimeException::class)
fun makeDeletionForAppendEditFailure() {
`when`(pageEditClient?.prependEdit(ArgumentMatchers.anyString(), ArgumentMatchers.anyString(), ArgumentMatchers.anyString()))
whenever(pageEditClient.prependEdit(ArgumentMatchers.anyString(), ArgumentMatchers.anyString(), ArgumentMatchers.anyString()))
.thenReturn(Observable.just(true))
`when`(pageEditClient?.appendEdit(ArgumentMatchers.anyString(), ArgumentMatchers.anyString(), ArgumentMatchers.anyString()))
whenever(pageEditClient.appendEdit(ArgumentMatchers.anyString(), ArgumentMatchers.anyString(), ArgumentMatchers.anyString()))
.thenReturn(Observable.just(false))
`when`(pageEditClient?.edit(ArgumentMatchers.anyString(), ArgumentMatchers.anyString(), ArgumentMatchers.anyString()))
whenever(pageEditClient.edit(ArgumentMatchers.anyString(), ArgumentMatchers.anyString(), ArgumentMatchers.anyString()))
.thenReturn(Observable.just(true))
`when`(media?.displayTitle).thenReturn("Test file")
`when`(media?.filename).thenReturn("Test file.jpg")
`when`(media?.creator).thenReturn("Creator (page does not exist)")
whenever(media.displayTitle).thenReturn("Test file")
whenever(media.filename).thenReturn("Test file.jpg")
whenever(media.creator).thenReturn("Creator (page does not exist)")
deleteHelper?.makeDeletion(context, media, "Test reason")?.blockingGet()
deleteHelper.makeDeletion(context, media, "Test reason")?.blockingGet()
}
@Test(expected = RuntimeException::class)
fun makeDeletionForEmptyCreatorName() {
`when`(pageEditClient?.prependEdit(ArgumentMatchers.anyString(), ArgumentMatchers.anyString(), ArgumentMatchers.anyString()))
whenever(pageEditClient.prependEdit(ArgumentMatchers.anyString(), ArgumentMatchers.anyString(), ArgumentMatchers.anyString()))
.thenReturn(Observable.just(true))
`when`(pageEditClient?.appendEdit(ArgumentMatchers.anyString(), ArgumentMatchers.anyString(), ArgumentMatchers.anyString()))
whenever(pageEditClient.appendEdit(ArgumentMatchers.anyString(), ArgumentMatchers.anyString(), ArgumentMatchers.anyString()))
.thenReturn(Observable.just(true))
`when`(pageEditClient?.edit(ArgumentMatchers.anyString(), ArgumentMatchers.anyString(), ArgumentMatchers.anyString()))
whenever(pageEditClient.edit(ArgumentMatchers.anyString(), ArgumentMatchers.anyString(), ArgumentMatchers.anyString()))
.thenReturn(Observable.just(true))
`when`(media?.displayTitle).thenReturn("Test file")
media?.filename="Test file.jpg"
whenever(media.displayTitle).thenReturn("Test file")
media.filename ="Test file.jpg"
`when`(media?.getCreator()).thenReturn(null)
whenever(media.creator).thenReturn(null)
deleteHelper?.makeDeletion(context, media, "Test reason")?.blockingGet()
deleteHelper.makeDeletion(context, media, "Test reason")?.blockingGet()
}
}
}

View file

@ -0,0 +1,73 @@
package fr.free.nrw.commons.depictions
import org.mockito.Mockito.verify
import fr.free.nrw.commons.Media
import fr.free.nrw.commons.depictions.Media.DepictedImagesFragment
import fr.free.nrw.commons.depictions.Media.DepictedImagesPresenter
import fr.free.nrw.commons.explore.depictions.DepictsClient
import fr.free.nrw.commons.kvstore.JsonKvStore
import fr.free.nrw.commons.media.MediaClient
import io.reactivex.Observable
import io.reactivex.Single
import io.reactivex.schedulers.TestScheduler
import org.junit.Before
import org.junit.Test
import org.mockito.ArgumentMatchers
import org.mockito.Mock
import org.mockito.Mockito
import org.mockito.MockitoAnnotations
class DepictedImagesPresenterTest {
@Mock
internal var view: DepictedImagesFragment? = null
var depictedImagesPresenter: DepictedImagesPresenter? = null
var jsonKvStore: JsonKvStore? = null
@Mock
var depictsClient: DepictsClient? = null
@Mock
var mediaClient: MediaClient? = null
var testScheduler: TestScheduler? = null
val mediaList: ArrayList<Media> = ArrayList()
@Mock
lateinit var mediaItem: Media
var testObservable: Observable<List<Media>>? = null
@Before
@Throws(Exception::class)
fun setUp() {
MockitoAnnotations.initMocks(this)
testScheduler = TestScheduler()
mediaList.add(mediaItem)
testObservable = Observable.just(mediaList)
depictedImagesPresenter = DepictedImagesPresenter(jsonKvStore, depictsClient, mediaClient, testScheduler, testScheduler)
depictedImagesPresenter?.onAttachView(view)
}
@Test
fun initList() {
Mockito.`when`(depictsClient?.fetchImagesForDepictedItem(ArgumentMatchers.anyString(),
ArgumentMatchers.anyInt())).thenReturn(testObservable)
depictedImagesPresenter?.initList("rabbit")
depictedImagesPresenter?.handleSuccess(mediaList)
verify(view)?.handleSuccess(mediaList)
}
@Test
fun replaceTitlesWithCaptions() {
var stringObservable: Single<String>? = Single.just(String())
Mockito.`when`(mediaClient?.getCaptionByWikibaseIdentifier(ArgumentMatchers.anyString()))?.thenReturn(stringObservable)
depictedImagesPresenter?.replaceTitlesWithCaptions("File:rabbit.jpg", 0)
testScheduler?.triggerActions()
verify(view)?.handleLabelforImage("", 0)
}
}

View file

@ -0,0 +1,79 @@
package fr.free.nrw.commons.depictions
import fr.free.nrw.commons.depictions.subClass.SubDepictionListContract
import fr.free.nrw.commons.depictions.subClass.SubDepictionListPresenter
import fr.free.nrw.commons.explore.depictions.DepictsClient
import fr.free.nrw.commons.explore.recentsearches.RecentSearchesDao
import fr.free.nrw.commons.mwapi.OkHttpJsonApiClient
import fr.free.nrw.commons.upload.structure.depictions.DepictedItem
import io.reactivex.Observable
import io.reactivex.Single
import io.reactivex.schedulers.TestScheduler
import org.junit.Before
import org.junit.Test
import org.mockito.ArgumentMatchers
import org.mockito.Mock
import org.mockito.Mockito
import org.mockito.Mockito.verify
import org.mockito.MockitoAnnotations
class SubDepictionListPresenterTest {
@Mock
internal var view: SubDepictionListContract.View? = null
var subDepictionListPresenter: SubDepictionListPresenter? = null
var testScheduler: TestScheduler? = null
internal var recentSearchesDao: RecentSearchesDao? = null
@Mock
internal var depictsClient: DepictsClient? = null
@Mock
internal var okHttpJsonApiClient: OkHttpJsonApiClient? = null
var testObservable: Observable<List<DepictedItem>>? = null
@Mock
lateinit var depictedItem: DepictedItem
val depictedItems: ArrayList<DepictedItem> = ArrayList()
@Before
@Throws(Exception::class)
fun setUp() {
MockitoAnnotations.initMocks(this)
testScheduler = TestScheduler()
depictedItems.add(depictedItem)
testObservable = Observable.just(depictedItems)
subDepictionListPresenter = SubDepictionListPresenter(recentSearchesDao, depictsClient, okHttpJsonApiClient, testScheduler, testScheduler)
subDepictionListPresenter?.onAttachView(view)
}
@Test
fun fetchThumbnailForEntityId() {
val singleString: Single<String> = Single.just(String())
Mockito.`when`(depictsClient?.getP18ForItem(ArgumentMatchers.anyString())).thenReturn(singleString)
subDepictionListPresenter?.fetchThumbnailForEntityId("Q9394", 0)
testScheduler?.triggerActions()
view?.onImageUrlFetched("url", 0)
}
@Test
fun initSubDepictionListForParentClass() {
Mockito.`when`(okHttpJsonApiClient?.getParentQIDs(ArgumentMatchers.anyString())).thenReturn(testObservable)
subDepictionListPresenter?.initSubDepictionList("Q9394", true)
testScheduler?.triggerActions()
verify(view)?.onSuccess(depictedItems)
}
@Test
fun initSubDepictionListForChildClass() {
Mockito.`when`(okHttpJsonApiClient?.getChildQIDs(ArgumentMatchers.anyString())).thenReturn(testObservable)
subDepictionListPresenter?.initSubDepictionList("Q9394", false)
testScheduler?.triggerActions()
verify(view)?.onSuccess(depictedItems)
}
}

View file

@ -0,0 +1,68 @@
package fr.free.nrw.commons.explore.depictions
import org.mockito.Mockito.verify
import fr.free.nrw.commons.explore.recentsearches.RecentSearchesDao
import fr.free.nrw.commons.kvstore.JsonKvStore
import fr.free.nrw.commons.upload.structure.depictions.DepictedItem
import io.reactivex.Observable
import io.reactivex.Single
import io.reactivex.schedulers.TestScheduler
import org.junit.Before
import org.junit.Test
import org.mockito.ArgumentMatchers
import org.mockito.Mock
import org.mockito.Mockito
import org.mockito.MockitoAnnotations
class SearchDepictionsPresenterTest {
@Mock
internal var view: SearchDepictionsFragmentContract.View? = null
var searchDepictionsFragmentPresenter: SearchDepictionsFragmentPresenter? = null
var testScheduler: TestScheduler? = null
var jsonKvStore: JsonKvStore? = null
//var mediaWikiApi: MediaWikiApi? = null
@Mock
var recentSearchesDao: RecentSearchesDao? = null
@Mock
var depictsClient: DepictsClient? = null
var testObservable: Observable<DepictedItem>? = null
var mediaList: ArrayList<DepictedItem> = ArrayList()
@Before
@Throws(Exception::class)
fun setUp() {
MockitoAnnotations.initMocks(this)
testScheduler = TestScheduler()
val depictedItem: DepictedItem = DepictedItem("label", "description", "url", false, "Q9394")
mediaList.add(depictedItem)
testObservable = Observable.just(depictedItem)
searchDepictionsFragmentPresenter = SearchDepictionsFragmentPresenter(jsonKvStore, recentSearchesDao, depictsClient, testScheduler, testScheduler)
searchDepictionsFragmentPresenter?.onAttachView(view)
}
@Test
fun updateDepictionList() {
Mockito.`when`(depictsClient?.searchForDepictions(ArgumentMatchers.anyString(), ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt())).thenReturn(testObservable)
searchDepictionsFragmentPresenter?.updateDepictionList("rabbit", 25, false)
testScheduler?.triggerActions()
verify(view)?.onSuccess(mediaList)
}
@Test
fun fetchThumbnailForEntityId() {
val singleString: Single<String> = Single.just(String())
Mockito.`when`(depictsClient?.getP18ForItem(ArgumentMatchers.anyString())).thenReturn(singleString)
searchDepictionsFragmentPresenter?.fetchThumbnailForEntityId("Q9394", 0)
testScheduler?.triggerActions()
verify(view)?.onImageUrlFetched("", 0)
}
}

View file

@ -1,6 +1,7 @@
package fr.free.nrw.commons.upload
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.whenever
import fr.free.nrw.commons.category.CategoryItem
import fr.free.nrw.commons.repository.UploadRepository
import fr.free.nrw.commons.upload.categories.CategoriesContract
@ -11,7 +12,6 @@ import org.junit.Before
import org.junit.Test
import org.mockito.ArgumentMatchers
import org.mockito.Mock
import org.mockito.Mockito
import org.mockito.MockitoAnnotations
/**
@ -19,23 +19,19 @@ import org.mockito.MockitoAnnotations
*/
class CategoriesPresenterTest {
@Mock
internal var repository: UploadRepository? = null
internal lateinit var repository: UploadRepository
@Mock
internal var view: CategoriesContract.View? = null
internal lateinit var view: CategoriesContract.View
var categoriesPresenter: CategoriesPresenter? = null
private lateinit var categoriesPresenter: CategoriesPresenter
var testScheduler: TestScheduler? = null
private lateinit var testScheduler: TestScheduler
val categoryItems: ArrayList<CategoryItem> = ArrayList()
private val categoryItems: ArrayList<CategoryItem> = ArrayList()
@Mock
lateinit var categoryItem: CategoryItem
var testObservable: Observable<CategoryItem>? = null
private val imageTitleList = ArrayList<String>()
/**
* initial setup
*/
@ -45,9 +41,8 @@ class CategoriesPresenterTest {
MockitoAnnotations.initMocks(this)
testScheduler = TestScheduler()
categoryItems.add(categoryItem)
testObservable = Observable.just(categoryItem)
categoriesPresenter = CategoriesPresenter(repository, testScheduler, testScheduler)
categoriesPresenter?.onAttachView(view)
categoriesPresenter.onAttachView(view)
}
/**
@ -55,16 +50,16 @@ class CategoriesPresenterTest {
*/
@Test
fun searchForCategoriesTest() {
Mockito.`when`(repository?.sortBySimilarity(ArgumentMatchers.anyString())).thenReturn(Comparator<CategoryItem> { _, _ -> 1 })
Mockito.`when`(repository?.selectedCategories).thenReturn(categoryItems)
Mockito.`when`(repository?.searchAll(ArgumentMatchers.anyString(), ArgumentMatchers.anyList())).thenReturn(Observable.empty())
categoriesPresenter?.searchForCategories("test")
verify(view)?.showProgress(true)
verify(view)?.showError(null)
verify(view)?.setCategories(null)
testScheduler?.triggerActions()
verify(view)?.setCategories(categoryItems)
verify(view)?.showProgress(false)
whenever(repository.sortBySimilarity(ArgumentMatchers.anyString())).thenReturn(Comparator<CategoryItem> { _, _ -> 1 })
whenever(repository.selectedCategories).thenReturn(categoryItems)
whenever(repository.searchAll(ArgumentMatchers.anyString(), ArgumentMatchers.anyList())).thenReturn(Observable.empty())
categoriesPresenter.searchForCategories("test")
verify(view).showProgress(true)
verify(view).showError(null)
verify(view).setCategories(null)
testScheduler.triggerActions()
verify(view).setCategories(categoryItems)
verify(view).showProgress(false)
}
/**
@ -72,10 +67,10 @@ class CategoriesPresenterTest {
*/
@Test
fun verifyCategoriesTest() {
Mockito.`when`(repository?.selectedCategories).thenReturn(categoryItems)
categoriesPresenter?.verifyCategories()
verify(repository)?.setSelectedCategories(ArgumentMatchers.anyList())
verify(view)?.goToNextScreen()
whenever(repository.selectedCategories).thenReturn(categoryItems)
categoriesPresenter.verifyCategories()
verify(repository).setSelectedCategories(ArgumentMatchers.anyList())
verify(view).goToNextScreen()
}
/**
@ -83,7 +78,7 @@ class CategoriesPresenterTest {
*/
@Test
fun onCategoryItemClickedTest() {
categoriesPresenter?.onCategoryItemClicked(categoryItem)
verify(repository)?.onCategoryClicked(categoryItem)
categoriesPresenter.onCategoryItemClicked(categoryItem)
verify(repository).onCategoryClicked(categoryItem)
}
}
}

View file

@ -0,0 +1,121 @@
package fr.free.nrw.commons.upload
import com.nhaarman.mockitokotlin2.whenever
import fr.free.nrw.commons.category.CategoryItem
import fr.free.nrw.commons.repository.UploadRepository
import fr.free.nrw.commons.upload.depicts.DepictsContract
import fr.free.nrw.commons.upload.depicts.DepictsFragment
import fr.free.nrw.commons.upload.depicts.DepictsPresenter
import fr.free.nrw.commons.upload.structure.depictions.DepictedItem
import io.reactivex.Observable
import io.reactivex.schedulers.TestScheduler
import org.junit.Before
import org.junit.Test
import org.mockito.ArgumentMatchers
import org.mockito.Mock
import org.mockito.Mockito.verify
import org.mockito.MockitoAnnotations
class DepictsPresenterTest {
@Mock
internal lateinit var repository: UploadRepository
@Mock
internal lateinit var view: DepictsContract.View
private lateinit var depictsPresenter: DepictsPresenter
private lateinit var depictsFragment: DepictsFragment
private lateinit var testScheduler: TestScheduler
private val depictedItems: ArrayList<DepictedItem> = ArrayList()
@Mock
lateinit var depictedItem: DepictedItem
/**
* initial setup
*/
@Before
@Throws(Exception::class)
fun setUp() {
MockitoAnnotations.initMocks(this)
testScheduler = TestScheduler()
depictedItem = DepictedItem("label", "desc", "", false, "entityId")
depictedItems.add(depictedItem)
depictsPresenter = DepictsPresenter(repository, testScheduler, testScheduler, null)
depictsFragment = DepictsFragment()
depictsPresenter.onAttachView(view)
}
@Test
fun searchEnglishDepictionsTest() {
whenever(repository.sortBySimilarity(ArgumentMatchers.anyString())).thenReturn(Comparator<CategoryItem> { _, _ -> 1 })
whenever(repository.selectedDepictions).thenReturn(depictedItems)
whenever(repository.searchAllEntities(ArgumentMatchers.anyString())).thenReturn(Observable.empty())
depictsPresenter.searchForDepictions("test")
verify(view).showProgress(true)
verify(view).setDepictsList(null)
testScheduler.triggerActions()
verify(view).showProgress(false)
}
@Test
fun searchOtherLanguageDepictions() {
whenever(repository.sortBySimilarity(ArgumentMatchers.anyString())).thenReturn(Comparator<CategoryItem> { _, _ -> 1 })
whenever(repository.selectedDepictions).thenReturn(depictedItems)
whenever(repository.searchAllEntities(ArgumentMatchers.anyString())).thenReturn(Observable.empty())
depictsPresenter.searchForDepictions("वी")
verify(view).showProgress(true)
verify(view).setDepictsList(null)
testScheduler.triggerActions()
verify(view).showProgress(false)
}
@Test
fun searchForNonExistingDepictions() {
whenever(repository.sortBySimilarity(ArgumentMatchers.anyString())).thenReturn(Comparator<CategoryItem> { _, _ -> 1 })
whenever(repository.selectedDepictions).thenReturn(depictedItems)
whenever(repository.searchAllEntities(ArgumentMatchers.anyString())).thenReturn(Observable.empty())
depictsPresenter.searchForDepictions("******")
verify(view).showProgress(true)
verify(view).setDepictsList(null)
testScheduler.triggerActions()
verify(view).setDepictsList(null)
verify(view).showProgress(false)
}
@Test
fun setSingleDepiction() {
whenever(repository.sortBySimilarity(ArgumentMatchers.anyString())).thenReturn(Comparator<CategoryItem> { _, _ -> 1 })
whenever(repository.selectedDepictions).thenReturn(depictedItems)
whenever(repository.searchAllEntities(ArgumentMatchers.anyString())).thenReturn(Observable.empty())
depictsPresenter.onDepictItemClicked(depictedItem)
depictsPresenter.verifyDepictions()
verify(view).goToNextScreen()
}
@Test
fun setMultipleDepictions() {
whenever(repository.sortBySimilarity(ArgumentMatchers.anyString())).thenReturn(Comparator<CategoryItem> { _, _ -> 1 })
whenever(repository.selectedDepictions).thenReturn(depictedItems)
whenever(repository.searchAllEntities(ArgumentMatchers.anyString())).thenReturn(Observable.empty())
depictsPresenter.onDepictItemClicked(depictedItem)
val depictedItem2 = DepictedItem("label2", "desc2", "", false, "entityid2")
depictsPresenter.onDepictItemClicked(depictedItem2)
depictsPresenter.verifyDepictions()
verify(view).goToNextScreen()
}
@Test
fun `on Search Exception Show Error And Stop Progress`() {
whenever(repository.searchAllEntities(ArgumentMatchers.anyString()))
.thenReturn(Observable.error(Exception()))
depictsPresenter.searchForDepictions("******")
testScheduler.triggerActions()
verify(view).showError(true)
verify(view).showProgress(false)
}
}

View file

@ -6,7 +6,7 @@ import org.junit.Test
class GpsCategoryModelTest {
private lateinit var testObject : GpsCategoryModel
private lateinit var testObject: GpsCategoryModel
@Before
fun setUp() {
@ -21,7 +21,7 @@ class GpsCategoryModelTest {
@Test
fun addingCategoriesToTheModel() {
testObject.add("one")
testObject.categoryList = listOf("one")
assertTrue(testObject.gpsCatExists)
assertFalse(testObject.categoryList.isEmpty())
assertEquals(listOf("one"), testObject.categoryList)
@ -29,14 +29,13 @@ class GpsCategoryModelTest {
@Test
fun duplicatesAreIgnored() {
testObject.add("one")
testObject.add("one")
testObject.categoryList = listOf("one", "one")
assertEquals(listOf("one"), testObject.categoryList)
}
@Test
fun modelProtectsAgainstExternalModification() {
testObject.add("one")
testObject.categoryList = listOf("one")
val list = testObject.categoryList
list.add("two")
@ -46,19 +45,19 @@ class GpsCategoryModelTest {
@Test
fun clearingTheModel() {
testObject.add("one")
testObject.categoryList = listOf("one")
testObject.clear()
assertFalse(testObject.gpsCatExists)
assertTrue(testObject.categoryList.isEmpty())
testObject.add("two")
testObject.categoryList = listOf("two")
assertEquals(listOf("two"), testObject.categoryList)
}
@Test
fun settingTheListHandlesNull() {
testObject.add("one")
testObject.categoryList = listOf("one")
testObject.categoryList = null
@ -68,10 +67,10 @@ class GpsCategoryModelTest {
@Test
fun settingTheListOverwritesExistingValues() {
testObject.add("one")
testObject.categoryList = listOf("one")
testObject.categoryList = listOf("two")
assertEquals(listOf("two"), testObject.categoryList)
}
}
}

View file

@ -41,18 +41,18 @@ class u {
MockitoAnnotations.initMocks(this)
val mediaUri = mock(Uri::class.java)
val mockPlace = mock(Place::class.java)
val mockTitle = mock(Title::class.java)
val mockTitle = mock(List::class.java)
`when`(mockPlace.wikiDataEntityId).thenReturn("Q1")
`when`(mockPlace.getLocation()).thenReturn(mock(LatLng::class.java))
`when`(mediaUri.path).thenReturn("filePath")
`when`(mockTitle.isEmpty).thenReturn(false)
`when`(mockTitle.isSet).thenReturn(true)
/*`when`(mockTitle.isEmpty).thenReturn(false)
`when`(mockTitle.isSet).thenReturn(true)*/
`when`(uploadItem.mediaUri).thenReturn(mediaUri)
`when`(uploadItem.imageQuality).thenReturn(ImageUtils.IMAGE_WAIT)
`when`(uploadItem.title).thenReturn(mockTitle)
`when`(uploadItem.uploadMediaDetails).thenReturn(mockTitle as MutableList<UploadMediaDetail>?)
`when`(uploadItem.place).thenReturn(mockPlace)
`when`(uploadItem.fileName).thenReturn("File:jpg")

View file

@ -16,8 +16,10 @@ import org.junit.Test
import org.mockito.ArgumentMatchers
import org.mockito.ArgumentMatchers.eq
import org.mockito.Mock
import org.mockito.Mockito
import org.mockito.Mockito.verify
import org.mockito.MockitoAnnotations
import java.util.*
/**
@ -42,10 +44,7 @@ class UploadMediaPresenterTest {
private lateinit var uploadItem: UploadModel.UploadItem
@Mock
private lateinit var title: Title
@Mock
private lateinit var descriptions: List<Description>
private lateinit var uploadMediaDetails: List<UploadMediaDetail>
private lateinit var testObservableUploadItem: Observable<UploadModel.UploadItem>
private lateinit var testSingleImageResult: Single<Int>
@ -75,11 +74,10 @@ class UploadMediaPresenterTest {
repository.preProcessImage(
ArgumentMatchers.any(UploadableFile::class.java),
ArgumentMatchers.any(Place::class.java),
ArgumentMatchers.anyString(),
ArgumentMatchers.any(UploadMediaPresenter::class.java)
)
).thenReturn(testObservableUploadItem)
uploadMediaPresenter.receiveImage(uploadableFile, ArgumentMatchers.anyString(), place)
uploadMediaPresenter.receiveImage(uploadableFile, place)
verify(view).showProgress(true)
testScheduler.triggerActions()
verify(view).onImageProcessed(
@ -116,17 +114,51 @@ class UploadMediaPresenterTest {
uploadMediaPresenter.handleImageResult(FILE_NAME_EXISTS)
verify(view).showDuplicatePicturePopup()
//Empty Title test
uploadMediaPresenter.handleImageResult(EMPTY_TITLE)
//Empty Caption test
uploadMediaPresenter.handleImageResult(EMPTY_CAPTION)
verify(view).showMessage(ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt())
//Bad Picture test
//Empty Title test
//Empty Caption test
uploadMediaPresenter.handleImageResult(-7)
verify(view).showBadImagePopup(ArgumentMatchers.anyInt())
verify(view)?.showBadImagePopup(ArgumentMatchers.anyInt())
}
@Test
fun addSingleCaption() {
val uploadMediaDetail = UploadMediaDetail()
uploadMediaDetail.captionText = "added caption"
uploadMediaDetail.languageCode = "en"
val uploadMediaDetailList: ArrayList<UploadMediaDetail> = ArrayList()
uploadMediaDetailList.add(uploadMediaDetail)
uploadItem.setMediaDetails(uploadMediaDetailList)
Mockito.`when`(repository.getImageQuality(uploadItem)).then {
verify(view).showProgress(true)
testScheduler.triggerActions()
verify(view).showProgress(true)
verify(view).onImageValidationSuccess()
uploadMediaPresenter.setUploadItem(0, uploadItem)
}
}
@Test
fun addMultipleCaptions() {
val uploadMediaDetail = UploadMediaDetail()
uploadMediaDetail.captionText = "added caption"
uploadMediaDetail.languageCode = "en"
uploadMediaDetail.captionText = "added caption"
uploadMediaDetail.languageCode = "eo"
uploadItem.setMediaDetails(Collections.singletonList(uploadMediaDetail))
Mockito.`when`(repository.getImageQuality(uploadItem)).then {
verify(view).showProgress(true)
testScheduler.triggerActions()
verify(view).showProgress(true)
verify(view).onImageValidationSuccess()
uploadMediaPresenter.setUploadItem(0, uploadItem)
}
}
/**
* Test fetch previous image title when there was one
*/
@ -134,12 +166,10 @@ class UploadMediaPresenterTest {
fun fetchPreviousImageAndTitleTestPositive() {
whenever(repository.getPreviousUploadItem(ArgumentMatchers.anyInt()))
.thenReturn(uploadItem)
whenever(uploadItem.descriptions).thenReturn(descriptions)
whenever(uploadItem.title).thenReturn(title)
whenever(title.getTitleText()).thenReturn(ArgumentMatchers.anyString())
whenever(uploadItem.uploadMediaDetails).thenReturn(uploadMediaDetails)
uploadMediaPresenter.fetchPreviousTitleAndDescription(0)
verify(view).setTitleAndDescription(ArgumentMatchers.anyString(), ArgumentMatchers.any())
verify(view).setCaptionsAndDescriptions(ArgumentMatchers.any())
}
/**

View file

@ -1,12 +1,12 @@
package fr.free.nrw.commons.wikidata
import com.nhaarman.mockitokotlin2.mock
import fr.free.nrw.commons.wikidata.model.AddEditTagResponse
import fr.free.nrw.commons.wikidata.model.WbCreateClaimResponse
import io.reactivex.Observable
import okhttp3.RequestBody
import org.junit.Before
import org.junit.Test
import org.mockito.ArgumentMatchers.*
import org.mockito.ArgumentMatchers.any
import org.mockito.ArgumentMatchers.anyString
import org.mockito.InjectMocks
import org.mockito.Mock
import org.mockito.Mockito.`when`
@ -32,25 +32,29 @@ class WikidataClientTest {
`when`(mwQueryResult!!.csrfToken()).thenReturn("test_token")
`when`(mwQueryResponse.query()).thenReturn(mwQueryResult)
`when`(wikidataInterface!!.getCsrfToken())
.thenReturn(Observable.just(mwQueryResponse))
.thenReturn(Observable.just(mwQueryResponse))
}
@Test
fun createClaim() {
`when`(wikidataInterface!!.postCreateClaim(any(RequestBody::class.java),
any(RequestBody::class.java),
any(RequestBody::class.java),
any(RequestBody::class.java),
any(RequestBody::class.java),
any(RequestBody::class.java)))
.thenReturn(Observable.just(mock(WbCreateClaimResponse::class.java)))
wikidataClient!!.createClaim("Q1", "test.jpg")
`when`(
wikidataInterface!!.postCreateClaim(
any(),
any(),
any(),
any(),
any(),
any()
)
)
.thenReturn(Observable.just(mock()))
wikidataClient!!.createImageClaim(mock(), "test.jpg")
}
@Test
fun addEditTag() {
`when`(wikidataInterface!!.addEditTag(anyString(), anyString(), anyString(), anyString()))
.thenReturn(Observable.just(mock(AddEditTagResponse::class.java)))
.thenReturn(Observable.just(mock(AddEditTagResponse::class.java)))
wikidataClient!!.addEditTag(1L, "test", "test")
}
}
}

View file

@ -1,13 +1,18 @@
package fr.free.nrw.commons.wikidata
import android.content.Context
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.verifyZeroInteractions
import com.nhaarman.mockitokotlin2.whenever
import fr.free.nrw.commons.kvstore.JsonKvStore
import fr.free.nrw.commons.upload.UploadResult
import fr.free.nrw.commons.upload.WikidataPlace
import fr.free.nrw.commons.wikidata.model.AddEditTagResponse
import io.reactivex.Observable
import org.junit.Before
import org.junit.Test
import org.mockito.ArgumentMatchers
import org.mockito.ArgumentMatchers.any
import org.mockito.ArgumentMatchers.anyString
import org.mockito.InjectMocks
import org.mockito.Mock
import org.mockito.Mockito.*
@ -15,16 +20,19 @@ import org.mockito.MockitoAnnotations
class WikidataEditServiceTest {
@Mock
internal var context: Context? = null
internal lateinit var context: Context
@Mock
internal var wikidataEditListener: WikidataEditListener? = null
internal lateinit var directKvStore: JsonKvStore
@Mock
internal var directKvStore: JsonKvStore? = null
internal lateinit var wikidataClient: WikidataClient
@Mock
internal var wikidataClient: WikidataClient? = null
internal lateinit var wikibaseClient: WikiBaseClient
@InjectMocks
var wikidataEditService: WikidataEditService? = null
lateinit var wikidataEditService: WikidataEditService
@Before
@Throws(Exception::class)
@ -32,42 +40,27 @@ class WikidataEditServiceTest {
MockitoAnnotations.initMocks(this)
}
@Test
fun noClaimsWhenEntityIdIsNull() {
wikidataEditService!!.createClaimWithLogging(null, null,"Test.jpg","")
verifyZeroInteractions(wikidataClient!!)
}
@Test
fun noClaimsWhenFileNameIsNull() {
wikidataEditService!!.createClaimWithLogging("Q1", "Test", null,"")
verifyZeroInteractions(wikidataClient!!)
}
@Test
fun noClaimsWhenP18IsNotEmpty() {
wikidataEditService!!.createClaimWithLogging("Q1", "Test","Test.jpg","Previous.jpg")
verifyZeroInteractions(wikidataClient!!)
}
@Test
fun noClaimsWhenLocationIsNotCorrect() {
`when`(directKvStore!!.getBoolean("Picture_Has_Correct_Location", true))
.thenReturn(false)
wikidataEditService!!.createClaimWithLogging("Q1", "","Test.jpg","")
verifyZeroInteractions(wikidataClient!!)
whenever(directKvStore.getBoolean("Picture_Has_Correct_Location", true))
.thenReturn(false)
wikidataEditService.createImageClaim(mock(), mock())
verifyZeroInteractions(wikidataClient)
}
@Test
fun createClaimWithLogging() {
`when`(directKvStore!!.getBoolean("Picture_Has_Correct_Location", true))
.thenReturn(true)
`when`(wikidataClient!!.createClaim(ArgumentMatchers.anyString(), ArgumentMatchers.anyString()))
.thenReturn(Observable.just(1L))
`when`(wikidataClient!!.addEditTag(anyLong(), ArgumentMatchers.anyString(), ArgumentMatchers.anyString()))
.thenReturn(Observable.just(mock(AddEditTagResponse::class.java)))
wikidataEditService!!.createClaimWithLogging("Q1", "Test","Test.jpg","")
verify(wikidataClient!!, times(1))
.createClaim(ArgumentMatchers.anyString(), ArgumentMatchers.anyString())
fun createImageClaim() {
whenever(directKvStore.getBoolean("Picture_Has_Correct_Location", true))
.thenReturn(true)
whenever(wikidataClient.createImageClaim(any(), any()))
.thenReturn(Observable.just(1L))
whenever(wikidataClient.addEditTag(anyLong(), anyString(), anyString()))
.thenReturn(Observable.just(mock(AddEditTagResponse::class.java)))
whenever(wikibaseClient.getFileEntityId(any())).thenReturn(Observable.just(1L))
val wikidataPlace:WikidataPlace = mock()
val uploadResult = mock<UploadResult>()
whenever(uploadResult.filename).thenReturn("file")
wikidataEditService.createImageClaim(wikidataPlace, uploadResult)
verify(wikidataClient, times(1)).createImageClaim(wikidataPlace, """"file"""")
}
}
}