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

testit-tms / adapters-python / 18900873859

29 Oct 2025 07:54AM UTC coverage: 36.921% (+0.03%) from 36.89%
18900873859

Pull #211

github

web-flow
Merge 26623bc01 into b45a2cdad
Pull Request #211: feat: TMS-35016: support for updating the test run name for all adapt…

32 of 68 new or added lines in 4 files covered. (47.06%)

75 existing lines in 1 file now uncovered.

1307 of 3540 relevant lines covered (36.92%)

0.74 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
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
    TestResultResponse,
14
    TestResultShortResponse,
15
    TestRunV2ApiResult,
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, test_run_name: str = None) -> str:
2✔
71
        test_run_name = f'TestRun_{datetime.today().strftime("%Y-%m-%dT%H:%M:%S")}' if \
×
72
            not test_run_name else 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
    def get_test_run(self, test_run_id: str) -> TestRunV2ApiResult:
2✔
84
        """Function gets test run and returns test run."""
NEW
85
        logging.debug(f"Getting test run by id {test_run_id}")
×
86

NEW
87
        test_run = self.__test_run_api.get_test_run_by_id(test_run_id)
×
NEW
88
        if test_run is not None:
×
NEW
89
            logging.debug(f"Got testrun: {test_run}")
×
NEW
90
            return test_run
×
91

NEW
92
        logging.error(f"Test run by id {test_run_id} not found!")
×
NEW
93
        raise Exception(f"Test run by id {test_run_id} not found!")
×
94

95
    def update_test_run(self, test_run: TestRunV2ApiResult) -> None:
2✔
96
        """Function updates test run."""
NEW
97
        model = Converter.build_update_empty_request(test_run)
×
NEW
98
        model = HtmlEscapeUtils.escape_html_in_object(model)
×
NEW
99
        logging.debug(f"Updating test run with model: {model}")
×
100

NEW
101
        self.__test_run_api.update_empty(update_empty_request=model)
×
102

NEW
103
        logging.debug(f'Updated testrun (ID: {test_run.id})')
×
104

105
    @adapter_logger
2✔
106
    def set_test_run_id(self, test_run_id: str) -> None:
2✔
107
        self.__config.set_test_run_id(test_run_id)
×
108

109
    @adapter_logger
2✔
110
    def get_external_ids_for_test_run_id(self) -> List[str]:
2✔
111
        test_results: List[TestResultShortResponse] = self.__get_test_results()
×
112
        external_ids: List[str] = Converter.get_external_ids_from_autotest_response_list(
×
113
            test_results,
114
            self.__config.get_configuration_id())
115

116
        if len(external_ids) > 0:
×
117
            return external_ids
×
118

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

122
    def __get_test_results(self) -> List[TestResultShortResponse]:
2✔
123
        all_test_results = []
×
124
        skip = 0
×
125
        model: ApiV2TestResultsSearchPostRequest = (
×
126
            Converter.build_test_results_search_post_request_with_in_progress_outcome(
127
                self.__config.get_test_run_id(),
128
                self.__config.get_configuration_id()))
129

130
        while skip >= 0:
×
131
            logging.debug(f"Getting test results with limit {self.__tests_limit}: {model}")
×
132

133
            test_results: List[TestResultShortResponse] = self.__test_results_api.api_v2_test_results_search_post(
×
134
                skip=skip,
135
                take=self.__tests_limit,
136
                api_v2_test_results_search_post_request=model)
137

138
            logging.debug(f"Got {len(test_results)} test results: {test_results}")
×
139

140
            all_test_results.extend(test_results)
×
141
            skip += self.__tests_limit
×
142

143
            if len(test_results) == 0:
×
144
                skip = -1
×
145

146
        return all_test_results
×
147

148
    @adapter_logger
2✔
149
    def __get_autotests_by_external_id(self, external_id: str) -> List[AutoTestApiResult]:
2✔
150
        model = Converter.project_id_and_external_id_to_auto_tests_search_post_request(
×
151
            self.__config.get_project_id(),
152
            external_id)
153

154
        return self.__autotest_api.api_v2_auto_tests_search_post(api_v2_auto_tests_search_post_request=model)
×
155

156
    @adapter_logger
2✔
157
    def write_test(self, test_result: TestResult) -> str:
