• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

testit-tms / adapters-python / 15869211008

25 Jun 2025 06:39AM UTC coverage: 43.078% (+7.9%) from 35.139%
15869211008

Pull #188

github

web-flow
Merge cc17fcbec into bdca47b5c
Pull Request #188: fix: TMS-33524 fix html tags escaping

75 of 106 new or added lines in 3 files covered. (70.75%)

3 existing lines in 1 file now uncovered.

1170 of 2716 relevant lines covered (43.08%)

0.87 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

29.76
/testit-python-commons/src/testit_python_commons/client/api_client.py
1
import logging
2✔
2
import os
2✔
3
import typing
2✔
4
from datetime import datetime
2✔
5

6
from testit_api_client import ApiClient, Configuration
2✔
7
from testit_api_client.api import AttachmentsApi, AutoTestsApi, TestRunsApi, TestResultsApi, WorkItemsApi
2✔
8
from testit_api_client.models import (
2✔
9
    AutoTestApiResult,
10
    AutoTestPostModel,
11
    AutoTestPutModel,
12
    AttachmentPutModel,
13
    AutoTestResultsForTestRunModel,
14
    TestResultResponse,
15
    WorkItemIdModel,
16
    WorkItemIdentifierModel
17
)
18

19
from testit_python_commons.client.client_configuration import ClientConfiguration
2✔
20
from testit_python_commons.client.converter import Converter
2✔
21
from testit_python_commons.models.test_result import TestResult
2✔
22
from testit_python_commons.services.logger import adapter_logger
2✔
23
from testit_python_commons.services.retry import retry
2✔
24
from testit_python_commons.utils.html_escape_utils import HtmlEscapeUtils
2✔
25

26

27
class ApiClientWorker:
2✔
28
    __max_tests_for_write = 100
2✔
29

30
    def __init__(self, config: ClientConfiguration):
2✔
31
        api_client_config = self.__get_api_client_configuration(
×
32
            url=config.get_url(),
33
            verify_ssl=config.get_cert_validation() != 'false',
34
            proxy=config.get_proxy())
35
        api_client = self.__get_api_client(api_client_config, config.get_private_token())
×
36

37
        self.__test_run_api = TestRunsApi(api_client=api_client)
×
38
        self.__autotest_api = AutoTestsApi(api_client=api_client)
×
39
        self.__attachments_api = AttachmentsApi(api_client=api_client)
×
40
        self.__test_results_api = TestResultsApi(api_client=api_client)
×
41
        self.__work_items_api = WorkItemsApi(api_client=api_client)
×
42
        self.__config = config
×
43

44
    @staticmethod
2✔
45
    @adapter_logger
2✔
46
    def __get_api_client_configuration(url: str, verify_ssl: bool = True, proxy: str = None) -> Configuration:
2✔
47
        api_client_configuration = Configuration(host=url)
×
48
        api_client_configuration.verify_ssl = verify_ssl
×
49
        api_client_configuration.proxy = proxy
×
50

51
        return api_client_configuration
×
52

53
    @staticmethod
2✔
54
    @adapter_logger
2✔
55
    def __get_api_client(api_client_config: Configuration, token: str) -> ApiClient:
2✔
56
        return ApiClient(
×
57
            configuration=api_client_config,
58
            header_name='Authorization',
59
            header_value='PrivateToken ' + token)
60

61
    @staticmethod
2✔
62
    def _escape_html_in_model(model):
2✔
63
        """Apply HTML escaping to all models before sending to API"""
NEW
64
        return HtmlEscapeUtils.escape_html_in_object(model)
×
65

66
    @adapter_logger
2✔
67
    def create_test_run(self):
2✔
68
        test_run_name = f'TestRun_{datetime.today().strftime("%Y-%m-%dT%H:%M:%S")}' if \
×
69
            not self.__config.get_test_run_name() else self.__config.get_test_run_name()
70
        model = Converter.test_run_to_test_run_short_model(
×
71
            self.__config.get_project_id(),
72
            test_run_name
73
        )
