http-mock-adapter
http-mock-adapter copied to clipboard
Let server return different responses
I would like to test a retry mechanism. Therefore I want the server to return different responses. The first response should be a 500 and the second one a 200. I tried to do that with the following code, but its not working. The callback is only called once. Do you have an idea how to achieve this?
void main() {
final dio = Dio(BaseOptions());
//Adding retry interceptor here, which would execute the GET again with the same Dio after receiving the 500
final dioAdapter = DioAdapter(dio: dio);
const path = 'https://example.com';
int counter = 0;
test("retry", () async {
dioAdapter.onGet(
path,
(server) {
if (counter == 0) {
counter += 1;
server.reply(
500,
{},
);
} else {
server.reply(
200,
{'message': 'Success!'},
// Reply would wait for one-sec before returning data.
delay: const Duration(seconds: 1),
);
}
},
);
final Response response = await dio.get(path);
expect(response.statusCode, 200);
});
}
Thank you!
@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.
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 @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
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:
- GET Request to http://localhost/cars/1 delivers 404 (not found)
- POST Request to http://localhost/cars/1 for creating the car entity (http status 200)
- GET Request to http://localhost/cars/1 delivers 200 with some cars data
- 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 Yeh, that makes sense. Currently, it's not supported, but definitely good to have. I'll keep this issue open. Thank you!
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:
- GET Request to http://localhost/cars/1 delivers 404 (not found)
- POST Request to http://localhost/cars/1 for creating the car entity (http status 200)
- GET Request to http://localhost/cars/1 delivers 200 with some cars data
- 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?
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