summaryrefslogtreecommitdiff
path: root/test/storage/http_error.cpp
blob: 498f1eae6b62b08adb16dc9b9dccf25630ef7458 (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
62
63
#include "storage.hpp"

#include <uv.h>

#include <mbgl/storage/default_file_source.hpp>
#include <mbgl/storage/network_status.hpp>

#include <cmath>

TEST_F(Storage, HTTPError) {
    SCOPED_TEST(HTTPTemporaryError)
    SCOPED_TEST(HTTPConnectionError)

    using namespace mbgl;

    uv_timer_t statusChange;
    uv_timer_init(uv_default_loop(), &statusChange);
    uv_timer_start(&statusChange, [](uv_timer_t *, int) {
        NetworkStatus::Reachable();
    }, 500, 500);
    uv_unref((uv_handle_t *)&statusChange);

    DefaultFileSource fs(nullptr, uv_default_loop());

    auto start = uv_hrtime();

    fs.request({ Resource::Unknown, "http://127.0.0.1:3000/temporary-error" }, uv_default_loop(), [&](const Response &res) {
        const auto duration = double(uv_hrtime() - start) / 1e9;
        EXPECT_LT(1, duration) << "Backoff timer didn't wait 1 second";
        EXPECT_GT(1.2, duration) << "Backoff timer fired too late";
        EXPECT_EQ(Response::Successful, res.status);
        EXPECT_EQ("Hello World!", res.data);
        EXPECT_EQ(0, res.expires);
        EXPECT_EQ(0, res.modified);
        EXPECT_EQ("", res.etag);
        EXPECT_EQ("", res.message);

        HTTPTemporaryError.finish();
    });

    fs.request({ Resource::Unknown, "http://127.0.0.1:3001/" }, uv_default_loop(), [&](const Response &res) {
        const auto duration = double(uv_hrtime() - start) / 1e9;
        // 1.5 seconds == 4 retries, with a 500ms timeout (see above).
        EXPECT_LT(1.5, duration) << "Resource wasn't retried the correct number of times";
        EXPECT_GT(1.7, duration) << "Resource wasn't retried the correct number of times";
        EXPECT_EQ(Response::Error, res.status);
        EXPECT_TRUE(res.message == "Couldn't connect to server: couldn't connect to host" || res.message == "The operation couldn’t be completed. (NSURLErrorDomain error -1004.)") << res.message;
        EXPECT_EQ("", res.data);
        EXPECT_EQ(0, res.expires);
        EXPECT_EQ(0, res.modified);
        EXPECT_EQ("", res.etag);
        HTTPConnectionError.finish();
    });


    uv_run(uv_default_loop(), UV_RUN_DEFAULT);

    uv_timer_stop(&statusChange);
    uv_close(reinterpret_cast<uv_handle_t *>(&statusChange), nullptr);

    // Run again so that the timer handle can be properly closed.
    uv_run(uv_default_loop(), UV_RUN_DEFAULT);
}