NEW
74
        model = self._escape_html_in_model(model)
×
75

76
        response = self.__test_run_api.create_empty(create_empty_test_run_api_model=model)
×
77

78
        return Converter.get_id_from_create_test_run_response(response)
×
79

80
    @adapter_logger
2✔
81
    def set_test_run_id(self, test_run_id: str):
2✔
82
        self.__config.set_test_run_id(test_run_id)
×
83

84
    @adapter_logger
2✔
85
    def get_autotests_by_test_run_id(self):
2✔
86
        response = self.__test_run_api.get_test_run_by_id(self.__config.get_test_run_id())
×
87

88
        return Converter.get_resolved_autotests_from_get_test_run_response(
×
89
            response,
90
            self.__config.get_configuration_id())
91

92
    @adapter_logger
2✔
93
    def write_test(self, test_result: TestResult):
2✔
94
        model = Converter.project_id_and_external_id_to_auto_tests_search_post_request(
×
95
            self.__config.get_project_id(),
96
            test_result.get_external_id())
97

98
        autotests = self.__autotest_api.api_v2_auto_tests_search_post(auto_test_search_api_model=model)
×
99

100
        if autotests:
×
101
            self.__update_test(test_result, autotests[0])
×
102
        else:
103
            self.__create_test(test_result)
×
104

105
        return self.__load_test_result(test_result)
×
106

107
    @adapter_logger
2✔
108
    def write_tests(self, test_results: typing.List[TestResult], fixture_containers: dict):
2✔
109
        autotests_for_create = []
×
110
        autotests_for_update = []
×
111
        results_for_autotests_being_created = []
×
112
        results_for_autotests_being_updated = []
×
113

114
        for test_result in test_results:
×
115
            test_result = self.__add_fixtures_to_test_result(test_result, fixture_containers)
×
116

117
            model = Converter.project_id_and_external_id_to_auto_tests_search_post_request(
×
118
                self.__config.get_project_id(),
119
                test_result.get_external_id())
120

121
            test_result_model = Converter.test_result_to_testrun_result_post_model(
×
122
                test_result,
123
                self.__config.get_configuration_id())
124

125
            autotests = self.__autotest_api.api_v2_auto_tests_search_post(auto_test_search_api_model=model)
×
126

127
            if autotests:
×
128
                autotest_for_update = self.__prepare_to_update_autotest(test_result, autotests[0])
×
129

130
                autotests_for_update.append(autotest_for_update)
×
131
                results_for_autotests_being_updated.append(test_result_model)
×
132

133
                if len(autotests_for_update) >= self.__max_tests_for_write:
×
134
                    self.__update_tests(autotests_for_update)
×
135
                    self.__load_test_results(results_for_autotests_being_updated)
×
136

137
                    autotests_for_update.clear()
×
138
                    results_for_autotests_being_updated.clear()
×
139
            else:
140
                autotest_for_create = self.__prepare_to_create_autotest(test_result)
×
141

142
                autotests_for_create.append(autotest_for_create)
×
143
                results_for_autotests_being_created.append(test_result_model)
×
144

145
                if len(autotests_for_create) >= self.__max_tests_for_write:
×
146
                    self.__create_tests(autotests_for_create)
×
147
                    self.__load_test_results(results_for_autotests_being_created)
×
148

149
                    autotests_for_create.clear()
×
150
                    results_for_autotests_being_created.clear()
×
151

152
        if len(autotests_for_update) > 0:
×
153
            self.__update_tests(autotests_for_update)
×
154
            self.__load_test_results(results_for_autotests_being_updated)
×
155

156
            autotests_for_update.clear()
×
157
            results_for_autotests_being_updated.clear()
×
158

159
        if len(autotests_for_create) > 0:
×
160
            self.__create_tests(autotests_for_create)
×
161
            self.__load_test_results(results_for_autotests_being_created)
×
162

163
            autotests_for_create.clear()
×
164
            results_for_autotests_being_created.clear()
×
165

166
    @adapter_logger
2✔
167
    def __prepare_to_create_autotest(self, test_result: TestResult) -> AutoTestPostModel:
