Skip to content

Commit

Permalink
Merge pull request #2 from Husseinhj/main
Browse files Browse the repository at this point in the history
Supported include and exclude queries
  • Loading branch information
javaherisaber authored Mar 19, 2023
2 parents 7dd9cbd + 1efca59 commit 0bcd9f7
Show file tree
Hide file tree
Showing 13 changed files with 287 additions and 36 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
# 2.0.0
- Support for include and exclude json path based on query params (Thanks to @[Husseinhj](https://github.com/Husseinhj))

# 1.1.0
- Escape closing curly brace in regex to support in android
- Add support to retrofit HTTP annotation
Expand Down
20 changes: 19 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,24 @@ interface Api {
@Query("page") page: Int,
@Query("limit") limit: Int
): Call<List<Picsum>>

// if you want to filter through query params
@Mock("picsum_recent.json", excludeQueries = ["type=favorites"])
@GET("list")
fun getRecentPicsums(
@Query("type") type: String,
@Query("page") page: Int,
@Query("limit") limit: Int
): Call<List<Picsum>>

// if you want to filter through query params
@Mock("picsum_favorites.json", includeQueries = ["type=favorites"])
@GET("list")
fun getFavoritePicsums(
@Query("type") type: String,
@Query("page") page: Int,
@Query("limit") limit: Int
): Call<List<Picsum>>
}
```

Expand All @@ -92,7 +110,7 @@ class RemoteDataSource(private val context: Context) {
bodyFactory = { input -> context.resources.assets.open(input) }, // read asset file
logger = { tag, message -> Log.d(tag, message) }, // pass logger to log events in logcat
baseUrl = BASE_URL, // base url of your api
requestPathToJsonMap = REQUEST_TO_JSON, // autogenerated constant, just press build button
requestPathToMockPathRule = REQUEST_TO_JSON, // autogenerated constant, just press build button
mockFilesPath = MOCK_FILES_PATH, // path to json files
mockFitEnable = true, // master setting to enable or disable mocking
apiEnableMock = true, // enable or disable mock when there are includes and excludes configs
Expand Down
2 changes: 1 addition & 1 deletion app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ dependencies {
implementation "com.squareup.retrofit2:retrofit:$versions.retrofit"
implementation "com.squareup.retrofit2:converter-gson:$versions.retrofit"
implementation "com.github.bumptech.glide:glide:$versions.glide"

testImplementation "junit:junit:$versions.junit"
androidTestImplementation "androidx.test.espresso:espresso-core:$versions.espresso"

Expand Down
146 changes: 146 additions & 0 deletions app/src/main/assets/mock_json/picsum_favorites.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
[
{
"id": "1016",
"author": "Andrew Ridley",
"width": 3844,
"height": 2563,
"url": "https://unsplash.com/photos/_h7aBovKia4",
"download_url": "https://picsum.photos/id/1018/3914/2935"
},
{
"id": "1018",
"author": "Andrew Ridley",
"width": 3914,
"height": 2935,
"url": "https://unsplash.com/photos/Kt5hRENuotI",
"download_url": "https://picsum.photos/id/1018/3914/2935"
},
{
"id": "1019",
"author": "Patrick Fore",
"width": 5472,
"height": 3648,
"url": "https://unsplash.com/photos/V6s1cmE39XM",
"download_url": "https://picsum.photos/id/1019/5472/3648"
},
{
"id": "102",
"author": "Ben Moore",
"width": 4320,
"height": 3240,
"url": "https://unsplash.com/photos/pJILiyPdrXI",
"download_url": "https://picsum.photos/id/102/4320/3240"
},
{
"id": "1020",
"author": "Adam Willoughby-Knox",
"width": 4288,
"height": 2848,
"url": "https://unsplash.com/photos/_snqARKTgoc",
"download_url": "https://picsum.photos/id/1020/4288/2848"
},
{
"id": "1022",
"author": "Vashishtha Jogi",
"width": 6000,
"height": 3376,
"url": "https://unsplash.com/photos/bClr95glx6k",
"download_url": "https://picsum.photos/id/1022/6000/3376"
},
{
"id": "1023",
"author": "William Hook",
"width": 3955,
"height": 2094,
"url": "https://unsplash.com/photos/93Ep1dhTd2s",
"download_url": "https://picsum.photos/id/1023/3955/2094"
},
{
"id": "1024",
"author": "Мартин Тасев",
"width": 1920,
"height": 1280,
"url": "https://unsplash.com/photos/7ALI0RYyq6s",
"download_url": "https://picsum.photos/id/1024/1920/1280"
},
{
"id": "1025",
"author": "Matthew Wiebe",
"width": 4951,
"height": 3301,
"url": "https://unsplash.com/photos/U5rMrSI7Pn4",
"download_url": "https://picsum.photos/id/1025/4951/3301"
},
{
"id": "1018",
"author": "Andrew Ridley",
"width": 3914,
"height": 2935,
"url": "https://unsplash.com/photos/Kt5hRENuotI",
"download_url": "https://picsum.photos/id/1018/3914/2935"
},
{
"id": "1019",
"author": "Patrick Fore",
"width": 5472,
"height": 3648,
"url": "https://unsplash.com/photos/V6s1cmE39XM",
"download_url": "https://picsum.photos/id/1019/5472/3648"
},
{
"id": "102",
"author": "Ben Moore",
"width": 4320,
"height": 3240,
"url": "https://unsplash.com/photos/pJILiyPdrXI",
"download_url": "https://picsum.photos/id/102/4320/3240"
},
{
"id": "1020",
"author": "Adam Willoughby-Knox",
"width": 4288,
"height": 2848,
"url": "https://unsplash.com/photos/_snqARKTgoc",
"download_url": "https://picsum.photos/id/1020/4288/2848"
},
{
"id": "1021",
"author": "Frances Gunn",
"width": 2048,
"height": 1206,
"url": "https://unsplash.com/photos/8BmNurlVR6M",
"download_url": "https://picsum.photos/id/1021/2048/1206"
},
{
"id": "1022",
"author": "Vashishtha Jogi",
"width": 6000,
"height": 3376,
"url": "https://unsplash.com/photos/bClr95glx6k",
"download_url": "https://picsum.photos/id/1022/6000/3376"
},
{
"id": "1023",
"author": "William Hook",
"width": 3955,
"height": 2094,
"url": "https://unsplash.com/photos/93Ep1dhTd2s",
"download_url": "https://picsum.photos/id/1023/3955/2094"
},
{
"id": "1024",
"author": "Мартин Тасев",
"width": 1920,
"height": 1280,
"url": "https://unsplash.com/photos/7ALI0RYyq6s",
"download_url": "https://picsum.photos/id/1024/1920/1280"
},
{
"id": "1025",
"author": "Matthew Wiebe",
"width": 4951,
"height": 3301,
"url": "https://unsplash.com/photos/U5rMrSI7Pn4",
"download_url": "https://picsum.photos/id/1025/4951/3301"
}
]
10 changes: 9 additions & 1 deletion app/src/main/java/ir/logicbase/mockfit/app/Api.kt
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,18 @@ import retrofit2.http.Query

interface Api {

@Mock("picsum_list.json")
@Mock("picsum_list.json", excludeQueries = ["type={#}"])
@GET("list")
fun getListOfPicsums(
@Query("page") page: Int,
@Query("limit") limit: Int
): Call<List<Picsum>>

@Mock("picsum_favorites.json", includeQueries = ["type=favorites"])
@GET("list")
fun getFavoritePicsums(
@Query("type") type: String,
@Query("page") page: Int,
@Query("limit") limit: Int
): Call<List<Picsum>>
}
2 changes: 1 addition & 1 deletion app/src/main/java/ir/logicbase/mockfit/app/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ class MainActivity : AppCompatActivity() {
currentImageIndex = 0
}
executors.networkIO().execute {
dataSource.api().getListOfPicsums(2, 20).enqueue(object : Callback<List<Picsum>> {
dataSource.api().getFavoritePicsums("favorites", 2, 20).enqueue(object : Callback<List<Picsum>> {
override fun onResponse(call: Call<List<Picsum>>, response: Response<List<Picsum>>) {
loadingApi = false
executors.mainThread().execute {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ class RemoteDataSource(private val context: Context, var mockFitEnable: Boolean
bodyFactory = { input -> context.resources.assets.open(input) }, // read asset file
logger = { tag, message -> Log.d(tag, message) }, // pass logger to log events in logcat
baseUrl = BASE_URL, // base url of your api
requestPathToJsonMap = REQUEST_TO_JSON, // autogenerated constant, just press build button
requestPathToMockPathRule = REQUEST_TO_JSON, // autogenerated constant, just press build button
mockFilesPath = MOCK_FILES_PATH, // path to json files
mockFitEnable = mockFitEnable, // master setting to enable or disable mocking
apiEnableMock = true, // enable or disable mock when there are includes and excludes configs
Expand Down
7 changes: 6 additions & 1 deletion common/src/main/java/ir/logicbase/mockfit/Mock.kt
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,15 @@ package ir.logicbase.mockfit
* Annotation meta to mark retrofit endpoints
*
* @property response path to mock file
* @property includeQueries are the queries to separating same paths with different responses based on query values.
* @property excludeQueries are the queries to separating same paths with different responses based on query values.
* For example: ```["limit={#}"]``` or ```["limit"]``` for just including keys not value. For separate them with value you have to pass value as well like ```["limit=20"]```
*/
@MustBeDocumented
@Target(AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.SOURCE)
public annotation class Mock(
val response: String
val response: String,
val includeQueries: Array<String> = [],
val excludeQueries: Array<String> = [],
)
33 changes: 33 additions & 0 deletions common/src/main/java/ir/logicbase/mockfit/MockPathRule.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package ir.logicbase.mockfit

public data class MockPathRule(
val method: String,
val route: String,
val responseFile: String,
val includeQueries: Array<String> = arrayOf(),
val excludeQueries: Array<String> = arrayOf(),
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false

other as MockPathRule

if (method != other.method) return false
if (route != other.route) return false
if (responseFile != other.responseFile) return false
if (!includeQueries.contentEquals(other.includeQueries)) return false
if (!excludeQueries.contentEquals(other.excludeQueries)) return false

return true
}

override fun hashCode(): Int {
var result = method.hashCode()
result = 31 * result + route.hashCode()
result = 31 * result + responseFile.hashCode()
result = 31 * result + includeQueries.contentHashCode()
result = 31 * result + excludeQueries.contentHashCode()
return result
}
}
4 changes: 2 additions & 2 deletions common/src/main/java/ir/logicbase/mockfit/StringExtensions.kt
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,11 @@ package ir.logicbase.mockfit
public fun String.removeQueryParams(): String = this.replace("\\?.*".toRegex(), "")

/**
* Replace resource path from given url, for example in this url : `users/2/form`
* Replace resource path from given url, for example in this url : `users/2/form` or `user/cb7d8a83-0b25-4cca-911b-49a1974f1193/form`
*
* result will be `users/{#}/form`
*/
public fun String.replaceUrlDynamicPath(): String = this.replace("\\b\\d+((,\\d)+)?".toRegex(), "{#}")
public fun String.replaceUrlDynamicPath(): String = this.replace("[\\da-f]{8}-[\\da-f]{4}-4[\\da-f]{3}-[89ab][\\da-f]{3}-[\\da-f]{12}|\\b\\d+((,\\d)+)?".toRegex(), "{#}")

/**
* Replace resource path from given url, for example in this url : `users/{id}/form`
Expand Down
44 changes: 25 additions & 19 deletions compiler/src/main/java/ir/logicbase/mockfit/MockFitProcessor.kt
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import javax.lang.model.element.TypeElement
@AutoService(Processor::class)
internal class MockFitProcessor : AbstractProcessor() {

private val requestToJsonPath = hashMapOf<String, String>()
private val requestToJsonPath = mutableListOf<MockPathRule>()

override fun getSupportedAnnotationTypes(): MutableSet<String> = mutableSetOf(
Mock::class.java.name,
Expand All @@ -40,34 +40,39 @@ internal class MockFitProcessor : AbstractProcessor() {
}

private fun processMock(element: Element) {
val jsonPath = (element.getAnnotation(Mock::class.java)).response
var requestMethodCount = 0
val mockAnnotation = element.getAnnotation(Mock::class.java)
val includeQuery = mockAnnotation.includeQueries
val excludeQuery = mockAnnotation.excludeQueries
val jsonPath = mockAnnotation.response

element.getAnnotation(GET::class.java)?.let {
requestToJsonPath["[GET] ${it.value}"] = jsonPath
requestToJsonPath += MockPathRule("GET", it.value, jsonPath, includeQuery, excludeQuery)
requestMethodCount++
}
element.getAnnotation(POST::class.java)?.let {
requestToJsonPath["[POST] ${it.value}"] = jsonPath
requestToJsonPath += MockPathRule("POST", it.value, jsonPath, includeQuery, excludeQuery)
requestMethodCount++
}
element.getAnnotation(PATCH::class.java)?.let {
requestToJsonPath["[PATCH] ${it.value}"] = jsonPath
requestToJsonPath += MockPathRule("PATCH", it.value, jsonPath, includeQuery, excludeQuery)
requestMethodCount++
}
element.getAnnotation(PUT::class.java)?.let {
requestToJsonPath["[PUT] ${it.value}"] = jsonPath
requestToJsonPath += MockPathRule("PUT", it.value, jsonPath, includeQuery, excludeQuery)
requestMethodCount++
}
element.getAnnotation(HEAD::class.java)?.let {
requestToJsonPath["[HEAD] ${it.value}"] = jsonPath
requestToJsonPath += MockPathRule("HEAD", it.value, jsonPath, includeQuery, excludeQuery)
}
element.getAnnotation(DELETE::class.java)?.let {
requestToJsonPath["[DELETE] ${it.value}"] = jsonPath
requestToJsonPath += MockPathRule("DELETE", it.value, jsonPath, includeQuery, excludeQuery)
requestMethodCount++
}
element.getAnnotation(HTTP::class.java)?.let {
requestToJsonPath["[${it.method}] ${it.path}"] = jsonPath
requestToJsonPath += MockPathRule(it.method, it.path, jsonPath, includeQuery, excludeQuery)
}

if (requestMethodCount > 1) {
val packageName = processingEnv.elementUtils.getPackageOf(element).toString()
val className = element.enclosingElement.simpleName
Expand All @@ -85,13 +90,13 @@ internal class MockFitProcessor : AbstractProcessor() {
classBuilder.addProperty(
PropertySpec.builder(
"REQUEST_TO_JSON",
Map::class.asClassName().parameterizedBy(
String::class.asClassName(), String::class.asClassName()
Array::class.asClassName().parameterizedBy(
MockPathRule::class.asTypeName()
)
).initializer(
"""
|mapOf(
|${generateRequestToJsonPathSource()}
|arrayOf(
| ${generateRequestToJsonPathSource()}
|)
""".trimMargin()
).addAnnotation(JvmField::class.java)
Expand All @@ -103,14 +108,15 @@ internal class MockFitProcessor : AbstractProcessor() {
}

private fun generateRequestToJsonPathSource(): String {
var result = ""
for ((request, jsonPath) in requestToJsonPath) {
val className = MockPathRule::class.java.name
return requestToJsonPath.joinToString(",") { rule ->
// replace path identifier with # so that interceptor can operate it
val requestPath = request.replaceEndpointDynamicPath()
result += """"$requestPath" to "$jsonPath","""
result += '\n'
val requestPath = rule.route.replaceEndpointDynamicPath()
val includeQueries = """arrayOf(${rule.includeQueries.joinToString(",") { """"$it""""}})"""
val excludeQueries = """arrayOf(${rule.excludeQueries.joinToString(","){ """"$it""""}})"""

"""${className}("${rule.method}", "$requestPath", "${rule.responseFile}", $includeQueries, $excludeQueries)"""
}
return result.dropLast(2) // drop last comma and newline
}

companion object {
Expand Down
Loading

0 comments on commit 0bcd9f7

Please sign in to comment.