Charlatan - A library for configuring and providing fake http responses to your dio HTTP client.

Overview

charlatan

pub package Build status License: MIT Maintenance

This package provides the ability to configure and return fake HTTP responses from your Dio HTTP Client. This makes it easy to test the behavior of code that interacts with HTTP services without having to use mocks.

It consists of two components:

  • Charlatan - a class for configuring and providing fake HTTP responses based on HTTP method and URI template.
  • CharlatanHttpClientAdapter - an implementation of Dio's HttpClientAdapter that returns responses from a configured Charlatan instance.

Usage

Add charlatan to your pubspec.yaml's dev_dependencies:

# pubspec.yaml
dev_dependencies:
  charlatan:

Configuring fake responses

Create an instance of Charlatan and call the corresponding configuration method for the HTTP method you want to map a request to.

You can configure fakes responses using a specific path or a URI template. You can also use the request object to customize your response.

final charlatan = Charlatan();
charlatan.whenPost('/users', (_) => { 'id': 1, 'bilbo' });
charlatan.whenGet('/users/{id}', (req) => { 'id': req.pathParameters['id'], 'name': 'bilbo' });
charlatan.whenPut('/users/{id}/profile', (_) => null, statusCode: 204);
charlatan.whenDelete('/users/{id}', (_) => null, statusCode: 204);

If you need to further customize the response, you can return a CharlatanHttpResponse.

charlatan.whenPost('/users', (req) {
  final data = req.body as Map<String, Object?>? ?? {};
  final name = data['name'] as String?;
  if (name == null) {
    return CharlatanHttpResponse(
      statusCode: 422,
      body: {
        'errors': {
          'name': ['cannot be blank'],
        },
      },
    );
  }

  return CharlatanHttpResponse(
    statusCode: 201,
    body: { 'id': 1, 'name': name },
  );
});

Building a fake HTTP client

Build the CharlatanHttpClientAdapter from the Charlatan instance and then assign it to your Dio instance's httpClientAdapter.

final charlatan = Charlatan();
// ... configure fake responses ...
final dio = Dio()..httpClientAdapter = charlatan.toFakeHttpClientAdapter();

Now make HTTP requests like your normally would and they will be routed through your configured fakes.

final result = await dio.get<Object?>('/users/1');
expect(result.data, {'id', 1, 'name': 'bilbo'});

FAQ

What happens if I make a request that doesn't match a configured fake response?

You get a helpful error message like this:

Unable to find matching fake http response definition for:

GET /blahhhh

Did you configure it?

The fake http response definitions configured were:
GET /users
POST /users
PUT /users
DELETE /users

How can I configure a fake response that relies upon the result of another fake request? e.g. a POST followed by a GET that can "read its own writes"

Check out the example directory.

