aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/testing/mock_server/server.cpp
blob: d310c76ad324c06c32acdd941671d675258ce0f6 (plain) (blame)
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
64
65
66
67
68
69
70
#include "server.h"

#include <util/system/thread.h>

namespace NMock {
    class TMockServer::TCallBack: public THttpServer::ICallBack {
        TGenerator Generator_;

        TClientRequest* CreateClient() override {
            return Generator_();
        }

    public:
        void SetGenerator(TGenerator generator) {
            Generator_ = generator;
        }

        TCallBack(TGenerator& generator)
            : Generator_(generator)
        {
        }
    };

    static THttpServerOptions createDefaultOptions(ui16 port) {
        THttpServerOptions o;
        o.AddBindAddress("localhost", port);
        o.SetThreads(1);
        o.SetMaxConnections(300);
        o.SetMaxQueueSize(30);
        return o;
    }

    TMockServer::TMockServer(ui16 port, TGenerator generator)
        : TMockServer(createDefaultOptions(port), generator)
    {
    }

    TMockServer::TMockServer(const THttpServerOptions& options, TGenerator generator)
        : Cb_(MakeHolder<TCallBack>(generator))
        , Server_(MakeHolder<THttpServer>(Cb_.Get(), options))
        , Thread_(MakeHolder<TThread>(Worker, this))
        , Ev_(MakeHolder<TAutoEvent>())
    {
        Thread_->Start();
        Ev_->Wait();
    }

    TMockServer::~TMockServer() {
        Server_->Stop();
        Thread_->Join();
    }

    size_t TMockServer::GetClientCount() const {
        return Server_->GetClientCount();
    }

    void TMockServer::SetGenerator(TMockServer::TGenerator generator) {
        Cb_->SetGenerator(generator);
    }

    void* TMockServer::Worker(void* arg) {
        TMockServer& this_ = *static_cast<TMockServer*>(arg);

        this_.Server_->Start();
        this_.Ev_->Signal();
        this_.Server_->Wait();

        return nullptr;
    }
}