Giter Club home page Giter Club logo

Comments (7)

sebastianbuechler avatar sebastianbuechler commented on June 25, 2024 3

Hi @LukaGiorgadze, yes absolutely. You are right. A frontend can't handle different structure of a response for the came api request. But how can I handle different values and different status code in the same test for the same URL? for example this test scenario:

  1. GET Request to http://localhost/cars/1 delivers 404 (not found)
  2. POST Request to http://localhost/cars/1 for creating the car entity (http status 200)
  3. GET Request to http://localhost/cars/1 delivers 200 with some cars data
  4. POST Request to http://localhost/cars/1 deliver 409 ("conflict" or something other)

Requests 1 and 3 are going to the same path with different responses. Request 2 and 4 too. There is a history (aka recording) mechanism inside http-mock-adapter , isn't it?

Any ideas?

@meltzow You can reconfigure the mock responses after you made your calls like this:

    test('test retry mechanism', () async {
      const path = 'http://localhost/cars/1';

      var data = {'id': 1, 'name': 'mock'};
      Response<dynamic> response;
      final dioError404 = DioException(
        error: {'message': 'error'},
        requestOptions: RequestOptions(path: path),
        response: Response(
          statusCode: 404,
          requestOptions: RequestOptions(path: path),
        ),
        type: DioExceptionType.badResponse,
      );
      final dioError409 = DioException(
        error: {'message': 'error'},
        requestOptions: RequestOptions(path: path),
        response: Response(
          statusCode: 409,
          requestOptions: RequestOptions(path: path),
        ),
        type: DioExceptionType.badResponse,
      );

      // 1. GET Request to http://localhost/cars/1 delivers 404 (not found)
      dioAdapter.onGet(path, (server) => server.throws(404, dioError404));
      dioAdapter.onPost(
        path,
        (server) => server.reply(201, 'Created'),
        data: data,
      );

      expect(() async => await dio.get(path), throwsA(isA<DioException>()));

      // 2. POST Request to http://localhost/cars/1 for creating the car entity (http status 200)
      response = await dio.post(path, data: data);
      expect(response.statusCode, 201);
      expect(response.data, 'Created');

      dioAdapter.onGet(
        path,
        (server) => server.reply(200, data),
      );

      // 3. GET Request to http://localhost/cars/1 delivers 200 with some cars data
      response = await dio.get(path);
      expect(response.statusCode, 200);
      expect(response.data, data);

      // 4. POST Request to http://localhost/cars/1 deliver 409 ("conflict" or something other)
      dioAdapter.onPost(
        path,
        (server) => server.throws(409, dioError409),
        data: data,
      );
      expect(() async => await dio.post(path), throwsA(isA<DioException>()));
    });

If you have a more complex solution I would usually go for a self-storing solution. Create a map in your test var cars = <String, Car>{}; and then make the endpoints general something like this:

      dioAdapter.onGet(
        path,
        (server) => server.reply(
          200,
          (RequestOptions options) {
            final carId = options.path.split('/').last;
            return cars[carId];
          },
        ),
      );
      dioAdapter.onPost(
        path,
        (server) => server.reply(
          201,
          (RequestOptions options) {
            final carId = options.path.split('/').last;
            cars[carId] = options.data;
            return 'Created';
          },
        ),
        data: data,
      );

However, here you would need to introduce a fallback for the cases where the car does not exist (GET) or even already exists (POST). I tried with the approach like this:

      dioAdapter.onGet(
        path,
        (server) {
          final carId = path.split('/').last;
          if (!cars.containsKey(carId)) {
            server.throws(404, dioError404);
            return;
          }

          server.reply(
            200,
            (RequestOptions options) {
              final carId = options.path.split('/').last;
              return cars[carId];
            },
          );
        },
      );

But it does not work as the guard clause for not-found cars is happening on the registering level and thus only called once (in comparison to the callback for the request). If I'm not mistaken there's at the moment no way to decide if we want to reply or throw an exception only based on the request. The callback would have to be on an entire level higher (the entire request and not just the body).