Comments
  • feat: Switch to analyzer that annotates on the PR

    feat: Switch to analyzer that annotates on the PR

    📰 Summary of changes

    Switches out our analyze step for one produces by invertase that will annotate the issues on the PR itself

    https://github.com/invertase/github-action-dart-analyzer

    Reviewers

    /domain @Betterment/charlatan-maintainers /no-platform

    approved 
    opened by CelticMajora 21
  • chore(dependabot): Revert

    chore(dependabot): Revert "chore: Add dependabot for github actions"

    Reverts Betterment/charlatan#14

    curious if reverting this will fix the issue with the lcov report. not sure why but i wanna try it.

    /domain @btrautmann @CelticMajora /no-platform

    approved 
    opened by samandmoore 12
  • feat(rename): rename to charlatan and more!

    feat(rename): rename to charlatan and more!

    📰 Summary of changes

    What is the new functionality added in this PR?

    • update readme with some usage and set up info
    • rename to charlatan because there's a defunct pub.dev package called fake_http
    • refactor to support a custom request type instead of relying on the RequestOptions from dio, so we can expose the parsed path params
    • add example for pub.dev
    • add support for async response body builders

    🧪 Testing done

    What testing was added to cover the functionality added in this PR

    Updated unit tests!

    Reviewers

    /domain @Betterment/charlatan-maintainers /no-platform

    opened by samandmoore 12
  • feat: use codecov

    feat: use codecov

    📰 Summary of changes

    What is the new functionality added in this PR?

    Switch to codecov

    Reviewers

    /domain @Betterment/charlatan-maintainers /no-platform

    approved 
    opened by samandmoore 9
  • fix(pana): fix pana warnings

    fix(pana): fix pana warnings

    📰 Summary of changes

    What is the new functionality added in this PR?

    🧪 Testing done

    What testing was added to cover the functionality added in this PR automated.

    Reviewers

    /domain @CelticMajora @caffeineflo @btrautmann /no-platform

    opened by samandmoore 4
  • fix(naming): Fix up some places that were still referring to fake_http

    fix(naming): Fix up some places that were still referring to fake_http

    📰 Summary of changes

    Just patching up a few places that were still referring to fake_http 🦅 👀

    🧪 Testing done

    None!

    Reviewers

    /domain @Betterment/charlatan-maintainers /platform @Betterment/charlatan-maintainers

    approved 
    opened by btrautmann 3
  • feat(response-customization): add CharlatanHttpResponse

    feat(response-customization): add CharlatanHttpResponse

    📰 Summary of changes

    What is the new functionality added in this PR?

    add the ability to customize the entire response within the response definition's response builder callback.

    this allows runtime configuration of the response statusCode, headers, and body; instead of just the body.

    it's a little cute, but we're returning Object? from the response builder still since we don't have the ability to use type unions.

    we could probably make it so that you always have to return a response object, but it's so many more characters to type in the case where you just want the response to be simple :shrug:

    🧪 Testing done

    What testing was added to cover the functionality added in this PR

    Automated tests ✅

    Reviewers

    /domain @Betterment/charlatan-maintainers /no-platform

    opened by samandmoore 3
  • chore: policy-bot updates

    chore: policy-bot updates

    📰 Summary of changes

    What is the new functionality added in this PR?

    Update PR template to remove nanda callouts and setup codeowners to populate reviewers list by default

    opened by samandmoore 2
  • chore(deps): bump actions/checkout from 2.3.5 to 2.4.0

    chore(deps): bump actions/checkout from 2.3.5 to 2.4.0

    Bumps actions/checkout from 2.3.5 to 2.4.0.

    Release notes

    Sourced from actions/checkout's releases.

    v2.4.0

    • Convert SSH URLs like org-<ORG_ID>@github.com: to https://github.com/ - pr
    Commits

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    dependencies 
    opened by dependabot[bot] 2
  • chore: Clean up random unimportant stuff I saw at an initial glance

    chore: Clean up random unimportant stuff I saw at an initial glance

    📰 Summary of changes

    • Cleans up a few things leftover from a freezed project
    • Removes pubspec.lock file

    Reviewers

    /domain @Betterment/charlatan-maintainers /no-platform

    opened by CelticMajora 2
  • Consider adding support for returning more than just body from responseBodyBuilder

    Consider adding support for returning more than just body from responseBodyBuilder

    i'm musing about something like this

    // return this, no processing
    return CharlatanResponse.raw(
      body: '{"id": 12}', // already a string
      headers: {'content-type': 'application/json'},
      statusCode: 200,
    );
    
    // return this but process the body
    return CharlatanResponse(
      // still a map to be converted automatically based on the incoming accept header
      // or defaulting to json
      {'id': 12},
      statusCode: 200,
    );
    
    // current behavior would still work
    return {'id': 12}; 
    

    the reason i'm curious about this approach is that it would be nice to have a way to dynamically decide on the status code in addition to the response body. e.g. sometimes you might wanna do a 422 and not a 200.

    enhancement 
    opened by samandmoore 1
  • Expose method for clearing defined fake `CharlatanHttpResponseDefinition`s

    Expose method for clearing defined fake `CharlatanHttpResponseDefinition`s

    The map with CharlatanHttpResponseDefinitions is private, I would like to have an exposed method for clearing this map. I would like to use this method in tearDown so I don't have to instantiate Charlatan everytime.

    Describe alternatives you've considered Something like http-mock-adapter package has: https://github.com/lomsa-dev/http-mock-adapter/blob/eff6dc4563e30dcfe6b29bac7f7343567d61bdf6/lib/src/mixins/recording.dart#L42

    enhancement 
    opened by mzdm 2
Releases(v0.1.0)
  • v0.1.0(Feb 11, 2022)

    What's Changed

    • feat: Switch to analyzer that annotates on the PR by @CelticMajora in https://github.com/Betterment/charlatan/pull/9
    • chore: Randomize CI test order by @CelticMajora in https://github.com/Betterment/charlatan/pull/10
    • chore: Upgrade deps by @CelticMajora in https://github.com/Betterment/charlatan/pull/11
    • chore: Release 0.1.0 by @CelticMajora in https://github.com/Betterment/charlatan/pull/12
    • chore: Release/0.1.0 by @CelticMajora in https://github.com/Betterment/charlatan/pull/13

    Full Changelog: https://github.com/Betterment/charlatan/compare/v0.0.1...v0.1.0

    Source code(tar.gz)
    Source code(zip)
  • v0.0.1(Dec 16, 2021)

Owner
Betterment
We're passionate about building the simplest, most sophisticated investment platform on the planet. Visit us at www.betterment.com/jobs.
Betterment
An easy-to-use flutter http network requests handler with more functionality than http but more simpler than dio.

network_requests An easy-to-use flutter http network requests handler with more functionality than http but more simpler than dio. Platform Supported

Coder_Manuel 3 Dec 15, 2022
Getx and Dio APi-Integration - Flutter RestApi Integration using Dio

