File: base.py

package info (click to toggle)
eumdac 3.0.0-1.1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 716 kB
  • sloc: python: 7,325; makefile: 6
file content (206 lines) | stat: -rw-r--r-- 6,348 bytes parent folder | download
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
import unittest
import re
import pickle
import os
import io
import gzip
import zlib
import urllib
from base64 import b64encode

import responses
from responses import matchers
from contextlib import contextmanager


CONSUMER_KEY = os.getenv("CONSUMER_KEY")
CONSUMER_SECRET = os.getenv("CONSUMER_SECRET")

# different modes
# INTEGRATION_TESTING -> Targets real OPE endpoints + record all calls
INTEGRATION_TESTING = os.getenv("INTEGRATION_TESTING")
if INTEGRATION_TESTING and not (CONSUMER_KEY and CONSUMER_SECRET):
    raise RuntimeError("Integration testing requires credentials!")

http_methods = ["GET", "HEAD", "POST", "PUT", "DELETE", "CONNECT", "OPTIONS", "TRACE", "PATCH"]


class ReplayResponse(responses.Response):
    def __init__(self, request, response):
        self._request = request
        self._response = response
        parsed_url = urllib.parse.urlparse(request.url)
        super().__init__(
            request.method,
            request.url,
            body=response.content,
            status=response.status_code,
            headers=response.headers,
            match=[matchers.query_string_matcher(parsed_url.query)],
        )
        if "gzip" in response.headers.get("Content-Encoding", ""):
            self.body = self._gzip_compress(self.body)

    @staticmethod
    def _gzip_compress(data):
        if hasattr(data, "read"):
            data = data.read()
        if isinstance(data, str):
            data = data.encode()
        # window size flag, +25 to +31 include a basic gzip
        # header and trailing checksum
        wbits = 28
        compressor = zlib.compressobj(wbits=wbits)
        compressed_chunks = [compressor.compress(data), compressor.flush()]
        return b"".join(compressed_chunks)


class ReplayResponsesTestCase(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        if INTEGRATION_TESTING:
            cls.prepare_integration_test()
        cls.recordpath = "{0}/data/{1}.{2}.pickle.gz".format(
            os.path.dirname(__file__), cls.__module__.split(".")[-1], cls.__name__
        )
        cls.requests_mock = responses.RequestsMock()
        if INTEGRATION_TESTING:
            cls._records = {}
        else:
            with gzip.open(cls.recordpath) as file:
                cls._records = pickle.load(file)

    def setUp(self):
        if INTEGRATION_TESTING:
            url = re.compile(".*")
            for method in http_methods:
                self.requests_mock.add(responses.PassthroughResponse(method, url))
            self.requests_mock.assert_all_requests_are_fired = False
            self.requests_mock.response_callback = self._record_streaming_response_body
        else:
            calls = self._records.get(self.record_key, responses.CallList())
            for request, response in calls:
                replay = ReplayResponse(request, response)
                self.requests_mock.add(replay)
            self.requests_mock.assert_all_requests_are_fired = True
        self.addCleanup(self.requests_mock.reset)
        self.requests_mock.start()
        self.addCleanup(self.requests_mock.stop)

    def tearDown(self):
        if INTEGRATION_TESTING:
            calls = list(self.requests_mock.calls)
            if calls:
                self._records[self.record_key] = calls

    @classmethod
    def tearDownClass(cls):
        if INTEGRATION_TESTING:
            with gzip.open(cls.recordpath, mode="wb") as file:
                pickle.dump(cls._records, file)

    @property
    def record_key(self):
        return self._testMethodName

    @staticmethod
    def _record_streaming_response_body(response):
        if not response.raw.closed:
            content = response.content
            response.raw = io.BytesIO(content)
        return response

    @classmethod
    def prepare_integration_test(cls):
        """This method can be used to check preconditions for integration tests"""
        pass


class DataServiceTestCase(ReplayResponsesTestCase):
    credentials = (
        CONSUMER_KEY or "pewh0CiBQ5Gl8BX7K2i8vww9tsr0",
        CONSUMER_SECRET or "cP58wJbenKRPaK9RKA8ODPxHmkw1",
    )

    @classmethod
    def tearDownClass(cls):
        if INTEGRATION_TESTING:
            key, secret = map(str.encode, cls.credentials)
            sensitive = b64encode(key + b":" + secret)
            xs = len(key) * b"x"
            crossed = b64encode(xs + b":" + xs)
            pickled = pickle.dumps(cls._records)
            sanitized = pickled.replace(sensitive, crossed)
            with gzip.open(cls.recordpath, mode="wb") as file:
                file.write(sanitized)


class FakeProduct:
    def __init__(self, id=None, collection=None):
        self._id = id or "product"
        self.collection = collection or FakeCollection()

    @property
    def md5(self):
        return None


class FakeCollection:
    def __init__(self, id=None):
        self._id = id or "collection"


class FakeCustomisation:
    def __init__(self, states_to_return, cid=None):
        self.states_to_return = iter(states_to_return)
        self.logfile = f"Fake Log: {states_to_return}"
        self._id = cid or "test"
        self.deleted = False

    @property
    def status(self):
        return next(self.states_to_return)

    @property
    def outputs(self):
        return ["prod1.nc", "prod2.nc"]

    def kill(self):
        pass

    def delete(self):
        if not self.deleted:
            self.deleted = True
        else:
            from eumdac.errors import CustomisationError

            raise CustomisationError("double deletion")

    @contextmanager
    def stream_output_iter_content(self, output, chunks=0):
        yield [bytes("test", "utf-8")]


class FakeTailor:
    def __init__(self):
        self.user_info = {
            "username": "test",
        }
        self.quota = {
            "data": {
                "test": {
                    "space_usage_percentage": 95,
                }
            }
        }

    def get_customisation(self, id):
        return FakeCustomisation(["QUEUED", "RUNNING", "DONE"], cid=id)

    def new_customisation(self, product, chain):
        return FakeCustomisation(["QUEUED", "RUNNING", "DONE"], cid=None)


class FakeStore:
    def get_product(self, col_id, p_id):
        return FakeProduct(id=p_id, collection=FakeCollection(id=col_id))