2✔
158
        model = Converter.project_id_and_external_id_to_auto_tests_search_post_request(
×
159
            self.__config.get_project_id(),
160
            test_result.get_external_id())
161

162
        autotests = self.__autotest_api.api_v2_auto_tests_search_post(api_v2_auto_tests_search_post_request=model)
×
163

164
        if autotests:
×
165
            self.__update_test(test_result, autotests[0])
×
166

167
            autotest_id = autotests[0].id
×
168

169
            self.__update_autotest_link_from_work_items(autotest_id, test_result.get_work_item_ids())
×
170
        else:
171
            self.__create_test(test_result)
×
172

173
        return self.__load_test_result(test_result)
×
174

175
    @adapter_logger
2✔
176
    def write_tests(self, test_results: List[TestResult], fixture_containers: dict) -> None:
2✔
177
        bulk_autotest_helper = BulkAutotestHelper(self.__autotest_api, self.__test_run_api, self.__config)
×
178

179
        for test_result in test_results:
×
180
            test_result = self.__add_fixtures_to_test_result(test_result, fixture_containers)
×
181

182
            test_result_model = Converter.test_result_to_testrun_result_post_model(
×
183
                test_result,
184
                self.__config.get_configuration_id())
185

186
            work_item_ids_for_link_with_auto_test = self.__get_work_item_uuids_for_link_with_auto_test(
×
187
                test_result.get_work_item_ids())
188

189
            autotests = self.__get_autotests_by_external_id(test_result.get_external_id())
×
190

191
            if autotests:
×
192
                autotest_links_to_wi_for_update = {}
×
193
                autotest_for_update = Converter.prepare_to_mass_update_autotest(
×
194
                    test_result,
195
                    autotests[0],
196
                    self.__config.get_project_id())
197

198
                autotest_id = autotests[0].id
×
199
                autotest_links_to_wi_for_update[autotest_id] = test_result.get_work_item_ids()
×
200

201
                bulk_autotest_helper.add_for_update(
×
202
                    autotest_for_update,
203
                    test_result_model,
204
                    autotest_links_to_wi_for_update)
205
            else:
206
                autotest_for_create = Converter.prepare_to_mass_create_autotest(
×
207
                    test_result,
208
                    self.__config.get_project_id(),
209
                    work_item_ids_for_link_with_auto_test)
210

211
                bulk_autotest_helper.add_for_create(autotest_for_create, test_result_model)
×
212

213
        bulk_autotest_helper.teardown()
×
214

215
    @staticmethod
2✔
216
    @adapter_logger
2✔
217
    def __add_fixtures_to_test_result(
2✔
218
            test_result: TestResult,
219
            fixtures_containers: dict) -> TestResult:
220
        setup_results = []
×
221
        teardown_results = []
×
222

223
        for uuid, fixtures_container in fixtures_containers.items():
×
224
            if test_result.get_external_id() in fixtures_container.external_ids:
×
225
                if fixtures_container.befores:
×
226
                    setup_results += fixtures_container.befores[0].steps
×
227

228
                if fixtures_container.afters:
×
229
                    teardown_results = fixtures_container.afters[0].steps + teardown_results
×
230

231
        test_result.set_setup_results(setup_results)
×
232
        test_result.set_teardown_results(teardown_results)
×
233

234
        return test_result
×
235

236
    @adapter_logger
2✔
237
    def __get_work_item_uuids_for_link_with_auto_test(
2✔
238
            self,
239
            work_item_ids: List[str],
240
            autotest_global_id: str = None) -> List[str]:
241
        linked_work_items = []
×
242

243
        if autotest_global_id:
×
244
            linked_work_items = self.__get_work_items_linked_to_autotest(autotest_global_id)
×
245

246
        work_item_uuids = self.__prepare_list_of_work_item_uuids(linked_work_items, work_item_ids)
×
247

248
        return work_item_uuids
×
249

250
    @adapter_logger
2✔
251
    def __prepare_list_of_work_item_uuids(
2✔
252
            self,
253
            linked_work_items: List[WorkItemIdentifierModel],
254
            work_item_ids: List[str]) -> List[str]:
255
        work_item_uuids = []
×
256

257
        for linked_work_item in linked_work_items:
