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

testit-tms / adapters-python / 17916648770

22 Sep 2025 01:20PM UTC coverage: 40.025% (+3.0%) from 37.068%
17916648770

push

github

web-flow
feat: TMS-33268: support the "status code" field. (#200)

* feat: TMS-33268: support the "status code" field.

* fix: add the types of input and return values.

* fix: fix the names of the methods for api_client and converter.

* feat: support the AutotestExternalId field from the TestResultShortResponse model.

---------

Co-authored-by: pavel.butuzov <pavel.butuzov@testit.software>

29 of 57 new or added lines in 5 files covered. (50.88%)

3 existing lines in 2 files now uncovered.

1280 of 3198 relevant lines covered (40.03%)

0.8 hits per line

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

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

5
from testit_api_client import ApiClient, Configuration
2✔
6
from testit_api_client.apis import AttachmentsApi, AutoTestsApi, TestRunsApi, TestResultsApi, WorkItemsApi
2✔
7
from testit_api_client.models import (
2✔
8
    ApiV2TestResultsSearchPostRequest,
9
    AutoTestApiResult,
10
    AutoTestPostModel,
11
    AutoTestPutModel,
12
    AttachmentPutModel,
13
    ApiV2AutoTestsSearchPostRequest,
14
    TestResultResponse,
15
    TestResultShortResponse,
16
    LinkAutoTestToWorkItemRequest,
17
    WorkItemIdentifierModel
18
)
19

20
from testit_python_commons.client.client_configuration import ClientConfiguration
2✔
21
from testit_python_commons.client.converter import Converter
2✔
22
from testit_python_commons.client.helpers.bulk_autotest_helper import BulkAutotestHelper
2✔
23
from testit_python_commons.models.test_result import TestResult
2✔
24
from testit_python_commons.services.logger import adapter_logger
2✔
25
from testit_python_commons.services.retry import retry
2✔
26
from testit_python_commons.utils.html_escape_utils import HtmlEscapeUtils
2✔
27
from typing import List, Any
2✔
28

29

30
class ApiClientWorker:
2✔
31
    __tests_limit = 100
2✔
32

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

40
        self.__test_run_api = TestRunsApi(api_client=api_client)
×
41
        self.__autotest_api = AutoTestsApi(api_client=api_client)
×
42
        self.__attachments_api = AttachmentsApi(api_client=api_client)
×
43
        self.__test_results_api = TestResultsApi(api_client=api_client)
×
44
        self.__work_items_api = WorkItemsApi(api_client=api_client)
×
45
        self.__config = config
×
46

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

54
        return api_client_configuration
×
55

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

64
    @staticmethod
2✔
65
    def _escape_html_in_model(model: Any) -> Any:
2✔
66
        """Apply HTML escaping to all models before sending to API"""
67
        return HtmlEscapeUtils.escape_html_in_object(model)
×
68

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

79
        response = self.__test_run_api.create_empty(create_empty_request=model)
×
80

81
        return Converter.get_id_from_create_test_run_response(response)
×
82

83
    @adapter_logger
2✔
84
    def set_test_run_id(self, test_run_id: str) -> None:
2✔
85
        self.__config.set_test_run_id(test_run_id)
×
86

87
    @adapter_logger
2✔
88
    def get_external_ids_for_test_run_id(self) -> List[str]:
2✔
NEW
89
        test_results: List[TestResultShortResponse] = self.__get_test_results()
×
NEW
90
        external_ids: List[str] = Converter.get_external_ids_from_autotest_response_list(
×
91
            test_results,
92
            self.__config.get_configuration_id())
93

NEW
94
        if len(external_ids) > 0:
×
NEW
95
            return external_ids
×
96

NEW
97
        raise Exception('The autotests with the status "InProgress" ' +
×
98
                        f'and the configuration id "{self.__config.get_configuration_id()}" were not found!')
99

100
    def __get_test_results(self) -> List[TestResultShortResponse]:
2✔
NEW
101
        all_test_results = []
×
NEW
102
        skip = 0
×
NEW
103
        model: ApiV2TestResultsSearchPostRequest = (
×
104
            Converter.build_test_results_search_post_request_with_in_progress_outcome(
105
                self.__config.get_test_run_id(),
106
                self.__config.get_configuration_id()))
107

NEW
108
        while skip >= 0:
×
NEW
109
            logging.debug(f"Getting test results with limit {self.__tests_limit}: {model}")
×
110

NEW
111
            test_results: List[TestResultShortResponse] = self.__test_results_api.api_v2_test_results_search_post(
×
112
                skip=skip,
113
                take=self.__tests_limit,
114
                api_v2_test_results_search_post_request=model)
115

NEW
116
            logging.debug(f"Got {len(test_results)} test results: {test_results}")
×
117

NEW
118
            all_test_results.extend(test_results)
×
NEW
119
            skip += self.__tests_limit
×
120

NEW
121
            if len(test_results) == 0:
×
NEW
122
                skip = -1
×
123

NEW
124
        return all_test_results
×
125

126
    @adapter_logger
2✔
127
    def __get_autotests_by_external_id(self, external_id: str) -> List[AutoTestApiResult]:
2✔
128
        model = Converter.project_id_and_external_id_to_auto_tests_search_post_request(
×
129
            self.__config.get_project_id(),
130
            external_id)
131

132
        return self.__autotest_api.api_v2_auto_tests_search_post(api_v2_auto_tests_search_post_request=model)
×
133

134
    @adapter_logger
2✔
135
    def write_test(self, test_result: TestResult) -> str:
2✔
136
        model = Converter.project_id_and_external_id_to_auto_tests_search_post_request(
×
137
            self.__config.get_project_id(),
138
            test_result.get_external_id())
139

140
        autotests = self.__autotest_api.api_v2_auto_tests_search_post(api_v2_auto_tests_search_post_request=model)
×
141

142
        if autotests:
×
143
            self.__update_test(test_result, autotests[0])
×
144

145
            autotest_id = autotests[0].id
×
146

147
            self.__update_autotest_link_from_work_items(autotest_id, test_result.get_work_item_ids())
×
148
        else:
149
            self.__create_test(test_result)
×
150

151
        return self.__load_test_result(test_result)
×
152

153
    @adapter_logger
2✔
154
    def write_tests(self, test_results: List[TestResult], fixture_containers: dict) -> None:
2✔
155
        bulk_autotest_helper = BulkAutotestHelper(self.__autotest_api, self.__test_run_api, self.__config)
×
156

157
        for test_result in test_results:
×
158
            test_result = self.__add_fixtures_to_test_result(test_result, fixture_containers)
×
159

160
            test_result_model = Converter.test_result_to_testrun_result_post_model(
×
161
                test_result,
162
                self.__config.get_configuration_id())
163

164
            work_item_ids_for_link_with_auto_test = self.__get_work_item_uuids_for_link_with_auto_test(
×
165
                test_result.get_work_item_ids())
166

167
            autotests = self.__get_autotests_by_external_id(test_result.get_external_id())
×
168

169
            if autotests:
×
170
                autotest_links_to_wi_for_update = {}
×
171
                autotest_for_update = Converter.prepare_to_mass_update_autotest(
×
172
                    test_result,
173
                    autotests[0],
174
                    self.__config.get_project_id())
175

176
                autotest_id = autotests[0].id
×
177
                autotest_links_to_wi_for_update[autotest_id] = test_result.get_work_item_ids()
×
178

179
                bulk_autotest_helper.add_for_update(
×
180
                    autotest_for_update,
181
                    test_result_model,
182
                    autotest_links_to_wi_for_update)
183
            else:
184
                autotest_for_create = Converter.prepare_to_mass_create_autotest(
×
185
                    test_result,
186
                    self.__config.get_project_id(),
187
                    work_item_ids_for_link_with_auto_test)
188

189
                bulk_autotest_helper.add_for_create(autotest_for_create, test_result_model)
×
190

191
        bulk_autotest_helper.teardown()
×
192

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

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

206
                if fixtures_container.afters:
×
207
                    teardown_results = fixtures_container.afters[0].steps + teardown_results
×
208

209
        test_result.set_setup_results(setup_results)
×
210
        test_result.set_teardown_results(teardown_results)
×
211

212
        return test_result
×
213

214
    @adapter_logger
2✔
215
    def __get_work_item_uuids_for_link_with_auto_test(
2✔
216
            self,
217
            work_item_ids: List[str],
218
            autotest_global_id: str = None) -> List[str]:
UNCOV
219
        linked_work_items = []
×
220

221
        if autotest_global_id:
×
222
            linked_work_items = self.__get_work_items_linked_to_autotest(autotest_global_id)
×
223

224
        work_item_uuids = self.__prepare_list_of_work_item_uuids(linked_work_items, work_item_ids)
×
225

226
        return work_item_uuids
×
227

228
    @adapter_logger
2✔
229
    def __prepare_list_of_work_item_uuids(
2✔
230
            self,
231
            linked_work_items: List[WorkItemIdentifierModel],
232
            work_item_ids: List[str]) -> List[str]:
UNCOV
233
        work_item_uuids = []
×
234

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

239
            if linked_work_item_id in work_item_ids:
×
240
                work_item_ids.remove(linked_work_item_id)
×
241
                work_item_uuids.append(linked_work_item_uuid)
×
242

243
                continue
×
244

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

248
        for work_item_id in work_item_ids:
×
249
            work_item_uuid = self.__get_work_item_uuid_by_work_item_id(work_item_id)
×
250

251
            if work_item_uuid:
×
252
                work_item_uuids.append(work_item_uuid)
×
253

254
        return work_item_uuids
×
255

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

260
        try:
×
261
            work_item = self.__work_items_api.get_work_item_by_id(id=work_item_id)
×
262

263
            logging.debug(f'Got workitem {work_item}')
×
264

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

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

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

277
        for linked_work_item in linked_work_items:
×
278
            linked_work_item_id = str(linked_work_item.global_id)
×
279

280
            if linked_work_item_id in work_item_ids:
×
281
                work_item_ids.remove(linked_work_item_id)
×
282

283
                continue
×
284

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

288
        for work_item_id in work_item_ids:
×
289
            self.__link_test_to_work_item(autotest_global_id, work_item_id)
×
290

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

295
        work_item_ids_for_link_with_auto_test = self.__get_work_item_uuids_for_link_with_auto_test(
×
296
            test_result.get_work_item_ids())
297

298
        model = Converter.prepare_to_create_autotest(
×
299
            test_result,
300
            self.__config.get_project_id(),
301
            work_item_ids_for_link_with_auto_test)
302
        model = self._escape_html_in_model(model)
×
303

304
        autotest_response = self.__autotest_api.create_auto_test(create_auto_test_request=model)
×
305

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

308
        return autotest_response.id
×
309

310
    @adapter_logger
2✔
311
    def __create_tests(self, autotests_for_create: List[AutoTestPostModel]) -> None:
2✔
312
        logging.debug(f'Creating autotests: "{autotests_for_create}')
×
313

314
        autotests_for_create = self._escape_html_in_model(autotests_for_create)
×
315
        self.__autotest_api.create_multiple(auto_test_post_model=autotests_for_create)
×
316

317
        logging.debug(f'Autotests were created')
×
318

319
    @adapter_logger
2✔
320
    def __update_test(self, test_result: TestResult, autotest: AutoTestApiResult) -> None:
2✔
321
        logging.debug(f'Autotest "{test_result.get_autotest_name()}" was found')
×
322

323
        model = Converter.prepare_to_update_autotest(test_result, autotest, self.__config.get_project_id())
×
324
        model = self._escape_html_in_model(model)
×
325

326
        try:
×
327
            self.__autotest_api.update_auto_test(update_auto_test_request=model)
×
328
        except Exception as exc:
×
329
            logging.error(f'Cannot update autotest "{test_result.get_autotest_name()}" status: {exc}')
×
330

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

333
    @adapter_logger
2✔
334
    def __update_tests(self, autotests_for_update: List[AutoTestPutModel]) -> None:
2✔
335
        logging.debug(f'Updating autotests: {autotests_for_update}')
×
336

337
        autotests_for_update = self._escape_html_in_model(autotests_for_update)
×
338
        self.__autotest_api.update_multiple(auto_test_put_model=autotests_for_update)
×
339

340
        logging.debug(f'Autotests were updated')
×
341

342
    @adapter_logger
2✔
343
    @retry
2✔
344
    def __unlink_test_to_work_item(self, autotest_global_id: str, work_item_id: str) -> None:
2✔
345
        self.__autotest_api.delete_auto_test_link_from_work_item(
×
346
            id=autotest_global_id,
347
            work_item_id=work_item_id)
348

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

351
    @adapter_logger
2✔
352
    @retry
2✔
353
    def __link_test_to_work_item(self, autotest_global_id: str, work_item_id: str) -> None:
2✔
354
        self.__autotest_api.link_auto_test_to_work_item(
×
355
            autotest_global_id,
356
            link_auto_test_to_work_item_request=LinkAutoTestToWorkItemRequest(id=work_item_id))
357

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

360
    @adapter_logger
2✔
361
    def __load_test_result(self, test_result: TestResult) -> str:
2✔
362
        model = Converter.test_result_to_testrun_result_post_model(
×
363
            test_result,
364
            self.__config.get_configuration_id())
365
        model = self._escape_html_in_model(model)
×
366

367
        response = self.__test_run_api.set_auto_test_results_for_test_run(
×
368
            id=self.__config.get_test_run_id(),
369
            auto_test_results_for_test_run_model=[model])
370

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

374
        return Converter.get_test_result_id_from_testrun_result_post_response(response)
×
375

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

380
    @adapter_logger
2✔
381
    def update_test_results(self, fixtures_containers: dict, test_result_ids: dict) -> None:
2✔
382
        test_results = Converter.fixtures_containers_to_test_results_with_all_fixture_step_results(
×
383
            fixtures_containers, test_result_ids)
384

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

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

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

403
    @adapter_logger
2✔
404
    def load_attachments(self, attach_paths: list or tuple) -> List[AttachmentPutModel]:
2✔
405
        attachments = []
×
406

407
        for path in attach_paths:
×
408
            if os.path.isfile(path):
×
409
                try:
×
410
                    attachment_response = self.__attachments_api.api_v2_attachments_post(file=open(path, "rb"))
×
411

412
                    attachments.append(AttachmentPutModel(attachment_response['id']))
×
413

414
                    logging.debug(f'Attachment "{path}" was uploaded')
×
415
                except Exception as exc:
×
416
                    logging.error(f'Upload attachment "{path}" status: {exc}')
×
417
            else:
418
                logging.error(f'File "{path}" was not found!')
×
419
        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