I'm also not quite sure what the reason behind the history feature of this package is as I currently do not see any benefits. Or is it so that we could easily test the entire call history?

from http-mock-adapter.

Tetr4 avatar Tetr4 commented on June 25, 2024 3

Here is a small workaround for returning different status codes with different requests:

final adapter = DioAdapter(dio: dio);
adapter.onGet('foo', (server) {
  // Reply with 401 on first response
  server.reply(401, (request) {
    // Reply with 200 on second response
    adapter.onGet('foo', (server) => server.reply(200, 'OK'));
    return 'Unauthorized';
  });
});

Not very elegant, but I need this for testing an interceptor for a token refresh flow, so the first response must return 401 (access token invalid and must be refreshed) and the second should return 200 (token valid).

A solution could be to allow "enqueuing" response, e.g. like okhttp/mockwebserver: https://github.com/square/okhttp/tree/master/mockwebserver

from http-mock-adapter.

LukaGiorgadze avatar LukaGiorgadze commented on June 25, 2024 2

@AdrianDev0 As per RESTful standards, usually you should expect the same result from the same endpoint. If not - there might be something wrong with the implementation.
If you need to test different scenarios on the same endpoint, I suggest using dioAdapter.onGet but per one request/per one response.

from http-mock-adapter.

meltzow avatar meltzow commented on June 25, 2024

hi @LukaGiorgadze
If I understand RESTful standard correct, there no expectation to have the same result from the same endpoint. It depends from time or better from state at server (perhaps database).

for example: If I do a GET from "http://localhost/cars/1" probably the response contains a car entity (with Id 1). But if this car entity was changed or deleted I'will get another response.

How can I test these scenario with http-mock-adapter in one test?
Thank you

from http-mock-adapter.

LukaGiorgadze avatar LukaGiorgadze commented on June 25, 2024

hi @LukaGiorgadze If I understand RESTful standard correct, there no expectation to have the same result from the same endpoint. It depends from time or better from state at server (perhaps database).

for example: If I do a GET from "http://localhost/cars/1" probably the response contains a car entity (with Id 1). But if this car entity was changed or deleted I'will get another response.

How can I test these scenario with http-mock-adapter in one test? Thank you

Hi @meltzow , thank you for your feedback!

Okay, let's take your example [GET] http://localhost/cars/1
This endpoint potentially can return a different response per different status codes, but not a different response with the same status code (when I'm saying response I mean the structure of the response, not the actual values).
Now imagine, you have a frontend typescript schema that expects a Cars entity with the pre-defined fields for status 200, how correct it will be if you get a different data structure but the same status code 200? Your front end won't understand what to expect and when.

Well, in the above case if you expect breaking changes on the front end, ideally you should version your API by URL. http://localhost/v1/cars/1

from http-mock-adapter.

meltzow avatar meltzow commented on June 25, 2024

Hi @LukaGiorgadze,
yes absolutely. You are right. A frontend can't handle different structure of a response for the came api request.
But how can I handle different values and different status code in the same test for the same URL?
for example this test scenario:

  1. GET Request to http://localhost/cars/1 delivers 404 (not found)
  2. POST Request to http://localhost/cars/1 for creating the car entity (http status 200)
  3. GET Request to http://localhost/cars/1 delivers 200 with some cars data
  4. POST Request to http://localhost/cars/1 deliver 409 ("conflict" or something other)

Requests 1 and 3 are going to the same path with different responses. Request 2 and 4 too. There is a history (aka recording) mechanism inside http-mock-adapter , isn't it?

Any ideas?

from http-mock-adapter.

LukaGiorgadze avatar LukaGiorgadze commented on June 25, 2024

@meltzow Yeh, that makes sense. Currently, it's not supported, but definitely good to have. I'll keep this issue open. Thank you!

from http-mock-adapter.

Related Issues (20)

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.