×
258
            linked_work_item_id = str(linked_work_item.global_id)
×
259
            linked_work_item_uuid = linked_work_item.id
×
260

261
            if linked_work_item_id in work_item_ids:
×
262
                work_item_ids.remove(linked_work_item_id)
×
263
                work_item_uuids.append(linked_work_item_uuid)
×
264

265
                continue
×
266

267
            if self.__config.get_automatic_updation_links_to_test_cases() != 'true':
×
268
                work_item_uuids.append(linked_work_item_uuid)
×
269

270
        for work_item_id in work_item_ids:
×
271
            work_item_uuid = self.__get_work_item_uuid_by_work_item_id(work_item_id)
×
272

273
            if work_item_uuid:
×
274
                work_item_uuids.append(work_item_uuid)
×
275

276
        return work_item_uuids
×
277

278
    @adapter_logger
2✔
279
    def __get_work_item_uuid_by_work_item_id(self, work_item_id: str) -> str or None:
2✔
280
        logging.debug('Getting workitem by id ' + work_item_id)
×
281

282
        try:
×
283
            work_item = self.__work_items_api.get_work_item_by_id(id=work_item_id)
×
284

285
            logging.debug(f'Got workitem {work_item}')
×
286

287
            return work_item.id
×
288
        except Exception as exc:
×
289
            logging.error(f'Getting workitem by id {work_item_id} status: {exc}')
×
290

291
    @adapter_logger
2✔
292
    def __get_work_items_linked_to_autotest(self, autotest_global_id: str) -> List[WorkItemIdentifierModel]:
2✔
293
        return self.__autotest_api.get_work_items_linked_to_auto_test(id=autotest_global_id)
×
294

295
    @adapter_logger
2✔
296
    def __update_autotest_link_from_work_items(self, autotest_global_id: str, work_item_ids: list):
2✔
297
        linked_work_items = self.__get_work_items_linked_to_autotest(autotest_global_id)
×
298

299
        for linked_work_item in linked_work_items:
×
300
            linked_work_item_id = str(linked_work_item.global_id)
×
301

302
            if linked_work_item_id in work_item_ids:
×
303
                work_item_ids.remove(linked_work_item_id)
×
304

305
                continue
×
306

307
            if self.__config.get_automatic_updation_links_to_test_cases() != 'false':
×
308
                self.__unlink_test_to_work_item(autotest_global_id, linked_work_item_id)
×
309

310
        for work_item_id in work_item_ids:
×
311
            self.__link_test_to_work_item(autotest_global_id, work_item_id)
×
312

313
    @adapter_logger
2✔
314
    def __create_test(self, test_result: TestResult) -> str:
2✔
315
        logging.debug(f'Autotest "{test_result.get_autotest_name()}" was not found')
×
316

317
        work_item_ids_for_link_with_auto_test = self.__get_work_item_uuids_for_link_with_auto_test(
×
318
            test_result.get_work_item_ids())
319

320
        model = Converter.prepare_to_create_autotest(
×
321
            test_result,
322
            self.__config.get_project_id(),
323
            work_item_ids_for_link_with_auto_test)
324
        model = self._escape_html_in_model(model)
×
325

326
        autotest_response = self.__autotest_api.create_auto_test(create_auto_test_request=model)
×
327

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

330
        return autotest_response.id
×
331

332
    @adapter_logger
2✔
333
    def __create_tests(self, autotests_for_create: List[AutoTestPostModel]) -> None:
2✔
334
        logging.debug(f'Creating autotests: "{autotests_for_create}')
×
335

336
        autotests_for_create = self._escape_html_in_model(autotests_for_create)
×
337
        self.__autotest_api.create_multiple(auto_test_post_model=autotests_for_create)
×
338

339
        logging.debug(f'Autotests were created')
×
340

341
    @adapter_logger
2✔
342
    def __update_test(self, test_result: TestResult, autotest: AutoTestApiResult) -> None:
2✔
343
        logging.debug(f'Autotest "{test_result.get_autotest_name()}" was found')
×
344

345
        model = Converter.prepare_to_update_autotest(test_result, autotest, self.__config.get_project_id())
×
346
        model = self._escape_html_in_model(model)
×
347

348
        try:
