summaryrefslogtreecommitdiff
path: root/test/src/mbgl/test/fake_file_source.hpp
blob: baae7f9b7e5838cc8add0f13f3f483a2f3f6d0df (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#pragma once

#include <mbgl/storage/file_source.hpp>

#include <algorithm>
#include <list>

namespace mbgl {

/*
   FakeFileSource is similar to StubFileSource, but it follows a post hoc, "push" model rather than
   a pre hoc, "pull" model. You pass it to code that makes requests, it records what requests are
   made, then you can examine them, make assertions about them, and respond as desired.

   This is particularly useful if you want to simulate multiple responses, e.g. as part of a resource
   revalidation flow. StubFileSource allows only a single response.
*/
class FakeFileSource : public FileSource {
public:
    class FakeFileRequest : public AsyncRequest {
    public:
        Resource resource;
        Callback callback;

        std::list<FakeFileRequest*>& list;
        std::list<FakeFileRequest*>::iterator link;

        FakeFileRequest(Resource resource_, Callback callback_, std::list<FakeFileRequest*>& list_)
            : resource(std::move(resource_)),
              callback(std::move(callback_)),
              list(list_),
              link((list.push_back(this), std::prev(list.end()))) {
        }

        ~FakeFileRequest() override {
            list.erase(link);
        }
    };

    std::unique_ptr<AsyncRequest> request(const Resource& resource, Callback callback) override {
        return std::make_unique<FakeFileRequest>(resource, callback, requests);
    }

    bool respond(Resource::Kind kind, const Response& response) {
        auto it = std::find_if(requests.begin(), requests.end(), [&] (FakeFileRequest* fakeRequest) {
            return fakeRequest->resource.kind == kind;
        });

        if (it != requests.end()) {
            // Copy the callback, in case calling it deallocates the AsyncRequest.
            Callback callback_ = (*it)->callback;
            callback_(response);
        }

        return it != requests.end();
    }

    std::list<FakeFileRequest*> requests;
};

} // namespace mbgl