2✔
168
        logging.debug('Preparing to create the auto test ', test_result.get_external_id())
×
169

170
        model = Converter.test_result_to_autotest_post_model(
×
171
            test_result,
172
            self.__config.get_project_id())
173
        model.work_item_ids_for_link_with_auto_test = self.__get_work_item_uuids_for_link_with_auto_test(
×
174
            test_result.get_work_item_ids())
175

176
        return model
×
177

178
    @adapter_logger
2✔
179
    def __prepare_to_update_autotest(
2✔
180
            self,
181
            test_result: TestResult,
182
            autotest: AutoTestApiResult) -> AutoTestPutModel:
183
        logging.debug('Preparing to update the auto test ', test_result.get_external_id())
×
184

185
        model = Converter.test_result_to_autotest_put_model(
×
186
            test_result,
187
            self.__config.get_project_id())
188
        model.is_flaky = autotest.is_flaky
×
189
        model.work_item_ids_for_link_with_auto_test = self.__get_work_item_uuids_for_link_with_auto_test(
×
190
            test_result.get_work_item_ids(),
191
            str(autotest.global_id))
192

193
        return model
×
194

195
    @staticmethod
2✔
196
    @adapter_logger
2✔
197
    def __add_fixtures_to_test_result(
2✔
198
            test_result: TestResult,
199
            fixtures_containers: dict) -> TestResult:
200
        setup_results = []
×
201
        teardown_results = []
×
202

203
        for uuid, fixtures_container in fixtures_containers.items():
×
204
            if test_result.get_external_id() in fixtures_container.external_ids:
×
205
                if fixtures_container.befores:
×
206
                    setup_results += fixtures_container.befores[0].steps
×
207

208
                if fixtures_container.afters:
×
209
                    teardown_results = fixtures_container.afters[0].steps + teardown_results
×
210

211
        test_result.set_setup_results(setup_results)
×
212
        test_result.set_teardown_results(teardown_results)
×
213

214
        return test_result
×
215

216
    @adapter_logger
2✔
217
    def __get_work_item_uuids_for_link_with_auto_test(
2✔
218
            self,
219
            work_item_ids: list,
220
            autotest_global_id: str = None) -> list:
221
        linked_work_items = []
×
222

223
        if autotest_global_id:
×
224
            linked_work_items = self.__get_work_items_linked_to_autotest(autotest_global_id)
×
225

226
        work_item_uuids = self.__prepare_list_of_work_item_uuids(linked_work_items, work_item_ids)
×
227

228
        return work_item_uuids
×
229

230
    @adapter_logger
2✔
231
    def __prepare_list_of_work_item_uuids(
2✔
232
            self,
233
            linked_work_items: list,
234
            work_item_ids: list) -> list:
235
        work_item_uuids = []
×
236

237
        for linked_work_item in linked_work_items:
×
238
            linked_work_item_id = str(linked_work_item.global_id)
×
239
            linked_work_item_uuid = linked_work_item.id
×
240

241
            if linked_work_item_id in work_item_ids:
×
242
                work_item_ids.remove(linked_work_item_id)
×
243
                work_item_uuids.append(linked_work_item_uuid)
×
244

245
                continue
×
246

247
            if self.__config.get_automatic_updation_links_to_test_cases() != 'true':
×
248
                work_item_uuids.append(linked_work_item_uuid)
×
249

250
        for work_item_id in work_item_ids:
×
251
            work_item_uuid = self.__get_work_item_uuid_by_work_item_id(work_item_id)
×
252

253
            if work_item_uuid:
×
254
                work_item_uuids.append(work_item_uuid)
×
255

256
        return work_item_uuids
×
257

258
    @adapter_logger
2✔
259
    def __get_work_item_uuid_by_work_item_id(self, work_item_id: str) -> str or None:
2✔
260
        logging.debug('Getting workitem by id ' + work_item_id)
×
261

262
        try:
×
263
            work_item = self.__work_items_api.get_work_item_by_id(id=work_item_id)
