How to use scenario_keywords method in Gherkin-python

Best Python code snippet using gherkin-python

Run Gherkin-python automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

testlinkapi_offline_test.py

Source: testlinkapi_offline_test.py Github

copy
1#! /usr/bin/python
2# -*- coding: UTF-8 -*-
3
4#  Copyright 2012-2019 Luiko Czub, TestLink-API-Python-client developers
5#
6#  Licensed under the Apache License, Version 2.0 (the "License");
7#  you may not use this file except in compliance with the License.
8#  You may obtain a copy of the License at
9#
10#       http://www.apache.org/licenses/LICENSE-2.0
11#
12#  Unless required by applicable law or agreed to in writing, software
13#  distributed under the License is distributed on an "AS IS" BASIS,
14#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15#  See the License for the specific language governing permissions and
16#  limitations under the License.
17#
18# ------------------------------------------------------------------------
19
20# this test works WITHOUT an online TestLink Server
21# no calls are send to a TestLink Server
22
23import sys
24import unittest
25
26if sys.version_info[0] == 2 and sys.version_info[1] == 7:
27    # py27 and py31 assertRaisesRegexp was renamed in py32 to assertRaisesRegex
28    unittest.TestCase.assertRaisesRegex = unittest.TestCase.assertRaisesRegexp
29
30from testlink import TestlinkAPIClient, TestLinkHelper
31from testlink.testlinkerrors import TLArgError
32
33# scenario_a includes response from a testlink 1.9.3 server
34SCENARIO_A = {'getProjects' : [
35               {'opt': {'requirementsEnabled': 0, 'testPriorityEnabled': 1, 
36                        'automationEnabled': 1, 'inventoryEnabled': 0}, 
37                'prefix': 'NPROAPI', 'name': 'NEW_PROJECT_API', 'color': '', 
38                'notes': 'This is a Project created with the API', 
39                'option_priority': '0', 
40                'options': 'O:8:"stdClass":4:{s:19:"requirementsEnabled";i:0;s:19:"testPriorityEnabled";i:1;s:17:"automationEnabled";i:1;s:16:"inventoryEnabled";i:0;}', 
41                'tc_counter': '2', 'option_reqs': '0', 'active': '1', 
42                'is_public': '1', 'id': '21', 'option_automation': '0'}, 
43               {'opt': {'requirementsEnabled': 1, 'testPriorityEnabled': 1, 
44                        'automationEnabled': 1, 'inventoryEnabled': 1}, 
45                'prefix': 'TP', 'name': 'TestProject', 'color': '', 
46                'notes': '<p>Initiales TestProject, um &nbsp;TestLink kennen zu lernen</p>', 
47                'option_priority': '0', 
48                'options': 'O:8:"stdClass":4:{s:19:"requirementsEnabled";i:1;s:19:"testPriorityEnabled";i:1;s:17:"automationEnabled";i:1;s:16:"inventoryEnabled";i:1;}', 
49                'tc_counter': '0', 'option_reqs': '0', 'active': '1', 
50                'is_public': '1', 'id': '1', 'option_automation': '0'}],
51              'getProjectTestPlans' : {
52                '21' : [{'name': 'TestPlan_API', 
53                         'notes': 'New TestPlan created with the API', 
54                         'active': '1', 'is_public': '1', 
55                         'testproject_id': '21', 'id': '22'},
56                        {'name': 'TestPlan_NoSuite', 
57                         'notes': 'TestPlan with No Suites and No Platforms', 
58                         'active': '1', 'is_public': '1', 
59                         'testproject_id': '21', 'id': '222'}] ,
60                '1' : '' },
61              'getFirstLevelTestSuitesForTestProject' : {
62                '21' :  [{'node_type_id': '2', 'name': 'A - First Level', 
63                          'parent_id': '21', 'node_order': '0', 
64                          'node_table': 'testsuites', 'id': '23'}, 
65                         {'node_type_id': '2', 'name': 'B - First Level', 
66                          'parent_id': '21', 'node_order': '0', 
67                          'node_table': 'testsuites', 'id': '24'}],
68                '1' : [{'message': '(getFirstLevelTestSuitesForTestProject) - Test Project (TestProject) is empty.', 
69                        'code': 7008}] },
70              'getTestSuitesForTestPlan' : {'22' : '', '222' : ''},
71              'getTestCasesForTestPlan' : {'22' : '', '222' : ''},
72              # TL(1.9.3)->getTestSuitesForTestSuite really returns {...} and not [{....}] !!!
73              'getTestSuitesForTestSuite' : {
74                '23' : {'node_type_id': '2', 'name': 'AA - Second Level', 
75                        'parent_id': '23', 'node_order': '0', 
76                        'details': 'Details of the Test Suite AA', 'id': '25'},
77                '24' : ''},
78              'getTestCasesForTestSuite' : {
79                '23' : [{'node_type_id': '3', 'tcversion_id': '25', 
80                         'name': 'TESTCASE_AA', 'parent_id': '25', 
81                         'node_order': '0', 'node_table': 'testcases', 
82                         'external_id': 'NPROAPI-1', 'id': '26'}],
83                '24' : [{'node_type_id': '3', 'tcversion_id': '24', 
84                         'name': 'TESTCASE_B', 'parent_id': '24', 
85                         'node_order': '0', 'node_table': 'testcases', 
86                         'external_id': 'NPROAPI-2', 'id': '33'}],
87                '25' : [{'node_type_id': '3', 'tcversion_id': '25', 
88                         'name': 'TESTCASE_AA', 'parent_id': '25', 
89                         'node_order': '0', 'node_table': 'testcases', 
90                         'external_id': 'NPROAPI-1',  'id': '26'}]
91                 },
92              'getTestPlanPlatforms' : {
93                '22' : [{'notes': '', 'id': '1', 'name': 'dutch'}, {'notes': '', 'id': '2', 'name': 'platt'}],
94                '222' : [{'message': 'Test plan (name:TestPlan_API) has no platforms linked', 
95                         'code': 3041}]},
96              'getBuildsForTestPlan' : {'22' : '', '222' : ''},
97              'getTestCaseIDByName' : {
98                'dictResult' :  {'1': {'parent_id': '24', 'tc_external_id': '2', 
99                                       'id': '33', 'tsuite_name': 'B - First Level', 
100                                       'name': 'TESTCASE_B'}}, 
101                'listResult' : [{'parent_id': '25', 'tc_external_id': '1', 
102                                 'id': '26', 'tsuite_name': 'AA - Second Level', 
103                                 'name': 'TESTCASE_AA'}]},
104              'getTestCase' : {
105                '26-1' : [{'full_tc_external_id': 'NPROAPI-1', 'node_order': '0', 'is_open': '1', 'id': '27', 
106                         'author_last_name': 'LkaTlinkD7', 'updater_login': '', 'layout': '1', 'tc_external_id': '1', 
107                         'version': '1', 'estimated_exec_duration': '', 'testsuite_id': '25', 'updater_id': '', 
108                         'status': '1', 'updater_first_name': '', 'testcase_id': '26', 'author_first_name': 'Tester', 
109                         'importance': '2', 'modification_ts': '', 'execution_type': '1', 'preconditions': 'V1', 
110                         'active': '1', 'creation_ts': '2013-12-26 21:17:43', 'name': 'TC-C', 'summary': 'SumSumSum', 
111                         'updater_last_name': '', 
112                         'steps': [{'step_number': '1', 'actions': 'Step action 1', 'execution_type': '2', 'active': '1', 
113                                    'id': '5101', 'expected_results': 'Step result 1'}], 
114                         'author_id': '3', 'author_login': 'tester'}],
115                '26-2' : [{'full_tc_external_id': 'NPROAPI-1', 'node_order': '0', 'is_open': '1', 'id': '127', 
116                         'author_last_name': 'LkaTlinkD7', 'updater_login': '', 'layout': '1', 'tc_external_id': '1', 
117                         'version': '2', 'estimated_exec_duration': '', 'testsuite_id': '25', 'updater_id': '', 
118                         'status': '1', 'updater_first_name': '', 'testcase_id': '26', 'author_first_name': 'Tester', 
119                         'importance': '2', 'modification_ts': '', 'execution_type': '1', 'preconditions': 'V2', 
120                         'active': '1', 'creation_ts': '2013-12-26 22:17:43', 'name': 'TC-C', 'summary': 'SumSumSum', 
121                         'updater_last_name': '', 
122                         'steps': [{'step_number': '1', 'actions': 'Step action 1', 'execution_type': '2', 'active': '1', 
123                                    'id': '5101', 'expected_results': 'Step result 1'}], 
124                         'author_id': '3', 'author_login': 'tester'}],
125                '26-None' : [{'full_tc_external_id': 'NPROAPI-1', 'node_order': '0', 'is_open': '1', 'id': '127', 
126                         'author_last_name': 'LkaTlinkD7', 'updater_login': '', 'layout': '1', 'tc_external_id': '1', 
127                         'version': '2', 'estimated_exec_duration': '', 'testsuite_id': '25', 'updater_id': '', 
128                         'status': '1', 'updater_first_name': '', 'testcase_id': '26', 'author_first_name': 'Tester', 
129                         'importance': '2', 'modification_ts': '', 'execution_type': '1', 'preconditions': 'V2 None', 
130                         'active': '1', 'creation_ts': '2013-12-26 22:17:43', 'name': 'TC-C', 'summary': 'SumSumSum', 
131                         'updater_last_name': '', 
132                         'steps': [{'step_number': '1', 'actions': 'Step action 1', 'execution_type': '2', 'active': '1', 
133                                    'id': '5101', 'expected_results': 'Step result 1'}], 
134                         'author_id': '3', 'author_login': 'tester'}]
135                               
136                               },
137              'getFullPath' : {
138                               
139                26 : {'26' : ['NEW_PROJECT_API', 'A - First Level', 'AA - Second Level']},
140                4711 : {'4711' : ['OLD_PROJECT_API']},
141                    },
142              'getTestProjectByName' : {
143                'NEW_PROJECT_API' : {
144                    'prefix': 'NPROAPI', 'name': 'NEW_PROJECT_API', 'color': '',
145                    'notes': 'This is a Project created with the API', 
146                    'is_public': '1', 'id': '21', 'option_automation': '0'},
147                'OLD_PROJECT_API' : {
148                     'prefix': 'OPROAPI', 'name': 'OLD_PROJECT_API', 'color': '',
149                    'notes': 'This is a Project created with the API', 
150                    'is_public': '1', 'id': '2211', 'option_automation': '0'},
151                    },
152              'createTestCase' : 'dummy response createTestCase',
153              'reportTCResult' :  [{'status': True, 'operation': 'reportTCResult', 
154                                    'message': 'Success!', 'overwrite': False, 'id': '773'}]              
155
156              }
157
158SCENARIO_STEPS = {'createTestCase' : ['noRealReponseData - ok for step tests']}
159
160# scenario_keywords defines response with keywords
161SCENARIO_KEYWORDS = {'getTestCasesForTestSuite' : {
162                    'noTestCase' : [] ,
163                    
164                     'deepTrue1' : [{'node_order': '0', 'is_open': '1', 
165                        'keywords': {'3': {'keyword_id': '3', 'notes': 'a third key word', 'testcase_id': '8136', 'keyword': 'KeyWord03'}}, 
166                        'id': '8136', 'node_type_id': '3', 'layout': '1', 'tc_external_id': '1', 'parent_id': '8135', 'version': '1', 
167                        'estimated_exec_duration': '', 'updater_id': '2', 'status': '1', 'tsuite_name': 'AA - Second Level', 
168                        'importance': '2', 'modification_ts': '2014-07-01 21:21:59', 'execution_type': '2', 
169                        'preconditions': '<p>\n\tthese are the preconditions</p>\n', 'active': '1', 'creation_ts': '2014-06-28 22:06:17', 
170                        'node_table': 'testcases', 'tcversion_id': '8137', 'name': 'TESTCASE_AA', 
171                        'summary': '<p>\n\tThis is the summary of the Test Case AA</p>\n', 
172                        'steps': [{'step_number': '1', 'actions': 'Step action 1 - aa', 'execution_type': '1', 'active': '1', 'id': '8138', 'expected_results': 'Step result 1 - aa'}, 
173                                  {'step_number': '2', 'actions': 'Step action 2 - aa', 'execution_type': '1', 'active': '1', 'id': '8139', 'expected_results': 'Step result 2 - aa'}, 
174                                  {'step_number': '3', 'actions': 'Step action 3 - aa', 'execution_type': '1', 'active': '1', 'id': '8140', 'expected_results': 'Step result 3 - aa'}, 
175                                  {'step_number': '4', 'actions': 'Step action 4 - aa', 'execution_type': '1', 'active': '1', 'id': '8141', 'expected_results': 'Step result 4 - aa'}, 
176                                  {'step_number': '5', 'actions': 'Step action 5 - aa', 'execution_type': '1', 'active': '1', 'id': '8142', 'expected_results': 'Step result 5 - aa'}], 
177                        'author_id': '1', 'external_id': 'GPROAPI10-1'}],
178                    
179                    'deepFalse3' :  [{'node_order': '0', 'is_open': '1', 
180                        'keywords': {'1': {'keyword_id': '1', 'notes': 'a key word', 'testcase_id': '8144', 'keyword': 'KeyWord01'}, 
181                                     '3': {'keyword_id': '3', 'notes': 'a third key word', 'testcase_id': '8144', 'keyword': 'KeyWord03'}}, 
182                        'id': '8144', 'node_type_id': '3', 'layout': '1', 'tc_external_id': '2', 'parent_id': '8134', 'version': '1', 
183                        'details': '<p>\n\tDetails of the Test Suite B</p>\n', 'estimated_exec_duration': '3.00', 'updater_id': '2', 'status': '1', 
184                        'importance': '3', 'modification_ts': '2014-06-30 20:45:40', 'execution_type': '1', 
185                        'preconditions': '<p>\n\tthese are the preconditions</p>\n', 'active': '1', 'creation_ts': '2014-06-28 22:06:17', 
186                        'node_table': 'testcases', 'tcversion_id': '8145', 'name': 'TESTCASE_B', 
187                        'summary': '<p>\n\tThis is the summary of the Test Case B</p>\n', 
188                        'steps': [{'step_number': '1', 'actions': 'Step action 1 -b ', 'execution_type': '2', 'active': '1', 'id': '8151', 'expected_results': 'Step result 1 - b'}, 
189                                  {'step_number': '2', 'actions': 'Step action 2 -b ', 'execution_type': '2', 'active': '1', 'id': '8152', 'expected_results': 'Step result 2 - b'}, 
190                                  {'step_number': '3', 'actions': 'action 3 createTestCaseSteps.update', 'execution_type': '2', 'active': '1', 'id': '8153', 'expected_results': 'update - cause step 3 already exist'}, 
191                                  {'step_number': '4', 'actions': 'Step action 4 -b ', 'execution_type': '2', 'active': '1', 'id': '8154', 'expected_results': 'Step result 4 - b'}, 
192                                  {'step_number': '5', 'actions': 'Step action 5 -b changed by updateTestCase', 'execution_type': '2', 'active': '1', 'id': '8155', 'expected_results': 'Step result 5 - b changed'}, 
193                                  {'step_number': '6', 'actions': 'Step action 6 -b added by updateTestCase', 'execution_type': '2', 'active': '1', 'id': '8156', 'expected_results': 'Step result 6 - b added'}, 
194                                  {'step_number': '7', 'actions': 'action 7 createTestCaseSteps.create', 'execution_type': '2', 'active': '1', 'id': '8157', 'expected_results': 'create - cause step 7 not yet exist'}, 
195                                  {'step_number': '8', 'actions': 'action 8 createTestCaseSteps.update', 'execution_type': '2', 'active': '1', 'id': '8158', 'expected_results': 'create - cause step 8 not yet exist'}], 
196                        'author_id': '1'}, 
197                                     {'node_order': '1', 'is_open': '1', 
198                        'keywords': {'2': {'keyword_id': '2', 'notes': 'another key word', 'testcase_id': '8159', 'keyword': 'KeyWord02'}}, 
199                        'id': '8159', 'node_type_id': '3', 'layout': '1', 'tc_external_id': '3', 'parent_id': '8134', 'version': '1', 
200                        'details': '<p>\n\tDetails of the Test Suite B</p>\n', 'estimated_exec_duration': '3.00', 'updater_id': '2', 'status': '1', 
201                        'importance': '3', 'modification_ts': '2014-07-02 21:03:02', 'execution_type': '1', 
202                        'preconditions': '<p>\n\tthese are the preconditions</p>\n', 'active': '1', 'creation_ts': '2014-07-02 20:53:45', 
203                        'node_table': 'testcases', 'tcversion_id': '8160', 'name': 'TESTCASE_B2', 
204                        'summary': '<p>\n\tThis is the summary of the Test Case B2</p>\n', 
205                        'steps': [{'step_number': '1', 'actions': '<p>\n\tStep action 1 -b2</p>\n', 'execution_type': '2', 'active': '1', 'id': '8161', 'expected_results': '<p>\n\tStep result 1 - b2</p>\n'}, 
206                                  {'step_number': '2', 'actions': '<p>\n\tStep action 2 -b2</p>\n', 'execution_type': '2', 'active': '1', 'id': '8162', 'expected_results': '<p>\n\tStep result 2 - b2</p>\n'}], 
207                        'author_id': '2'}, 
208                                     {'node_order': '2', 'is_open': '1', 
209                     'id': '8169', 'node_type_id': '3', 'layout': '1', 'tc_external_id': '4', 'parent_id': '8134', 'version': '1', 
210                     'details': '<p>\n\tDetails of the Test Suite B</p>\n', 'estimated_exec_duration': '3.00', 'updater_id': '2', 'status': '1', 
211                     'importance': '3', 'modification_ts': '2014-07-02 21:02:23', 'execution_type': '1', 
212                     'preconditions': '<p>\n\tthese are the preconditions</p>\n', 'active': '1', 'creation_ts': '2014-07-02 20:55:46', 
213                     'node_table': 'testcases', 'tcversion_id': '8170', 'name': 'TESTCASE_B3', 
214                     'summary': '<p>\n\tThis is the summary of the Test Case B3</p>\n', 
215                     'steps': [{'step_number': '1', 'actions': '<p>\n\tStep action 1 -b3</p>\n', 'execution_type': '2', 'active': '1', 'id': '8171', 'expected_results': '<p>\n\tStep result 1 - b3</p>\n'}, 
216                               {'step_number': '2', 'actions': '<p>\n\tStep action 2 -b3</p>\n', 'execution_type': '2', 'active': '1', 'id': '8172', 'expected_results': '<p>\n\tStep result 2 - b3</p>\n'}], 
217                     'author_id': '2'}],
218                                                   
219                '4711' :  [{'node_order': '0', 'is_open': '1', 
220                        'keywords': {'1': {'keyword_id': '1', 'notes': 'a key word', 'testcase_id': '8144', 'keyword': 'KeyWord01'}, 
221                                     '3': {'keyword_id': '3', 'notes': 'a third key word', 'testcase_id': '8144', 'keyword': 'KeyWord03'}}, 
222                        'id': '8144', 'node_type_id': '3', 'layout': '1', 'tc_external_id': '2', 'parent_id': '8134', 'version': '1', 
223                        'details': '<p>\n\tDetails of the Test Suite B</p>\n', 'estimated_exec_duration': '3.00', 'updater_id': '2', 'status': '1', 
224                        'importance': '3', 'modification_ts': '2014-06-30 20:45:40', 'execution_type': '1', 
225                        'preconditions': '<p>\n\tthese are the preconditions</p>\n', 'active': '1', 'creation_ts': '2014-06-28 22:06:17', 
226                        'node_table': 'testcases', 'tcversion_id': '8145', 'name': 'TESTCASE_B', 
227                        'summary': '<p>\n\tThis is the summary of the Test Case B</p>\n', 
228                        'steps': [{'step_number': '1', 'actions': 'Step action 1 -b ', 'execution_type': '2', 'active': '1', 'id': '8151', 'expected_results': 'Step result 1 - b'}], 
229                        'author_id': '1'} ],
230
231                'noKeywords' :  [{'node_order': '0', 'is_open': '1', 
232                        'id': '8144', 'node_type_id': '3', 'layout': '1', 'tc_external_id': '2', 'parent_id': '8134', 'version': '1', 
233                        'details': '<p>\n\tDetails of the Test Suite B</p>\n', 'estimated_exec_duration': '3.00', 'updater_id': '2', 'status': '1', 
234                        'importance': '3', 'modification_ts': '2014-06-30 20:45:40', 'execution_type': '1', 
235                        'preconditions': '<p>\n\tthese are the preconditions</p>\n', 'active': '1', 'creation_ts': '2014-06-28 22:06:17', 
236                        'node_table': 'testcases', 'tcversion_id': '8145', 'name': 'TESTCASE_B', 
237                        'summary': '<p>\n\tThis is the summary of the Test Case B</p>\n', 
238                        'steps': [{'step_number': '1', 'actions': 'Step action 1 -b ', 'execution_type': '2', 'active': '1', 'id': '8151', 'expected_results': 'Step result 1 - b'}], 
239                        'author_id': '1'} ]
240
241                                            },
242                     'getTestCase' : {
243                                    '8144' : [{'full_tc_external_id': 'NPROAPI-2', 'id': '8145', 'tc_external_id': '2', 'version': '1', 
244                                                    'testsuite_id': 'deepFalse3', 'testcase_id': '8144', 'name': 'TESTCASE_B'}],
245                                    'NPROAPI-2' : [{'full_tc_external_id': 'NPROAPI-2', 'id': '8145', 'tc_external_id': '2', 'version': '1', 
246                                                    'testsuite_id': 'deepFalse3', 'testcase_id': '8144', 'name': 'TESTCASE_B'}],
247                                    '8159' : [{'full_tc_external_id': 'NPROAPI-3', 'id': '8160', 'tc_external_id': '3', 'version': '1', 
248                                                    'testsuite_id': 'deepFalse3', 'testcase_id': '8159', 'name': 'TESTCASE_B2'}],
249                                    'NPROAPI-3' : [{'full_tc_external_id': 'NPROAPI-3', 'id': '8160', 'tc_external_id': '3', 'version': '1', 
250                                                    'testsuite_id': 'deepFalse3', 'testcase_id': '8159', 'name': 'TESTCASE_B2'}],
251                                    '8169' : [{'full_tc_external_id': 'NPROAPI-4', 'id': '8170', 'tc_external_id': '3', 'version': '1', 
252                                                    'testsuite_id': 'deepFalse3', 'testcase_id': '8169', 'name': 'TESTCASE_B3'}],
253                                    'NPROAPI-4' : [{'full_tc_external_id': 'NPROAPI-4', 'id': '8170', 'tc_external_id': '3', 'version': '1', 
254                                                    'testsuite_id': 'deepFalse3', 'testcase_id': '8169', 'name': 'TESTCASE_B3'}] },
255                     'getTestCaseKeywords' : {
256                                               #{'12622': {'34': 'KeyWord01', '36': 'KeyWord03'}}
257                                    '8144' : {'8144' : {'1': 'KeyWord01', '3': 'KeyWord03'} },
258                                    'NPROAPI-2' : {'8144' : {'1': 'KeyWord01', '3': 'KeyWord03'} },
259                                    '8159' : {'8159' : {'2': 'KeyWord02'}},
260                                    'NPROAPI-3' : {'8159' : {'2': 'KeyWord02'}},
261                                    '8169' : {'8169' : {}},
262                                    'NPROAPI-4' : {'8169' : {}} 
263                                              }
264                     }
265
266# scenario_no_project simulates a fresh empty test link application
267SCENARIO_NO_PROJECT = {'getProjects' : [] }
268
269class DummyAPIClient(TestlinkAPIClient):
270    """ Dummy for Simulation TestLinkAPICLient. 
271    Overrides _callServer() Method to return test scenarios
272    """
273
274    __slots__ = ['scenario_data', 'callArgs']
275
276    def __init__(self, server_url, devKey, **args):
277        super(DummyAPIClient, self).__init__(server_url, devKey, **args)
278        self.scenario_data = {}
279        self.callArgs = None
280
281    def loadScenario(self, a_scenario):
282        self.scenario_data = a_scenario
283        self.callArgs = None
284
285    def _callServer(self, methodAPI, argsAPI=None):
286        self.callArgs = argsAPI
287        data = self.scenario_data[methodAPI]
288        response = None
289        if methodAPI in ['getProjectTestPlans', 
290                         'getFirstLevelTestSuitesForTestProject']:
291            response = data[argsAPI['testprojectid']]
292        elif methodAPI in ['getTestSuitesForTestPlan', 
293                           'getTestCasesForTestPlan', 'getTestPlanPlatforms',
294                           'getBuildsForTestPlan']:
295            response = data[argsAPI['testplanid']]
296        elif methodAPI in ['getTestCasesForTestSuite', 
297                           'getTestSuitesForTestSuite']:
298            response = data[argsAPI['testsuiteid']]
299        elif methodAPI in ['getTestCaseIDByName']:
300            response = data[argsAPI['testcasename']]
301        elif methodAPI in ['getTestCase', 'getTestCaseKeywords']:
302            datakey = argsAPI.get('testcaseid')
303            if datakey:
304                datakey = str(datakey)
305            else:
306                datakey = argsAPI.get('testcaseexternalid', '')
307            if 'version' in argsAPI:
308                datakey += '-%(version)s' % argsAPI
309            response = data[datakey]
310        elif methodAPI in ['getFullPath']:
311            response = data[argsAPI['nodeid']]
312        elif methodAPI in ['getTestProjectByName']:
313            response = data[argsAPI['testprojectname']]
314        else:
315            response = data
316        return response
317
318
319class TestLinkAPIOfflineTestCase(unittest.TestCase):
320    """ TestCases for TestlinkAPIClient - does not interacts with a TestLink Server.
321    works with DummyAPIClientm which returns special test data
322    """
323
324    example_steps = [{'step_number' : '1', 'actions' : "action A" , 
325                'expected_results' : "result A", 'execution_type' : "0"},
326                 {'step_number' : '2', 'actions' : "action B" , 
327                'expected_results' : "result B", 'execution_type' : "1"},
328                 {'step_number' : '3', 'actions' : "action C" , 
329                'expected_results' : "result C", 'execution_type' : "0"}]
330
331    @classmethod
332    def setUpClass(cls):
333        cls.api = TestLinkHelper().connect(DummyAPIClient)
334        
335    def setUp(self):
336        self.api._emptyStepsList()
337
338#    def tearDown(self):
339#        pass
340
341    def test_countProjects(self):
342        self.api.loadScenario(SCENARIO_A)
343        response = self.api.countProjects()
344        self.assertEqual(2, response)
345        
346    def test_countProjects_NoProject(self):
347        self.api.loadScenario(SCENARIO_NO_PROJECT)
348        response = self.api.countProjects()
349        self.assertEqual(0, response)
350
351    def test_countTestPlans(self):
352        self.api.loadScenario(SCENARIO_A)
353        response = self.api.countTestPlans()
354        self.assertEqual(2, response)
355
356    def test_countTestPlans_NoProject(self):
357        self.api.loadScenario(SCENARIO_NO_PROJECT)
358        response = self.api.countTestPlans()
359        self.assertEqual(0, response)
360
361    def test_countTestSuites(self):
362        self.api.loadScenario(SCENARIO_A)
363        response = self.api.countTestSuites()
364        self.assertEqual(0, response)
365
366    def test_countTestSuites_NoProject(self):
367        self.api.loadScenario(SCENARIO_NO_PROJECT)
368        response = self.api.countTestSuites()
369        self.assertEqual(0, response)
370
371    def test_countTestCasesTP(self):
372        self.api.loadScenario(SCENARIO_A)
373        response = self.api.countTestCasesTP()
374        self.assertEqual(0, response)
375
376    def test_countTestCasesTP_NoProject(self):
377        self.api.loadScenario(SCENARIO_NO_PROJECT)
378        response = self.api.countTestCasesTP()
379        self.assertEqual(0, response)
380
381    def test_countTestCasesTS(self):
382        self.api.loadScenario(SCENARIO_A)
383        response = self.api.countTestCasesTS()
384        self.assertEqual(0, response)
385
386    def test_countTestCasesTS_NoProject(self):
387        self.api.loadScenario(SCENARIO_NO_PROJECT)
388        response = self.api.countTestCasesTS()
389        self.assertEqual(0, response)
390
391    def test_countPlatforms(self):
392        self.api.loadScenario(SCENARIO_A)
393        response = self.api.countPlatforms()
394        self.assertEqual(2, response)
395        
396    def test_countPlatforms_NoProject(self):
397        self.api.loadScenario(SCENARIO_NO_PROJECT)
398        response = self.api.countPlatforms()
399        self.assertEqual(0, response)
400
401    def test_countBuilds(self):
402        self.api.loadScenario(SCENARIO_A)
403        response = self.api.countBuilds()
404        self.assertEqual(0, response)
405        
406    def test_countBuilds_NoProject(self):
407        self.api.loadScenario(SCENARIO_NO_PROJECT)
408        response = self.api.countBuilds()
409        self.assertEqual(0, response)
410
411
412#    def test_listProjects(self):
413#        self.api.loadScenario(SCENARIO_A)
414#        self.api.listProjects()
415#         no assert check cause method returns nothing
416#         'just' prints to stdout
417
418    def test_getProjectIDByName(self):
419        self.api.loadScenario(SCENARIO_A)
420        response = self.api.getProjectIDByName('NEW_PROJECT_API')
421        self.assertEqual('21', response)
422        response = self.api.getProjectIDByName('UNKNOWN_PROJECT')
423        self.assertEqual(-1, response)
424        
425    def test_getProjectIDByName_NoProject(self):
426        self.api.loadScenario(SCENARIO_NO_PROJECT)
427        response = self.api.getProjectIDByName('UNKNOWN_PROJECT')
428        self.assertEqual(-1, response)
429        
430
431    def test_initStep(self):
432        self.api.initStep("action A", "result A", 0)
433        steps = self.example_steps[:1]
434        self.assertEqual(steps, self.api.stepsList)
435
436    def test_appendStep(self):
437        steps = self.example_steps
438        self.api.stepsList = steps[:1] 
439        self.api.appendStep("action B", "result B", 1)
440        self.api.appendStep("action C", "result C", 0)
441        self.assertEqual(steps, self.api.stepsList)
442
443    def test_createTestCaseWithSteps(self):
444        self.api.loadScenario(SCENARIO_STEPS)
445        self.api.initStep("action A", "result A", 0)
446        self.api.appendStep("action B", "result B", 1)
447        self.api.appendStep("action C", "result C", 0)
448        self.api.createTestCase('case 4711', 4712, 4713, 'Big Bird', 
449                                'summary 4714')
450        self.assertEqual(self.example_steps, self.api.callArgs['steps'])
451        self.assertEqual([], self.api.stepsList)
452
453    def test_createTestCaseWithConfusingSteps(self):
454        self.api.loadScenario(SCENARIO_STEPS)
455        self.api.initStep("action A", "result A", 0)
456        self.api.appendStep("action B", "result B", 1)
457        self.api.appendStep("action C", "result C", 0)
458        with self.assertRaisesRegex(TLArgError, 'confusing createTestCase*'):
459            self.api.createTestCase('case 4711', 4712, 4713, 'Big Bird', 
460                                    'summary 4714', steps=[])
461
462    def test_getTestCaseIDByName_dictResult(self):
463        "test that getTestCaseIDByName converts dictionary result into a list"
464        self.api.loadScenario(SCENARIO_A)
465        # v0.4.0 version for optional args testsuitename + testprojectname
466        #response = self.api.getTestCaseIDByName('dictResult', None, 'NEW_PROJECT_API')
467        # v0.4.5 version
468        response = self.api.getTestCaseIDByName('dictResult', 
469                                            testprojectname='NEW_PROJECT_API')
470        self.assertEqual(list, type(response))
471        self.assertEqual('TESTCASE_B', response[0]['name']) 
472        self.assertEqual(self.api.devKey, self.api.callArgs['devKey'])
473
474    def test_getTestCaseIDByName_listResult(self):
475        self.api.loadScenario(SCENARIO_A)
476        response = self.api.getTestCaseIDByName('listResult')
477        self.assertEqual(list, type(response))
478        self.assertEqual('TESTCASE_AA', response[0]['name']) 
479        self.assertEqual(self.api.devKey, self.api.callArgs['devKey'])
480
481    def test_getProjectIDByNode(self):
482        self.api.loadScenario(SCENARIO_A)
483        self.assertEqual('2211', self.api.getProjectIDByNode('4711'))
484
485    def test__copyTC_generate_new(self):
486        self.api.loadScenario(SCENARIO_A)
487        self.api._copyTC('26', {}, duplicateaction = 'generate_new')
488        self.assertEqual('generate_new',  
489                         self.api.callArgs['actiononduplicatedname'])
490
491    def test__copyTC_create_new_version(self):
492        self.api.loadScenario(SCENARIO_A)
493        self.api._copyTC('26', {}, duplicateaction = 'create_new_version')
494        self.assertEqual('create_new_version',  
495                         self.api.callArgs['actiononduplicatedname'])
496        self.assertEqual('V2 None', self.api.callArgs['preconditions'])
497
498    def test__copyTC_changedArgs(self):
499        self.api.loadScenario(SCENARIO_A)
500        self.api._copyTC('26', {'testsuiteid' :'4711'}, 
501                         duplicateaction = 'generate_new')
502        self.assertEqual('4711', self.api.callArgs['testsuiteid'])
503        self.assertEqual('2211', self.api.callArgs['testprojectid'])
504
505    def test__copyTC_changedArgs_version(self):
506        self.api.loadScenario(SCENARIO_A)
507        self.api._copyTC('26', {'testsuiteid' :'4711'}, 1,
508                         duplicateaction = 'generate_new')
509        self.assertEqual('4711', self.api.callArgs['testsuiteid'])
510        self.assertEqual('2211', self.api.callArgs['testprojectid'])
511        self.assertEqual('V1', self.api.callArgs['preconditions'])
512
513    def test_copyTCnewVersion(self):
514        self.api.loadScenario(SCENARIO_A)
515        self.api.copyTCnewVersion('26', summary = 'The summary has changed', 
516                                    importance = '33')
517        self.assertEqual('create_new_version',  
518                         self.api.callArgs['actiononduplicatedname'])
519        self.assertEqual('V2 None', self.api.callArgs['preconditions'])
520        self.assertEqual('The summary has changed', self.api.callArgs['summary'])
521        self.assertEqual('33', self.api.callArgs['importance'])
522        self.assertEqual('TC-C', self.api.callArgs['testcasename'])
523        self.assertEqual('25', self.api.callArgs['testsuiteid'])
524        self.assertEqual('21', self.api.callArgs['testprojectid'])
525
526    def test_copyTCnewVersion_version(self):
527        self.api.loadScenario(SCENARIO_A)
528        self.api.copyTCnewVersion('26', 1, summary = 'The summary has changed', 
529                                    importance = '33')
530        self.assertEqual('create_new_version',  
531                         self.api.callArgs['actiononduplicatedname'])
532        self.assertEqual('V1', self.api.callArgs['preconditions'])
533        self.assertEqual('The summary has changed', self.api.callArgs['summary'])
534        self.assertEqual('33', self.api.callArgs['importance'])
535        self.assertEqual('TC-C', self.api.callArgs['testcasename'])
536        self.assertEqual('25', self.api.callArgs['testsuiteid'])
537        self.assertEqual('21', self.api.callArgs['testprojectid'])
538
539    def test_copyTCnewTestCase(self):
540        self.api.loadScenario(SCENARIO_A)
541        self.api.copyTCnewTestCase('26', testsuiteid = '4711')
542        self.assertEqual('generate_new',  
543                         self.api.callArgs['actiononduplicatedname'])
544        self.assertEqual('V2 None', self.api.callArgs['preconditions'])
545        self.assertEqual('4711', self.api.callArgs['testsuiteid'])
546        self.assertEqual('2211', self.api.callArgs['testprojectid'])
547
548    def test_copyTCnewTestCase_version(self):
549        self.api.loadScenario(SCENARIO_A)
550        self.api.copyTCnewTestCase('26', 1, testsuiteid = '4711')
551        self.assertEqual('generate_new',  
552                         self.api.callArgs['actiononduplicatedname'])
553        self.assertEqual('V1', self.api.callArgs['preconditions'])
554        self.assertEqual('4711', self.api.callArgs['testsuiteid'])
555        self.assertEqual('2211', self.api.callArgs['testprojectid'])
556
557    def test_reportTCResult_user(self):
558        self.api.loadScenario(SCENARIO_A)
559        response = self.api.reportTCResult(4711, 4712, 'build 4713', 'p', 
560                                           'note 4714', user='a login name') 
561        self.assertEqual('reportTCResult', response[0]['operation']) 
562        self.assertEqual(self.api.devKey, self.api.callArgs['devKey'])
563        self.assertEqual('a login name', self.api.callArgs['user'])
564        
565    def test_getTestCasesForTestSuite_keyWords(self):
566        self.api.loadScenario(SCENARIO_KEYWORDS)
567        response = self.api.getTestCasesForTestSuite('deepFalse3', False, 
568                                                     'full', getkeywords=True)
569        self.assertIn('keywords', response[0])
570        self.assertNotIn('keywords', response[2])
571        self.assertEqual(self.api.devKey, self.api.callArgs['devKey'])
572
573    def test_listKeywordsForTC_FullExternalId(self):
574        self.api.loadScenario(SCENARIO_KEYWORDS)
575        response = self.api.listKeywordsForTC('NPROAPI-2')
576        self.assertEqual(set(['KeyWord01', 'KeyWord03']), set(response))
577
578    def test_listKeywordsForTC_InternalId_Int(self):
579        self.api.loadScenario(SCENARIO_KEYWORDS)
580        response = self.api.listKeywordsForTC(8144)
581        self.assertEqual(set(['KeyWord01', 'KeyWord03']), set(response))
582
583    def test_listKeywordsForTC_InternalId_String(self):
584        self.api.loadScenario(SCENARIO_KEYWORDS)
585        response = self.api.listKeywordsForTC('8144')
586        self.assertEqual(set(['KeyWord01', 'KeyWord03']), set(response))
587
588    def test_listKeywordsForTC_One(self):
589        self.api.loadScenario(SCENARIO_KEYWORDS)
590        response = self.api.listKeywordsForTC('NPROAPI-3')
591        self.assertEqual(['KeyWord02'], response)
592
593    def test_listKeywordsForTC_None(self):
594        self.api.loadScenario(SCENARIO_KEYWORDS)
595        response = self.api.listKeywordsForTC('NPROAPI-4')
596        self.assertEqual([], response)
597
598    def test_listKeywordsForTS_NoneTC(self):
599        self.api.loadScenario(SCENARIO_KEYWORDS)
600        response = self.api.listKeywordsForTS('noTestCase')
601        self.assertEqual({}, response)
602
603    def test_listKeywordsForTS_NoneKW(self):
604        self.api.loadScenario(SCENARIO_KEYWORDS)
605        response = self.api.listKeywordsForTS('noKeywords')
606        self.assertEqual({'8144': []}, response)
607        
608    def test_listKeywordsForTS_Id_Int(self):
609        self.api.loadScenario(SCENARIO_KEYWORDS)
610        response = self.api.listKeywordsForTS(4711)
611        set_response = response
612        for item in set_response:
613            set_response[item] = set(response[item])
614        self.assertEqual({'8144': set(['KeyWord01', 'KeyWord03'])}, set_response)
615
616    def test_listKeywordsForTS_Id_String(self):
617        self.api.loadScenario(SCENARIO_KEYWORDS)
618        response = self.api.listKeywordsForTS('4711')
619        set_response = response
620        for item in set_response:
621            set_response[item] = set(response[item])
622        self.assertEqual({'8144': set(['KeyWord01', 'KeyWord03'])}, set_response)
623
624    def test_listKeywordsForTS_Multi(self):
625        self.api.loadScenario(SCENARIO_KEYWORDS)
626        response = self.api.listKeywordsForTS('deepFalse3')
627        set_response = response
628        for item in set_response:
629            set_response[item] = set(response[item])
630        self.assertEqual({'8144': set(['KeyWord01', 'KeyWord03']),
631                          '8159': set(['KeyWord02']), '8169': set()}, set_response)
632
633    def test_connect_with_proxy(self):
634        """ create a TestLink API dummy with ProxiedTransport"""
635        self.api = DummyAPIClient('http://SERVER-URL-71', 'DEVKEY-71', 
636                                   transport='PROXY-71')
637        self.assertEqual('PROXY-71', self.api.server.__call__('transport'))        
638
639    def test_connect_with_use_datetime(self):
640        """ create a TestLink Generic API dummy with use_datetime"""
641        self.api = DummyAPIClient('http://SERVER-URL-71', 'DEVKEY-71', 
642                                   use_datetime='datetime?')
643        a_transport = self.api.server.__call__('transport')
644        self.assertEqual('datetime?', a_transport._use_datetime)
645
646    def test_connect_with_context(self):
647        """ create a TestLink Generic API dummy with use_datetime"""
648        self.api = DummyAPIClient('https://SERVER-URL-71', 'DEVKEY-71', 
649                                   context='ssl_context')
650        a_transport = self.api.server.__call__('transport')
651        self.assertEqual('ssl_context', a_transport.context)
652
653if __name__ == "__main__":
654    #import sys;sys.argv = ['', 'Test.testName']
655    unittest.main()
Full Screen