×
349
            self.__autotest_api.update_auto_test(update_auto_test_request=model)
×
350
        except Exception as exc:
×
351
            logging.error(f'Cannot update autotest "{test_result.get_autotest_name()}" status: {exc}')
×
352

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

355
    @adapter_logger
2✔
356
    def __update_tests(self, autotests_for_update: List[AutoTestPutModel]) -> None:
2✔
357
        logging.debug(f'Updating autotests: {autotests_for_update}')
×
358

359
        autotests_for_update = self._escape_html_in_model(autotests_for_update)
×
360
        self.__autotest_api.update_multiple(auto_test_put_model=autotests_for_update)
×
361

362
        logging.debug(f'Autotests were updated')
×
363

364
    @adapter_logger
2✔
365
    @retry
2✔
366
    def __unlink_test_to_work_item(self, autotest_global_id: str, work_item_id: str) -> None:
2✔
367
        self.__autotest_api.delete_auto_test_link_from_work_item(
×
368
            id=autotest_global_id,
369
            work_item_id=work_item_id)
370

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

373
    @adapter_logger
2✔
374
    @retry
2✔
375
    def __link_test_to_work_item(self, autotest_global_id: str, work_item_id: str) -> None:
2✔
376
        self.__autotest_api.link_auto_test_to_work_item(
×
377
            autotest_global_id,
378
            link_auto_test_to_work_item_request=LinkAutoTestToWorkItemRequest(id=work_item_id))
379

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

382
    @adapter_logger
2✔
383
    def __load_test_result(self, test_result: TestResult) -> str:
2✔
384
        model = Converter.test_result_to_testrun_result_post_model(
×
385
            test_result,
386
            self.__config.get_configuration_id())
387
        model = self._escape_html_in_model(model)
×
388

389
        response = self.__test_run_api.set_auto_test_results_for_test_run(
×
390
            id=self.__config.get_test_run_id(),
391
            auto_test_results_for_test_run_model=[model])
392

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

396
        return Converter.get_test_result_id_from_testrun_result_post_response(response)
×
397

398
    @adapter_logger
2✔
399
    def get_test_result_by_id(self, test_result_id: str) -> TestResultResponse:
2✔
400
        return self.__test_results_api.api_v2_test_results_id_get(id=test_result_id)
×
401

402
    @adapter_logger
2✔
403
    def update_test_results(self, fixtures_containers: dict, test_result_ids: dict) -> None:
2✔
404
        test_results = Converter.fixtures_containers_to_test_results_with_all_fixture_step_results(
×
405
            fixtures_containers, test_result_ids)
406

407
        for test_result in test_results:
×
408
            model = Converter.convert_test_result_model_to_test_results_id_put_request(
×
409
                self.get_test_result_by_id(test_result.get_test_result_id()))
410

411
            model.setup_results = Converter.step_results_to_auto_test_step_result_update_request(
×
412
                    test_result.get_setup_results())
413
            model.teardown_results = Converter.step_results_to_auto_test_step_result_update_request(
×
414
                    test_result.get_teardown_results())
415
            
416
            model = self._escape_html_in_model(model)
×
417

418
            try:
×
419
                self.__test_results_api.api_v2_test_results_id_put(
×
420
                    id=test_result.get_test_result_id(),
421
                    api_v2_test_results_id_put_request=model)
422
            except Exception as exc:
×
423
                logging.error(f'Cannot update test result with id "{test_result.get_test_result_id()}" status: {exc}')
×
424

425
    @adapter_logger
2✔
426
    def load_attachments(self, attach_paths: list or tuple) -> List[AttachmentPutModel]:
2✔
427
        attachments = []
×
428

429
        for path in attach_paths:
×
430
            if os.path.isfile(path):
×
431
                try:
×
432
                    attachment_response = self.__attachments_api.api_v2_attachments_post(file=open(path, "rb"))
×
433

434
                    attachments.append(AttachmentPutModel(attachment_response['id']))
×
435

436
                    logging.debug(f'Attachment "{path}" was uploaded')
×
437
                except Exception as exc:
×
438
                    logging.error(f'Upload attachment "{path}" status: {exc}')
×
439
            else:
440
                logging.error(f'File "{path}" was not found!')
×
441
        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