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

testit-tms / adapters-python / 19481714419

18 Nov 2025 09:57PM UTC coverage: 36.992%. Remained the same
19481714419

push

github

web-flow
fix: TMS-36027: fix the parsing of bool cli-parameters. (#217)

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

2 of 8 new or added lines in 4 files covered. (25.0%)

1 existing line in 1 file now uncovered.

1301 of 3517 relevant lines covered (36.99%)

0.74 hits per line

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

30.0
/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 typing import List
2✔
27

28

29
class ApiClientWorker:
2✔
30
    __tests_limit = 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(),
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
    @adapter_logger
2✔
64
    def create_test_run(self, test_run_name: str = None) -> str:
2✔
65
        test_run_name = f'TestRun_{datetime.today().strftime("%Y-%m-%dT%H:%M:%S")}' if \
×
66
            not test_run_name else test_run_name
67
        model = Converter.test_run_to_test_run_short_model(
×
68
            self.__config.get_project_id(),
69
            test_run_name
70
        )
71

72
        response = self.__test_run_api.create_empty(create_empty_request=model)
×
73

74
        return Converter.get_id_from_create_test_run_response(response)
×
75

76
    def get_test_run(self, test_run_id: str) -> TestRunV2ApiResult:
2✔
77
        """Function gets test run and returns test run."""
78
        logging.debug(f"Getting test run by id {test_run_id}")
×
79

80
        test_run = self.__test_run_api.get_test_run_by_id(test_run_id)
×
81
        if test_run is not None:
×
82
            logging.debug(f"Got testrun: {test_run}")
×
83
            return test_run
×
84

85
        logging.error(f"Test run by id {test_run_id} not found!")
×
86
        raise Exception(f"Test run by id {test_run_id} not found!")
×
87

88
    def update_test_run(self, test_run: TestRunV2ApiResult) -> None:
2✔
89
        """Function updates test run."""
90
        model = Converter.build_update_empty_request(test_run)
×
91
        logging.debug(f"Updating test run with model: {model}")
×
92

93
        self.__test_run_api.update_empty(update_empty_request=model)
×
94

95
        logging.debug(f'Updated testrun (ID: {test_run.id})')
×
96

97
    @adapter_logger
2✔
98
    def set_test_run_id(self, test_run_id: str) -> None:
2✔
99
        self.__config.set_test_run_id(test_run_id)
×
100

101
    @adapter_logger
2✔
102
    def get_external_ids_for_test_run_id(self) -> List[str]:
2✔
103
        test_results: List[TestResultShortResponse] = self.__get_test_results()
×
104
        external_ids: List[str] = Converter.get_external_ids_from_autotest_response_list(
×
105
            test_results,
106
            self.__config.get_configuration_id())
107

108
        if len(external_ids) > 0:
×
109
            return external_ids
×
110

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

114
    def __get_test_results(self) -> List[TestResultShortResponse]:
2✔
115
        all_test_results = []
×
116
        skip = 0
×
117
        model: ApiV2TestResultsSearchPostRequest = (
×
118
            Converter.build_test_results_search_post_request_with_in_progress_outcome(
119
                self.__config.get_test_run_id(),
120
                self.__config.get_configuration_id()))
121

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

125
            test_results: List[TestResultShortResponse] = self.__test_results_api.api_v2_test_results_search_post(
×
126
                skip=skip,
127
                take=self.__tests_limit,
128
                api_v2_test_results_search_post_request=model)
129

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

132
            all_test_results.extend(test_results)
×
133
            skip += self.__tests_limit
×
134

135
            if len(test_results) == 0:
×
136
                skip = -1
×
137

138
        return all_test_results
×
139

140
    @adapter_logger
2✔
141
    def __get_autotests_by_external_id(self, external_id: str) -> List[AutoTestApiResult]:
2✔
142
        model = Converter.project_id_and_external_id_to_auto_tests_search_post_request(
×
143
            self.__config.get_project_id(),
144
            external_id)
145

146
        return self.__autotest_api.api_v2_auto_tests_search_post(api_v2_auto_tests_search_post_request=model)
×
147

148
    @adapter_logger
2✔
149
    def write_test(self, test_result: TestResult) -> str:
2✔
150
        model = Converter.project_id_and_external_id_to_auto_tests_search_post_request(
×
151
            self.__config.get_project_id(),
152
            test_result.get_external_id())
153

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

156
        if autotests:
×
157
            self.__update_test(test_result, autotests[0])
×
158

159
            autotest_id = autotests[0].id
×
160

161
            self.__update_autotest_link_from_work_items(autotest_id, test_result.get_work_item_ids())
×
162
        else:
163
            self.__create_test(test_result)
×
164

165
        return self.__load_test_result(test_result)
×
166

167
    @adapter_logger
2✔
168
    def write_tests(self, test_results: List[TestResult], fixture_containers: dict) -> None:
2✔
169
        bulk_autotest_helper = BulkAutotestHelper(self.__autotest_api, self.__test_run_api, self.__config)
×
170

171
        for test_result in test_results:
×
172
            test_result = self.__add_fixtures_to_test_result(test_result, fixture_containers)
×
173

174
            test_result_model = Converter.test_result_to_testrun_result_post_model(
×
175
                test_result,
176
                self.__config.get_configuration_id())
177

178
            work_item_ids_for_link_with_auto_test = self.__get_work_item_uuids_for_link_with_auto_test(
×
179
                test_result.get_work_item_ids())
180

181
            autotests = self.__get_autotests_by_external_id(test_result.get_external_id())
×
182

183
            if autotests:
×
184
                autotest_links_to_wi_for_update = {}
×
185
                autotest_for_update = Converter.prepare_to_mass_update_autotest(
×
186
                    test_result,
187
                    autotests[0],
188
                    self.__config.get_project_id())
189

190
                autotest_id = autotests[0].id
×
191
                autotest_links_to_wi_for_update[autotest_id] = test_result.get_work_item_ids()
×
192

193
                bulk_autotest_helper.add_for_update(
×
194
                    autotest_for_update,
195
                    test_result_model,
196
                    autotest_links_to_wi_for_update)
197
            else:
198
                autotest_for_create = Converter.prepare_to_mass_create_autotest(
×
199
                    test_result,
200
                    self.__config.get_project_id(),
201
                    work_item_ids_for_link_with_auto_test)
202

203
                bulk_autotest_helper.add_for_create(autotest_for_create, test_result_model)
×
204

205
        bulk_autotest_helper.teardown()
×
206

207
    @staticmethod
2✔
208
    @adapter_logger
2✔
209
    def __add_fixtures_to_test_result(
2✔
210
            test_result: TestResult,
211
            fixtures_containers: dict) -> TestResult:
212
        setup_results = []
×
213
        teardown_results = []
×
214

215
        for uuid, fixtures_container in fixtures_containers.items():
×
216
            if test_result.get_external_id() in fixtures_container.external_ids:
×
217
                if fixtures_container.befores:
×
218
                    setup_results += fixtures_container.befores[0].steps
×
219

220
                if fixtures_container.afters:
×
221
                    teardown_results = fixtures_container.afters[0].steps + teardown_results
×
222

223
        test_result.set_setup_results(setup_results)
×
224
        test_result.set_teardown_results(teardown_results)
×
225

226
        return test_result
×
227

228
    @adapter_logger
2✔
229
    def __get_work_item_uuids_for_link_with_auto_test(
2✔
230
            self,
231
            work_item_ids: List[str],
232
            autotest_global_id: str = None) -> List[str]:
233
        linked_work_items = []
×
234

235
        if autotest_global_id:
×
236
            linked_work_items = self.__get_work_items_linked_to_autotest(autotest_global_id)
×
237

238
        work_item_uuids = self.__prepare_list_of_work_item_uuids(linked_work_items, work_item_ids)
×
239

240
        return work_item_uuids
×
241

242
    @adapter_logger
2✔
243
    def __prepare_list_of_work_item_uuids(
2✔
244
            self,
245
            linked_work_items: List[WorkItemIdentifierModel],
246
            work_item_ids: List[str]) -> List[str]:
247
        work_item_uuids = []
×
248

249
        for linked_work_item in linked_work_items:
×
250
            linked_work_item_id = str(linked_work_item.global_id)
×
251
            linked_work_item_uuid = linked_work_item.id
×
252

253
            if linked_work_item_id in work_item_ids:
×
254
                work_item_ids.remove(linked_work_item_id)
×
255
                work_item_uuids.append(linked_work_item_uuid)
×
256

257
                continue
×
258

NEW
259
            if not self.__config.get_automatic_updation_links_to_test_cases():
×
260
                work_item_uuids.append(linked_work_item_uuid)
×
261

262
        for work_item_id in work_item_ids:
×
263
            work_item_uuid = self.__get_work_item_uuid_by_work_item_id(work_item_id)
×
264

265
            if work_item_uuid:
×
266
                work_item_uuids.append(work_item_uuid)
×
267

268
        return work_item_uuids
×
269

270
    @adapter_logger
2✔
271
    def __get_work_item_uuid_by_work_item_id(self, work_item_id: str) -> str or None:
2✔
272
        logging.debug('Getting workitem by id ' + work_item_id)
×
273

274
        try:
×
275
            work_item = self.__work_items_api.get_work_item_by_id(id=work_item_id)
×
276

277
            logging.debug(f'Got workitem {work_item}')
×
278

279
            return work_item.id
×
280
        except Exception as exc:
×
281
            logging.error(f'Getting workitem by id {work_item_id} status: {exc}')
×
282

283
    @adapter_logger
2✔
284
    def __get_work_items_linked_to_autotest(self, autotest_global_id: str) -> List[WorkItemIdentifierModel]:
2✔
285
        return self.__autotest_api.get_work_items_linked_to_auto_test(id=autotest_global_id)
×
286

287
    @adapter_logger
2✔
288
    def __update_autotest_link_from_work_items(self, autotest_global_id: str, work_item_ids: list):
2✔
289
        linked_work_items = self.__get_work_items_linked_to_autotest(autotest_global_id)
×
290

291
        for linked_work_item in linked_work_items:
×
292
            linked_work_item_id = str(linked_work_item.global_id)
×
293

294
            if linked_work_item_id in work_item_ids:
×
295
                work_item_ids.remove(linked_work_item_id)
×
296

297
                continue
×
298

NEW
299
            if self.__config.get_automatic_updation_links_to_test_cases():
×
300
                self.__unlink_test_to_work_item(autotest_global_id, linked_work_item_id)
×
301

302
        for work_item_id in work_item_ids:
×
303
            self.__link_test_to_work_item(autotest_global_id, work_item_id)
×
304

305
    @adapter_logger
2✔
306
    def __create_test(self, test_result: TestResult) -> str:
2✔
307
        logging.debug(f'Autotest "{test_result.get_autotest_name()}" was not found')
×
308

309
        work_item_ids_for_link_with_auto_test = self.__get_work_item_uuids_for_link_with_auto_test(
×
310
            test_result.get_work_item_ids())
311

312
        model = Converter.prepare_to_create_autotest(
×
313
            test_result,
314
            self.__config.get_project_id(),
315
            work_item_ids_for_link_with_auto_test)
316

317
        autotest_response = self.__autotest_api.create_auto_test(create_auto_test_request=model)
×
318

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

321
        return autotest_response.id
×
322

323
    @adapter_logger
2✔
324
    def __create_tests(self, autotests_for_create: List[AutoTestPostModel]) -> None:
2✔
325
        logging.debug(f'Creating autotests: "{autotests_for_create}')
×
326

327
        self.__autotest_api.create_multiple(auto_test_post_model=autotests_for_create)
×
328

329
        logging.debug(f'Autotests were created')
×
330

331
    @adapter_logger
2✔
332
    def __update_test(self, test_result: TestResult, autotest: AutoTestApiResult) -> None:
2✔
333
        logging.debug(f'Autotest "{test_result.get_autotest_name()}" was found')
×
334

335
        model = Converter.prepare_to_update_autotest(test_result, autotest, self.__config.get_project_id())
×
336

337
        try:
×
338
            self.__autotest_api.update_auto_test(update_auto_test_request=model)
×
339
        except Exception as exc:
×
340
            logging.error(f'Cannot update autotest "{test_result.get_autotest_name()}" status: {exc}')
×
341

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

344
    @adapter_logger
2✔
345
    def __update_tests(self, autotests_for_update: List[AutoTestPutModel]) -> None:
2✔
346
        logging.debug(f'Updating autotests: {autotests_for_update}')
×
347

348
        self.__autotest_api.update_multiple(auto_test_put_model=autotests_for_update)
×
349

350
        logging.debug(f'Autotests were updated')
×
351

352
    @adapter_logger
2✔
353
    @retry
2✔
354
    def __unlink_test_to_work_item(self, autotest_global_id: str, work_item_id: str) -> None:
2✔
355
        self.__autotest_api.delete_auto_test_link_from_work_item(
×
356
            id=autotest_global_id,
357
            work_item_id=work_item_id)
358

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

361
    @adapter_logger
2✔
362
    @retry
2✔
363
    def __link_test_to_work_item(self, autotest_global_id: str, work_item_id: str) -> None:
2✔
364
        self.__autotest_api.link_auto_test_to_work_item(
×
365
            autotest_global_id,
366
            link_auto_test_to_work_item_request=LinkAutoTestToWorkItemRequest(id=work_item_id))
367

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

370
    @adapter_logger
2✔
371
    def __load_test_result(self, test_result: TestResult) -> str:
2✔
372
        model = Converter.test_result_to_testrun_result_post_model(
×
373
            test_result,
374
            self.__config.get_configuration_id())
375

376
        response = self.__test_run_api.set_auto_test_results_for_test_run(
×
377
            id=self.__config.get_test_run_id(),
378
            auto_test_results_for_test_run_model=[model])
379

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

383
        return Converter.get_test_result_id_from_testrun_result_post_response(response)
×
384

385
    @adapter_logger
2✔
386
    def get_test_result_by_id(self, test_result_id: str) -> TestResultResponse:
2✔
387
        return self.__test_results_api.api_v2_test_results_id_get(id=test_result_id)
×
388

389
    @adapter_logger
2✔
390
    def update_test_results(self, fixtures_containers: dict, test_result_ids: dict) -> None:
2✔
391
        test_results = Converter.fixtures_containers_to_test_results_with_all_fixture_step_results(
×
392
            fixtures_containers, test_result_ids)
393

394
        for test_result in test_results:
×
395
            model = Converter.convert_test_result_model_to_test_results_id_put_request(
×
396
                self.get_test_result_by_id(test_result.get_test_result_id()))
397

398
            model.setup_results = Converter.step_results_to_auto_test_step_result_update_request(
×
399
                    test_result.get_setup_results())
400
            model.teardown_results = Converter.step_results_to_auto_test_step_result_update_request(
×
401
                    test_result.get_teardown_results())
402

403
            try:
×
404
                self.__test_results_api.api_v2_test_results_id_put(
×
405
                    id=test_result.get_test_result_id(),
406
                    api_v2_test_results_id_put_request=model)
407
            except Exception as exc:
×
408
                logging.error(f'Cannot update test result with id "{test_result.get_test_result_id()}" status: {exc}')
×
409

410
    @adapter_logger
2✔
411
    def load_attachments(self, attach_paths: list or tuple) -> List[AttachmentPutModel]:
2✔
412
        attachments = []
×
413

414
        for path in attach_paths:
×
415
            if os.path.isfile(path):
×
416
                try:
×
417
                    attachment_response = self.__attachments_api.api_v2_attachments_post(file=open(path, "rb"))
×
418

419
                    attachments.append(AttachmentPutModel(attachment_response['id']))
×
420

421
                    logging.debug(f'Attachment "{path}" was uploaded')
×
422
                except Exception as exc:
×
423
                    logging.error(f'Upload attachment "{path}" status: {exc}')
×
424
            else:
425
                logging.error(f'File "{path}" was not found!')
×
426
        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