Flutter RestApi Integration using Dio. Click this image to find videos==> //Crud

Fsd Ramjan 9 Nov 5, 2022
A wrapper around our Cocoa and Java client library SDKs, providing iOS and Android support for those using Flutter and Dart.

Ably Flutter Plugin A Flutter plugin wrapping the ably-cocoa (iOS) and ably-java (Android) client library SDKs for Ably, the platform that powers sync

Ably Realtime - our client library SDKs and libraries 46 Dec 13, 2022
Create fake phone contacts, to do data-poisoning.

Fake Contacts Android phone app that creates fake contacts, which will be stored on your smartphone along with your real contacts. This feeds fake dat

Bill Dietrich 531 Dec 23, 2022
Fake Firebase Performance for use during Flutter unit & widget tests.

Fake Firebase Performance Fakes to write unit tests for apps using Firebase Performance monitoring. Instantiate a FakeFirebasePerformance, then pass i

Philipp Bauer 2 Apr 16, 2022
A composable, light-weight package that can be used as a placeholder whenever you need some fake data

API Placeholder A composable, light-weight package that can be used as a placeholder whenever you need some fake data. With this package, you can get

ASMIT VIMAL 2 Feb 27, 2022
This library allows you to create editable tables and spreadsheets with ease, either by providing initial row and column count to display an empty table or use it with predefined rows and column data sets.

Editable ⚡️ A highly customizable, editable table package for Flutter projects. Specs This package allows you to create editable tables and spreadshee

Godwin Asuquo 94 Dec 7, 2022
A simple library providing programmatic access to the iTunes search API for podcasts.

A library for searching for podcasts, parsing podcast RSS feeds and obtaining episodes details. Supports searching via iTunes and PodcastIndex (previe

Ben Hills 23 Dec 28, 2022
An app that randomly draws Japanese vocabularies from N5 to N1 level to test your listening skill, providing pronunciation and answer checking.

An app that randomly draws Japanese vocabularies from N5 to N1 level to test your listening skill, providing pronunciation and answer checking.

Eric Lau 13 Jul 17, 2022
Nebula makes your Flutter development journey easier by providing helper widgets, utilities and abstractions.

Nebula makes your Flutter development journey easier by providing helper widgets, utilities and abstractions.

Aldrin's Art Factory 1 Apr 21, 2022
A flutter package that helps you create an on-boarding screen for your project within minutes just by providing a few parameters.

A flutter package that helps you create an on-boarding screen for your project within minutes just by providing a few parameters.

Sachin Kr. Shukla 40 Sep 27, 2022
A middleware library for Dart's http library.

http_middleware A middleware library for Dart http library. Getting Started http_middleware is a module that lets you build middleware for Dart's http

TED Consulting 38 Oct 23, 2021
Weather app using Bloc architecture pattern & generic HTTP client with interface implementation and much more for more detail read Readme

weather Weather application for current weather, hourly forecast for 48 hours, Daily forecast for 7 days and national weather alerts. How to Run Insta

Jibran Ahmed SiddiQui 9 Oct 29, 2022
Powerful, helpfull, extensible and highly customizable API's that wrap http client to make communication easier with Axelor server with boilerplate code free.

flutter_axelor_sdk Powerful, helpful, extensible and highly customizable API's that wrap http client to make communication easier with Axelor server w

Abd al-Rahman al-Ktefane 5 Dec 25, 2022
A lightweight and customizable http client that allows you to create offline-first dart app easily.

Enjoyable & customizable offline-first REST API client Unruffled is lightweight and customizable http client that allows you to create offline-first e

T. Milian 3 May 20, 2022
Generates a new Flutter app with http client, theme, routing and localization features.

Starter Template Generates a new Flutter app with http client, theme, routing and localization features. Brick Uses: dio as http client pretty_dio_log

Cem Avcı 12 Nov 3, 2022
A powerful Http client for Dart, which supports Interceptors, FormData, Request Cancellation, File Downloading, Timeout etc.

dio_http A powerful Http client for Dart, which supports Interceptors, Global configuration, FormData, Request Cancellation, File downloading, Timeout

null 46 Dec 19, 2021
A powerful Http client for Dart, which supports Interceptors, FormData, Request Cancellation, File Downloading, Timeout etc.

Language: English | 中文简体 dio A powerful Http client for Dart, which supports Interceptors, Global configuration, FormData, Request Cancellation, File

Flutter中国开源项目 11.2k Jan 3, 2023
CoVAC is an all-in-one Covid info toolkit app, providing users the facility to check for available slots along with receiving the latest updates related to the pandemic and the virus.

CoVAC - Covid 19 Vaccine Availability Checker Introduction ?? CoVAC is an android application developed to provide users the facility to check the ava

Aryan Kenchappagol 6 Dec 29, 2021