×
264

265
            logging.debug(f'Got workitem {work_item}')
×
266

267
            return work_item.id
×
268
        except Exception as exc:
×
269
            logging.error(f'Getting workitem by id {work_item_id} status: {exc}')
×
270

271
    @adapter_logger
2✔
272
    def __get_work_items_linked_to_autotest(self, autotest_global_id: str) -> typing.List[WorkItemIdentifierModel]:
2✔
273
        return self.__autotest_api.get_work_items_linked_to_auto_test(id=autotest_global_id)
×
274

275
    @adapter_logger
2✔
276
    def __update_autotest_link_from_work_items(self, autotest_global_id: str, work_item_ids: list):
2✔
277
        linked_work_items = self.__get_work_items_linked_to_autotest(autotest_global_id)
×
278

279
        for linked_work_item in linked_work_items:
×
280
            linked_work_item_id = str(linked_work_item.global_id)
×
281

282
            if linked_work_item_id in work_item_ids:
×
283
                work_item_ids.remove(linked_work_item_id)
×
284

285
                continue
×
286

287
            if self.__config.get_automatic_updation_links_to_test_cases() != 'false':
×
288
                self.__unlink_test_to_work_item(autotest_global_id, linked_work_item_id)
×
289

290
        for work_item_id in work_item_ids:
×
291
            self.__link_test_to_work_item(autotest_global_id, work_item_id)
×
292

293
    @adapter_logger
2✔
294
    def __create_test(self, test_result: TestResult) -> str:
2✔
295
        logging.debug(f'Autotest "{test_result.get_autotest_name()}" was not found')
×
296

297
        model = self.__prepare_to_create_autotest(test_result)
×
NEW
298
        model = self._escape_html_in_model(model)
×
299

300
        autotest_response = self.__autotest_api.create_auto_test(auto_test_post_model=model)
×
301

302
        logging.debug(f'Autotest "{test_result.get_autotest_name()}" was created')
×
303

304
        return autotest_response.id
×
305

306
    @adapter_logger
2✔
307
    def __create_tests(self, autotests_for_create: typing.List[AutoTestPostModel]):
2✔
308
        logging.debug(f'Creating autotests: "{autotests_for_create}')
×
309

NEW
310
        autotests_for_create = self._escape_html_in_model(autotests_for_create)
×
UNCOV
311
        self.__autotest_api.create_multiple(auto_test_post_model=autotests_for_create)
×
312

313
        logging.debug(f'Autotests were created')
×
314

315
    @adapter_logger
2✔
316
    def __update_test(self, test_result: TestResult, autotest: AutoTestApiResult):
2✔
317
        logging.debug(f'Autotest "{test_result.get_autotest_name()}" was found')
×
318

319
        model = self.__prepare_to_update_autotest(test_result, autotest)
×
NEW
320
        model = self._escape_html_in_model(model)
×
321

322
        self.__autotest_api.update_auto_test(auto_test_put_model=model)
×
323

324
        logging.debug(f'Autotest "{test_result.get_autotest_name()}" was updated')
×
325

326
    @adapter_logger
2✔
327
    def __update_tests(self, autotests_for_update: typing.List[AutoTestPutModel]):
2✔
328
        logging.debug(f'Updating autotests: {autotests_for_update}')
×
329

NEW
330
        autotests_for_update = self._escape_html_in_model(autotests_for_update)
×
UNCOV
331
        self.__autotest_api.update_multiple(auto_test_put_model=autotests_for_update)
×
332

333
        logging.debug(f'Autotests were updated')
×
334

335
    @adapter_logger
2✔
336
    @retry
2✔
337
    def __unlink_test_to_work_item(self, autotest_global_id: str, work_item_id: str):
2✔
338
        self.__autotest_api.delete_auto_test_link_from_work_item(
×
339
            id=autotest_global_id,
340
            work_item_id=work_item_id)
341

342
        logging.debug(f'Autotest was unlinked with workItem "{work_item_id}" by global id "{autotest_global_id}')
×
343

344
    @adapter_logger
