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

testit-tms / adapters-python / 17062786569

19 Aug 2025 07:33AM UTC coverage: 36.773% (+0.3%) from 36.441%
17062786569

Pull #199

github

web-flow
Merge b947c0c07 into e79fbf989
Pull Request #199: fix: fix updating autotest links to workitems.

49 of 143 new or added lines in 3 files covered. (34.27%)

1 existing line in 1 file now uncovered.

1233 of 3353 relevant lines covered (36.77%)

0.74 hits per line

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

32.6
/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.apis import AttachmentsApi, AutoTestsApi, TestRunsApi, TestResultsApi, WorkItemsApi
2✔
8
from testit_api_client.models import (
2✔
9
    AutoTestApiResult,
10
    AutoTestPostModel,
11
    AutoTestPutModel,
12
    UpdateAutoTestRequest,
13
    AttachmentPutModel,
14
    AutoTestResultsForTestRunModel,
15
    TestResultResponse,
16
    WorkItemIdModel,
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

28

29
class ApiClientWorker:
2✔
30
    __max_tests_for_write = 100
2✔
31

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

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

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

53
        return api_client_configuration
×
54

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

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

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

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

80
        return Converter.get_id_from_create_test_run_response(response)
×
81

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

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

90
        return Converter.get_resolved_autotests_from_get_test_run_response(
×
91
            response,
92
            self.__config.get_configuration_id())
93

94
    @adapter_logger
2✔
95
    def __get_autotests_by_external_id(self, external_id: str) -> list:
2✔
NEW
96
        model = Converter.project_id_and_external_id_to_auto_tests_search_post_request(
×
97
            self.__config.get_project_id(),
98
            external_id)
99

NEW
100
        return self.__autotest_api.api_v2_auto_tests_search_post(api_v2_auto_tests_search_post_request=model)
×
101

102
    @adapter_logger
2✔
103
    def write_test(self, test_result: TestResult):
2✔
104
        model = Converter.project_id_and_external_id_to_auto_tests_search_post_request(
×
105
            self.__config.get_project_id(),
106
            test_result.get_external_id())
107

108
        autotests = self.__autotest_api.api_v2_auto_tests_search_post(api_v2_auto_tests_search_post_request=model)
×
109

110
        if autotests:
×
111
            self.__update_test(test_result, autotests[0])
×
112

NEW
113
            autotest_id = autotests[0].id
×
114

NEW
115
            self.__update_autotest_link_from_work_items(autotest_id, test_result.get_work_item_ids())
×
116
        else:
117
            self.__create_test(test_result)
×
118

119
        return self.__load_test_result(test_result)
×
120

121
    @adapter_logger
2✔
122
    def write_tests(self, test_results: typing.List[TestResult], fixture_containers: dict):
2✔
NEW
123
        bulk_autotest_helper = BulkAutotestHelper(self.__autotest_api, self.__test_run_api, self.__config)
×
124

125
        for test_result in test_results:
×
126
            test_result = self.__add_fixtures_to_test_result(test_result, fixture_containers)
×
127

128
            test_result_model = Converter.test_result_to_testrun_result_post_model(
×
129
                test_result,
130
                self.__config.get_configuration_id())
131

NEW
132
            work_item_ids_for_link_with_auto_test = self.__get_work_item_uuids_for_link_with_auto_test(
×
133
                test_result.get_work_item_ids())
134

NEW
135
            autotests = self.__get_autotests_by_external_id(test_result.get_external_id())
×
136

NEW
137
            if autotests:
×
NEW
138
                autotest_links_to_wi_for_update = {}
×
NEW
139
                autotest_for_update = Converter.prepare_to_mass_update_autotest(
×
140
                    test_result,
141
                    autotests[0],
142
                    self.__config.get_project_id())
143

NEW
144
                autotest_id = autotests[0].id
×
NEW
145
                autotest_links_to_wi_for_update[autotest_id] = test_result.get_work_item_ids()
×
146

NEW
147
                bulk_autotest_helper.add_for_update(
×
148
                    autotest_for_update,
149
                    test_result_model,
150
                    autotest_links_to_wi_for_update)
151
            else:
NEW
152
                autotest_for_create = Converter.prepare_to_mass_create_autotest(
×
153
                    test_result,
154
                    self.__config.get_project_id(),
155
                    work_item_ids_for_link_with_auto_test)
156

NEW
157
                bulk_autotest_helper.add_for_create(autotest_for_create, test_result_model)
×
158

NEW
159
        bulk_autotest_helper.teardown()
×
160

161
    @staticmethod
2✔
162
    @adapter_logger
2✔
163
    def __add_fixtures_to_test_result(
2✔
164
            test_result: TestResult,
165
            fixtures_containers: dict) -> TestResult:
166
        setup_results = []
×
167
        teardown_results = []
×
168

169
        for uuid, fixtures_container in fixtures_containers.items():
×
170
            if test_result.get_external_id() in fixtures_container.external_ids:
×
171
                if fixtures_container.befores:
×
172
                    setup_results += fixtures_container.befores[0].steps
×
173

174
                if fixtures_container.afters:
×
175
                    teardown_results = fixtures_container.afters[0].steps + teardown_results
×
176

177
        test_result.set_setup_results(setup_results)
×
178
        test_result.set_teardown_results(teardown_results)
×
179

180
        return test_result
×
181

182
    @adapter_logger
2✔
183
    def __get_work_item_uuids_for_link_with_auto_test(
2✔
184
            self,
185
            work_item_ids: list,
186
            autotest_global_id: str = None) -> list:
187
        linked_work_items = []
×
188

189
        if autotest_global_id:
×
190
            linked_work_items = self.__get_work_items_linked_to_autotest(autotest_global_id)
×
191

192
        work_item_uuids = self.__prepare_list_of_work_item_uuids(linked_work_items, work_item_ids)
×
193

194
        return work_item_uuids
×
195

196
    @adapter_logger
2✔
197
    def __prepare_list_of_work_item_uuids(
2✔
198
            self,
199
            linked_work_items: list,
200
            work_item_ids: list) -> list:
201
        work_item_uuids = []
×
202

203
        for linked_work_item in linked_work_items:
×
204
            linked_work_item_id = str(linked_work_item.global_id)
×
205
            linked_work_item_uuid = linked_work_item.id
×
206

207
            if linked_work_item_id in work_item_ids:
×
208
                work_item_ids.remove(linked_work_item_id)
×
209
                work_item_uuids.append(linked_work_item_uuid)
×
210

211
                continue
×
212

213
            if self.__config.get_automatic_updation_links_to_test_cases() != 'true':
×
214
                work_item_uuids.append(linked_work_item_uuid)
×
215

216
        for work_item_id in work_item_ids:
×
217
            work_item_uuid = self.__get_work_item_uuid_by_work_item_id(work_item_id)
×
218

219
            if work_item_uuid:
×
220
                work_item_uuids.append(work_item_uuid)
×
221

222
        return work_item_uuids
×
223

224
    @adapter_logger
2✔
225
    def __get_work_item_uuid_by_work_item_id(self, work_item_id: str) -> str or None:
2✔
226
        logging.debug('Getting workitem by id ' + work_item_id)
×
227

228
        try:
×
229
            work_item = self.__work_items_api.get_work_item_by_id(id=work_item_id)
×
230

231
            logging.debug(f'Got workitem {work_item}')
×
232

233
            return work_item.id
×
234
        except Exception as exc:
×
235
            logging.error(f'Getting workitem by id {work_item_id} status: {exc}')
×
236

237
    @adapter_logger
2✔
238
    def __get_work_items_linked_to_autotest(self, autotest_global_id: str) -> typing.List[WorkItemIdentifierModel]:
2✔
239
        return self.__autotest_api.get_work_items_linked_to_auto_test(id=autotest_global_id)
×
240

241
    @adapter_logger
2✔
242
    def __update_autotest_link_from_work_items(self, autotest_global_id: str, work_item_ids: list):
2✔
243
        linked_work_items = self.__get_work_items_linked_to_autotest(autotest_global_id)
×
244

245
        for linked_work_item in linked_work_items:
×
246
            linked_work_item_id = str(linked_work_item.global_id)
×
247

248
            if linked_work_item_id in work_item_ids:
×
249
                work_item_ids.remove(linked_work_item_id)
×
250

251
                continue
×
252

253
            if self.__config.get_automatic_updation_links_to_test_cases() != 'false':
×
254
                self.__unlink_test_to_work_item(autotest_global_id, linked_work_item_id)
×
255

256
        for work_item_id in work_item_ids:
×
257
            self.__link_test_to_work_item(autotest_global_id, work_item_id)
×
258

259
    @adapter_logger
2✔
260
    def __create_test(self, test_result: TestResult) -> str:
2✔
261
        logging.debug(f'Autotest "{test_result.get_autotest_name()}" was not found')
×
262

NEW
263
        work_item_ids_for_link_with_auto_test = self.__get_work_item_uuids_for_link_with_auto_test(
×
264
            test_result.get_work_item_ids())
265

NEW
266
        model = Converter.prepare_to_create_autotest(
×
267
            test_result,
268
            self.__config.get_project_id(),
269
            work_item_ids_for_link_with_auto_test)
UNCOV
270
        model = self._escape_html_in_model(model)
×
271

272
        autotest_response = self.__autotest_api.create_auto_test(create_auto_test_request=model)
×
273

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

276
        return autotest_response.id
×
277

278
    @adapter_logger
2✔
279
    def __create_tests(self, autotests_for_create: typing.List[AutoTestPostModel]):
2✔
280
        logging.debug(f'Creating autotests: "{autotests_for_create}')
×
281

282
        autotests_for_create = self._escape_html_in_model(autotests_for_create)
×
283
        self.__autotest_api.create_multiple(auto_test_post_model=autotests_for_create)
×
284

285
        logging.debug(f'Autotests were created')
×
286

287
    @adapter_logger
2✔
288
    def __update_test(self, test_result: TestResult, autotest: AutoTestApiResult):
2✔
289
        logging.debug(f'Autotest "{test_result.get_autotest_name()}" was found')
×
290

NEW
291
        model = Converter.prepare_to_update_autotest(test_result, autotest)
×
292
        model = self._escape_html_in_model(model)
×
293

294
        try:
×
295
            self.__autotest_api.update_auto_test(update_auto_test_request=model)
×
296
        except Exception as exc:
×
297
            logging.error(f'Cannot update autotest "{test_result.get_autotest_name()}" status: {exc}')
×
298

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

301
    @adapter_logger
2✔
302
    def __update_tests(self, autotests_for_update: typing.List[AutoTestPutModel]):
2✔
303
        logging.debug(f'Updating autotests: {autotests_for_update}')
×
304

305
        autotests_for_update = self._escape_html_in_model(autotests_for_update)
×
306
        self.__autotest_api.update_multiple(auto_test_put_model=autotests_for_update)
×
307

308
        logging.debug(f'Autotests were updated')
×
309

310
    @adapter_logger
2✔
311
    @retry
2✔
312
    def __unlink_test_to_work_item(self, autotest_global_id: str, work_item_id: str):
2✔
313
        self.__autotest_api.delete_auto_test_link_from_work_item(
×
314
            id=autotest_global_id,
315
            work_item_id=work_item_id)
316

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

319
    @adapter_logger
2✔
320
    @retry
2✔
321
    def __link_test_to_work_item(self, autotest_global_id: str, work_item_id: str):
2✔
322
        self.__autotest_api.link_auto_test_to_work_item(
×
323
            autotest_global_id,
324
            work_item_id_model=WorkItemIdModel(id=work_item_id))
325

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

328
    @adapter_logger
2✔
329
    def __load_test_result(self, test_result: TestResult) -> str:
2✔
330
        model = Converter.test_result_to_testrun_result_post_model(
×
331
            test_result,
332
            self.__config.get_configuration_id())
333
        model = self._escape_html_in_model(model)
×
334

335
        response = self.__test_run_api.set_auto_test_results_for_test_run(
×
336
            id=self.__config.get_test_run_id(),
337
            auto_test_results_for_test_run_model=[model])
338

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

342
        return Converter.get_test_result_id_from_testrun_result_post_response(response)
×
343

344
    @adapter_logger
2✔
345
    def __load_test_results(self, test_results: typing.List[AutoTestResultsForTestRunModel]):
2✔
346
        logging.debug(f'Loading test results: {test_results}')
×
347

348
        test_results = self._escape_html_in_model(test_results)
×
349
        self.__test_run_api.set_auto_test_results_for_test_run(
×
350
            id=self.__config.get_test_run_id(),
351
            auto_test_results_for_test_run_model=test_results)
352

353
    @adapter_logger
2✔
354
    def get_test_result_by_id(self, test_result_id: str) -> TestResultResponse:
2✔
355
        return self.__test_results_api.api_v2_test_results_id_get(id=test_result_id)
×
356

357
    @adapter_logger
2✔
358
    def update_test_results(self, fixtures_containers: dict, test_result_ids: dict):
2✔
359
        test_results = Converter.fixtures_containers_to_test_results_with_all_fixture_step_results(
×
360
            fixtures_containers, test_result_ids)
361

362
        for test_result in test_results:
×
363
            model = Converter.convert_test_result_model_to_test_results_id_put_request(
×
364
                self.get_test_result_by_id(test_result.get_test_result_id()))
365

366
            model.setup_results = Converter.step_results_to_auto_test_step_result_update_request(
×
367
                    test_result.get_setup_results())
368
            model.teardown_results = Converter.step_results_to_auto_test_step_result_update_request(
×
369
                    test_result.get_teardown_results())
370
            
371
            model = self._escape_html_in_model(model)
×
372

373
            try:
×
374
                self.__test_results_api.api_v2_test_results_id_put(
×
375
                    id=test_result.get_test_result_id(),
376
                    api_v2_test_results_id_put_request=model)
377
            except Exception as exc:
×
378
                logging.error(f'Cannot update test result with id "{test_result.get_test_result_id()}" status: {exc}')
×
379

380
    @adapter_logger
2✔
381
    def load_attachments(self, attach_paths: list or tuple):
2✔
382
        attachments = []
×
383

384
        for path in attach_paths:
×
385
            if os.path.isfile(path):
×
386
                try:
×
387
                    attachment_response = self.__attachments_api.api_v2_attachments_post(file=open(path, "rb"))
×
388

389
                    attachments.append(AttachmentPutModel(attachment_response['id']))
×
390

391
                    logging.debug(f'Attachment "{path}" was uploaded')
×
392
                except Exception as exc:
×
393
                    logging.error(f'Upload attachment "{path}" status: {exc}')
×
394
            else:
395
                logging.error(f'File "{path}" was not found!')
×
396
        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