gherkin.py

Source: gherkin.py Github

copy
1# -*- coding: utf-8 -*-
2#    Copyright 2020 Iñigo Gonzalez Ponce
3#
4#    Licensed under the Apache License, Version 2.0 (the "License");
5#    you may not use this file except in compliance with the License.
6#    You may obtain a copy of the License at
7#
8#        http://www.apache.org/licenses/LICENSE-2.0
9#
10#    Unless required by applicable law or agreed to in writing, software
11#    distributed under the License is distributed on an "AS IS" BASIS,
12#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13#    See the License for the specific language governing permissions and
14#    limitations under the License.
15
16import re
17import io
18# This ruleset has all the magic:
19# it stores both the ruleset and de compiled code
20# that does all the Gherkin magic.
21
22class gherkinRule:
23
24    def __init__(self, text=None, conjunction=None):
25        self.ruleType = None  # (when, given, and) - should have for each - for every
26        self.connector = conjunction  # and, or, and not, except (...)
27        self.action = None
28        self.text = text
29    def __repr__(self):
30        return f'{__class__}: {self.text}'
31
32    def match(self,text):
33        """
34        Check if this text matches a rule to  be excecuted
35        """
36        return False
37
38    def exec(self,code):
39        """
40        Execute piece of code if rule matches.
41        """
42        return False
43
44
45class gherkinScenario:
46
47    def __init__(self, name='No name'):
48        self.name = name.strip()
49        self.rules = []
50        self.code = None
51        self.is_runnable = False
52
53    def __repr__(self):
54       return f'{__class__}: {self.name}'
55
56    def add_rule(self, rule: gherkinRule):
57        self.rules.append(rule)
58
59class gherkin:
60
61    scenario_keywords = ['scenario', 'golden', 'golden record',
62                         'transform', 'transformation']
63
64    rule_keywords = ['when', 'given', 'since', 'and',
65                     'not', 'but', 'except',
66                     r'for\s*each', r'for\s*every', 'every',
67                     'and', 'or', 'not', 'but']
68
69    rule_actions = ['then', 'log', 'update', 'trigger', 'discard', 'remove']
70
71    def __init__(self):
72        self.scenarios = []
73
74    """
75    Parse gherkin from source. Source can be *whatever* we need
76    (stream or string/stingarray).
77
78    Since we are using Gherkin for data stuff, scenarios are not needed.
79    This makes "a bit" simpler the Gherkin parsing (by now).
80
81    Semi-BNF for the Gherkin-data language is:
82
83        Scenario|Transfor(mation)|Golden Record: "__name__":
84
85        ^Given|When|^_____ .....
86        ^And^Or^Not ____________
87        Then ___________________
88    """
89    def parse(self, source):
90
91        keywords_regexp = r"^\s*(" + "|".join(self.rule_keywords + self.rule_actions) + ")"
92        scenario_regexp = r"^\s*(" + "|".join(self.scenario_keywords) + ")"
93        print(keywords_regexp)
94        print (scenario_regexp)
95
96        curr_scenario = gherkinScenario()
97
98        # Adapt input
99
100        if source.__class__ is str:
101            source = source.splitlines()
102       
103        for lin in source:
104            # Clear whitespace and comments
105            lin = lin.lstrip()
106            if lin.startswith('#'):
107                lin = ''
108
109            if lin != '':
110                sp = lin.split(':')
111                # Check scenarios first, then rules
112                sp = lin.split(':')
113                print(lin)
114
115                if len(sp) > 1:
116                    print(curr_scenario.name)
117                    # Should be a 'Scenario: name' statement
118                    if re.match(scenario_regexp, sp[0], re.IGNORECASE) is not None:
119                        print("Scenario DETECTED: keyword={}\n\tScenario_name: {}".format(sp[0], sp[1]))
120                        new_scenario = gherkinScenario(sp[1])
121
122                        # Do we have already an scenario _with_ rules?
123                        if curr_scenario.rules:
124                            self.scenarios.append(curr_scenario)
125                        else:
126                            """ Empty scenario detected 
127                                Scenario: blah blah blah <-- this one
128                                Scenario: more blah blah blah
129
130                                Should send a warning and ignore the first
131                            """
132                            print("EMPTY Scenario detected")
133
134                        curr_scenario = new_scenario
135
136                    else:
137                        print("UNKNOWN Scenario type detected: {} - Ignoring?".format(sp[0]))
138                else:
139                    # Whitespace or rule
140                    ruleline = re.split(keywords_regexp, lin, 0, re.IGNORECASE)
141                    if len(ruleline) > 1:
142                        print(f'RULE =>{ruleline}<==')  # gherkin.parse: - Detected Rule {}".format(sp) )
143                        conjunction, phrase = ruleline[1], ruleline[2]
144                        this_rule = gherkinRule(text=phrase, conjunction=conjunction)
145                        curr_scenario.add_rule(this_rule)
146
147                    else:
148                        errmsg = 'Expected scenario, rule, comment, or empty line'
149                        displaymsg = f'{lin}\n^^^{errmsg}'
150                        print(displaymsg)
151                        raise RuntimeWarning(errmsg)
152
153        self.scenarios.append(curr_scenario)
154
155
Full Screen