2✔
345
    @retry
2✔
346
    def __link_test_to_work_item(self, autotest_global_id: str, work_item_id: str):
2✔
347
        self.__autotest_api.link_auto_test_to_work_item(
×
348
            autotest_global_id,
349
            work_item_id_model=WorkItemIdModel(id=work_item_id))
350

351
        logging.debug(f'Autotest was linked with workItem "{work_item_id}" by global id "{autotest_global_id}')
×
352

353
    @adapter_logger
2✔
354
    def __load_test_result(self, test_result: TestResult) -> str:
2✔
355
        model = Converter.test_result_to_testrun_result_post_model(
×
356
            test_result,
357
            self.__config.get_configuration_id())
NEW
358
        model = self._escape_html_in_model(model)
×
359

360
        response = self.__test_run_api.set_auto_test_results_for_test_run(
×
361
            id=self.__config.get_test_run_id(),
362
            auto_test_results_for_test_run_model=[model])
363

364
        logging.debug(f'Result of the autotest "{test_result.get_autotest_name()}" was set '
×
365
                      f'in the test run "{self.__config.get_test_run_id()}"')
366

367
        return Converter.get_test_result_id_from_testrun_result_post_response(response)
×
368

369
    @adapter_logger
2✔
370
    def __load_test_results(self, test_results: typing.List[AutoTestResultsForTestRunModel]):
2✔
371
        logging.debug(f'Loading test results: {test_results}')
×
372

NEW
373
        test_results = self._escape_html_in_model(test_results)
×
UNCOV
374
        self.__test_run_api.set_auto_test_results_for_test_run(
×
375
            id=self.__config.get_test_run_id(),
376
            auto_test_results_for_test_run_model=test_results)
377

378
    @adapter_logger
2✔
379
    def get_test_result_by_id(self, test_result_id: str) -> TestResultResponse:
2✔
380
        return self.__test_results_api.api_v2_test_results_id_get(id=test_result_id)
×
381

382
    @adapter_logger
2✔
383
    def update_test_results(self, fixtures_containers: dict, test_result_ids: dict):
2✔
384
        test_results = Converter.fixtures_containers_to_test_results_with_all_fixture_step_results(
×
385
            fixtures_containers, test_result_ids)
386

387
        for test_result in test_results:
×
388
            model = Converter.convert_test_result_model_to_test_results_id_put_request(
×
389
                self.get_test_result_by_id(test_result.get_test_result_id()))
390

391
            model.setup_results = Converter.step_results_to_auto_test_step_result_update_request(
×
392
                    test_result.get_setup_results())
393
            model.teardown_results = Converter.step_results_to_auto_test_step_result_update_request(
×
394
                    test_result.get_teardown_results())
395
            
NEW
396
            model = self._escape_html_in_model(model)
×
397

398
            try:
×
399
                self.__test_results_api.api_v2_test_results_id_put(
×
400
                    id=test_result.get_test_result_id(),
401
                    test_result_update_v2_request=model)
402
            except Exception as exc:
×
403
                logging.error(f'Cannot update test result with id "{test_result.get_test_result_id()}" status: {exc}')
×
404

405
    @adapter_logger
2✔
406
    def load_attachments(self, attach_paths: list or tuple):
2✔
407
        attachments = []
×
408

409
        for path in attach_paths:
×
410
            if os.path.isfile(path):
×
411
                try:
×
412
                    attachment_response = self.__attachments_api.api_v2_attachments_post(
×
413
                        file=path)
414

NEW
415
                    attachment_model = AttachmentPutModel(id=attachment_response.id)
×
NEW
416
                    attachment_model = self._escape_html_in_model(attachment_model)
×
NEW
417
                    attachments.append(attachment_model)
×
418

419
                    logging.debug(f'Attachment "{path}" was uploaded')
×
420
                except Exception as exc:
×
421
                    logging.error(f'Upload attachment "{path}" status: {exc}')
×
422
            else:
423
                logging.error(f'File "{path}" was not found!')
×
424
        return attachments
×
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc