Code Monkey home page Code Monkey logo

barricade2's Introduction

Barricade2 GitHub tag (latest by date)

Barricade is a library for Android apps that allows you to get responses to API requests locally by running a local server. Barricade will intercept your API calls using an OkHttp Network Interceptor and can provide a local response from a local file.

It also supports multiple responses per request, unlike other local server implementations and presents the user with an UI for modifying which response to return for a request. at runtime.

When to use

  • During development, Barricade is useful for easily exercising all edge cases and responses of a feature without waiting for those server devs to finish implementing the APIs

  • For integration and system tests, Barricade allows you to easily toggle through each predefined response for a request to cover every possible edge cases

  • To build a demo mode so that users can explore the app with dummy data

How is it different from OkHttp's MockWebServer?

  • MockWebServer is queue-based which is ok for simple apps, but hard to use predictably when you have multiple calls getting fired at the same time. Barricade is call-specific so it'll always return the response you configure irrespective of the number of requests your app is making.

  • Barricade gives you a UI to easily change the configuration whenever you want so even your QA can test different scenarios easily,

  • Barricade can be used outside of tests. For example, you can easily build a full-fledged demo mode to allow users to try out the app without creating an account.

  • Barricade allows you to specify responses in files instead of plain strings which keeps your codebase clean.

Adding Barricade to your project

Include the following dependencies in your app's build.gradle (the latest version is GitHub tag (latest by date)) :

def barricadeVersion = "0.0.4" // Get the latest version from tags
dependencies {
    implementation ("com.mutualmobile:barricade2:$barricadeVersion")
    implementation ("com.mutualmobile:barricade-annotations:$barricadeVersion")
    ksp ("com.mutualmobile:barricade-compiler:$barricadeVersion")
}

Since Barricade2 internally uses Kotlin Symbol Processing (KSP) and generates Config classes for us, therefore we also need to include the sourceSets it generates the files into in order to make them visible to our codebase. We can do that by including the following inside the android block in the app-level build gradle (or wherever we've put the dependencies in the step above) i.e.

android {
    ...
    sourceSets {
        debug {
            kotlin { srcDir(file("build/generated/ksp/debug/kotlin")) }
        }
        release {
            kotlin { srcDir(file("build/generated/ksp/release/kotlin")) }
        }
    }
}

How to use

  1. Install Barricade in your Application class' #onCreate()
override fun onCreate() {
      super.onCreate()
      Barricade.Builder(this, BarricadeConfig.getInstance())
          .enableShakeToStart(this)
          .install()
          ...
  }
  1. Add your API response files to assets/barricade/ for each type of response (success, invalid, error etc). You should consider creating subdirectories for each endpoint and putting the responses in them to organise them properly.

  2. In your Retrofit API interface, for the required methods, add annotation @Barricade which mentions which endpoint to intercept and the possible responses using @Response annotation.

Example -

@GET("/users/{user}/repos")
@Barricade(endpoint = "repos", responses = {
    @Response(fileName = "success.json", isDefault = true),
    @Response(fileName = "failure.json", statusCode = 500)
}) fun getUserRepositories(@Path("user") String userId): Single<ReposResponse>

To configure multiple / non-JSON responses -

@GET("/users/{user}/repos")
@Barricade(endpoint = "repos", responses = {
    @Response(fileName = "success.xml", type = "application/xml", isDefault = true),
    @Response(fileName = "failure.xml", type = "application/xml", statusCode = 500)
}) fun getUserRepositories(@Path("user") String userId): Single<ReposResponse>

Default type is "application/json"

  1. Add BarricadeInterceptor to your OkHttpClient
var okHttpClient = OkHttpClient.Builder()
    .addInterceptor(BarricadeInterceptor())
    ...
    .build()

Enable/ Disable Barricade

Barricade can be enabled or disabled at runtime using Barricade.getInstance().setEnabled(true/false)

Change Settings

Barricade allows you to change the response time and the required response for a request at runtime.

  • Open Barricade settings by shaking the device
  • Change the response time in milliseconds by clicking on the timer on top right
  • To change the required response for a request, click on the request from list and then select the response you want from the list of responses. This list is populated from the response files in assets folder

You can also change the above settings programmatically which can be helpful for testing -

Barricade.getInstance()
    .setDelay(100)
    .withResponse(BarricadeConfig.Endpoints.REPOS, BarricadeConfig.Responses.Repos.GetReposSuccess)
  • withResponse() changes the response of the endpoint passed in the first parameter.

Note: Using the above technique will also save the settings and apply to other responses as well, not just the next response, until changed.

Migration from Barricade1

If you're planning to migrate to Barricade2 from the older version(s) of Barricade, you might want to take into consideration that Barricade2 has completely been rewritten in Kotlin (which might not be feasible for Java-only projects) and has its own set of dependencies. Therefore, you will have to include the new dependencies and remove the old ones from your project now (again, only if you plan to or already use Kotlin).

License

Copyright 2022 Mutual Mobile

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

barricade2's People

Contributors

shubhamsinghmutualmobile avatar pushpalroymm avatar swap-musale avatar zeeshanshabbir avatar dependabot[bot] avatar

Stargazers

J!nl!n avatar Scott Birksted avatar Luke Wong avatar YugeshJainMM avatar Giridhara Sai Pavan Kumar Gurram avatar  avatar prudhvi reddy avatar Guadalupe Orlando avatar  avatar

Watchers

James Cloos avatar  avatar  avatar  avatar

barricade2's Issues

Feature request: Support for dynamic endpoints

often times endpoints are not static

say for URL : /users/{userId}

probably we can add support for wildcard patterns, that way we any endpoint after /users/ should be able to take mock data

Barricade( endpoint = /users/*, responses = [])

is this something we want to with barricade ?

BarricadeProcessor only generates 1 endpoint with all response

I was trying to create respones for numbers of endpoints but barricade was generate response for random endpoint only.

On further investigating, I noticed the BarricadeProcessor file is only designed for the random endpoint. Is this intentional or bug?

file writeToFile "package $PACKAGE_NAME\n\n"
        file writeToFile "class $GENERATED_FILE_NAME private constructor() : $PACKAGE_NAME.IBarricadeConfig {\n\n"

        file writeToFile "\tobject Endpoints {\n"
        file writeToFile "\t\tconst val RANDOM = \"random\"\n"
        file writeToFile "\t}\n\n"
        file writeToFile "\tobject Responses {\n"
        file writeToFile "\t\tconst val SUCCESS = 0\n"
        file writeToFile "\t\tconst val FAILURE = 1\n"
        file writeToFile "\t}\n\n"

        file writeToFile "\tcompanion object {"
        file writeToFile "\n\t\tprivate var instance: BarricadeConfig? = null\n"
        file writeToFile "\t\tfun getInstance(): BarricadeConfig {\n"
        file writeToFile "\t\t\tinstance?.let { nnInstance ->\n"
        file writeToFile "\t\t\t\treturn nnInstance\n"
        file writeToFile "\t\t\t} ?: run {\n"
        file writeToFile "\t\t\t\tinstance = BarricadeConfig()\n"
        file writeToFile "\t\t\t\treturn instance as BarricadeConfig\n"
        file writeToFile "\t\t\t}\n"
        file writeToFile "\t\t}\n"
        file writeToFile "\t}\n"

        file writeToFile "\tprivate val configs = hashMapOf<String, $PACKAGE_NAME.response.BarricadeResponseSet>()\n\n"
        file writeToFile "\tinit {\n"
        file writeToFile "\t\tval barricadeResponsesForRandom = mutableListOf<com.mutualmobile.barricade.response.BarricadeResponse>()\n"
        symbols.forEach { symbol ->
            symbol.accept(BarricadeVisitor(file, logger), Unit)
        }
        file writeToFile "\t\tconfigs.put(\"random\", com.mutualmobile.barricade.response.BarricadeResponseSet(barricadeResponsesForRandom, 0))\n"
        file writeToFile "\t}\n\n"
        file writeToFile "\toverride fun getConfigs(): HashMap<String, $PACKAGE_NAME.response.BarricadeResponseSet> = configs\n"
        file writeToFile "\toverride fun getResponseForEndpoint(endpoint: String): $PACKAGE_NAME.response.BarricadeResponse? {\n"
        file writeToFile "\t\tval responseSet = configs[endpoint]\n"
        file writeToFile "\t\tresponseSet?.let { nnResponseSet ->\n"
        file writeToFile "\t\t\treturn nnResponseSet.responses[nnResponseSet.defaultIndex]\n"
        file writeToFile "\t\t}\n"
        file writeToFile "\t\treturn null\n"
        file writeToFile "\t}\n"
        file writeToFile "}\n"

Unable to configure the barricade compiler

Gradle is unable to resolve the barricade compiler and times out.

I am adding ksp plugin as follow.

settings.gradle has following added

pluginManagement {
    plugins {
        id("com.google.devtools.ksp") version "1.6.10-1.0.4"
    }
    repositories {
        gradlePluginPortal()
        google()
    }
}

and in app module I have included the plugin id. id("com.google.devtools.ksp") and added compiler dependency as ksp(libs.barricade.compiler) and gradle times out. Is there something which I am missing?

This is the error that I am getting

Unable to find method 'com.google.devtools.ksp.gradle.KspTaskJvm.getClasspathSnapshotProperties()Lorg/jetbrains/kotlin/gradle/tasks/KotlinCompile$ClasspathSnapshotProperties;'
com.google.devtools.ksp.gradle.KspTaskJvm.getClasspathSnapshotProperties()Lorg/jetbrains/kotlin/gradle/tasks/KotlinCompile$ClasspathSnapshotProperties;
Gradle's dependency cache may be corrupt (this sometimes occurs after a network connection timeout.)```

Requesting a new release

Current release got "random" hardcoded in the library so when updating the UI in barricade config screen, we will get a crash

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.