dialect.py

Source: dialect.py Github

copy
1import io
2import os
3import json
4
5DIALECT_FILE_PATH = os.path.join(os.path.dirname(__file__),
6                                 'gherkin-languages.json')
7
8with io.open(DIALECT_FILE_PATH, 'r', encoding='utf-8') as file:
9    DIALECTS = json.load(file)
10
11# from .gherkin_languages import d as DIALECTS
12
13
14class Dialect(object):
15    @classmethod
16    def for_name(cls, name):
17        return cls(DIALECTS[name]) if name in DIALECTS else None
18
19    def __init__(self, spec):
20        self.spec = spec
21
22    @property
23    def feature_keywords(self):
24        return self.spec['feature']
25
26    @property
27    def scenario_keywords(self):
28        return self.spec['scenario']
29
30    @property
31    def scenario_outline_keywords(self):
32        return self.spec['scenarioOutline']
33
34    @property
35    def background_keywords(self):
36        return self.spec['background']
37
38    @property
39    def examples_keywords(self):
40        return self.spec['examples']
41
42    @property
43    def given_keywords(self):
44        return self.spec['given']
45
46    @property
47    def when_keywords(self):
48        return self.spec['when']
49
50    @property
51    def then_keywords(self):
52        return self.spec['then']
53
54    @property
55    def and_keywords(self):
56        return self.spec['and']
57
58    @property
59    def but_keywords(self):
60        return self.spec['but']
61
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run Python Tests on LambdaTest Cloud Grid

Execute automation tests with Gherkin-python on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)