How to use test_expected method in green

Best Python code snippet using green

test.py

Source:test.py Github

copy

Full Screen

1# Class encapsulating a unit test.2#3# * @author Ben Gardner October 20094# * @author Guy Maurel October 20155# * @author Matthew Woehlke June 20186#7import filecmp8import os9import re10import subprocess11import sys12import errno13from .ansicolor import printc14from .config import (config, test_dir, FAIL_ATTRS, PASS_ATTRS,15 MISMATCH_ATTRS, UNSTABLE_ATTRS)16from .failure import (ExecutionFailure, MismatchFailure, MissingFailure,17 TestDeclarationParseError, UnexpectedlyPassingFailure,18 UnstableFailure)19# =============================================================================20class SourceTest(object):21 # -------------------------------------------------------------------------22 def __init__(self):23 self.test_result_dir = 'results'24 self.diff_text = 'MISMATCH'25 self.diff_attrs = MISMATCH_ATTRS26 self.diff_exception = MismatchFailure27 # -------------------------------------------------------------------------28 def _check_attr(self, name):29 if not hasattr(self, name) or getattr(self, name) is None:30 raise AttributeError(31 'Test is missing required attribute {!r}'.format(name))32 # -------------------------------------------------------------------------33 def _make_abs(self, name, base):34 path = getattr(self, name)35 if not os.path.isabs(path):36 setattr(self, name, os.path.join(test_dir, base, path))37 # -------------------------------------------------------------------------38 def _diff(self, expected, actual):39 sys.stdout.flush()40 cmd = [config.git_exe, 'diff', '--no-index', expected, actual]41 subprocess.call(cmd)42 # -------------------------------------------------------------------------43 def build(self, test_input, test_lang, test_config, test_expected):44 self.test_name = os.path.basename(test_input)45 self.test_lang = test_lang46 self.test_input = test_input47 self.test_config = test_config48 self.test_expected = test_expected49 self.test_xfail = False50 # -------------------------------------------------------------------------51 def _check(self):52 self._check_attr('test_name')53 self._check_attr('test_lang')54 self._check_attr('test_input')55 self._check_attr('test_config')56 self._check_attr('test_expected')57 self._check_attr('test_xfail')58 # -------------------------------------------------------------------------59 def run(self, args):60 self._check()61 _expected = self.test_expected62 _result = os.path.join(args.result_dir, self.test_result_dir,63 os.path.basename(os.path.dirname(_expected)),64 os.path.basename(_expected))65 if args.verbose:66 print(self.test_name)67 print(' Language : {}'.format(self.test_lang))68 print(' Input : {}'.format(self.test_input))69 print(' Config : {}'.format(self.test_config))70 print(' Expected : {}'.format(_expected))71 print(' Result : {}'.format(_result))72 print(' XFail : {}'.format(self.test_xfail))73 if not os.path.exists(os.path.dirname(_result)):74 try:75 os.makedirs(os.path.dirname(_result))76 except OSError as e:77 if e.errno != errno.EEXIST:78 raise79 cmd = [80 config.uncrustify_exe,81 '-q',82 '-l', self.test_lang,83 '-c', self.test_config,84 '-f', self.test_input,85 '-o', _result86 ]87 if args.debug:88 cmd += [89 '-LA',90 '-p', _result + '.unc'91 ]92 else:93 cmd += ['-LA']94 if args.show_commands:95 printc('RUN: ', repr(cmd))96 try:97 output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)98 except subprocess.CalledProcessError as exc:99 output = exc.output100 if not self.test_xfail:101 print(output.rstrip())102 msg = '{} (Uncrustify error code {})'103 msg = msg.format(self.test_name, exc.returncode)104 printc('FAILED: ', msg, **FAIL_ATTRS)105 raise ExecutionFailure(exc)106 elif args.xdiff:107 print(output.rstrip())108 finally:109 if args.debug:110 with open(_result + '.log', 'wt') as f:111 f.write(output)112 try:113 has_diff = not filecmp.cmp(_expected, _result)114 if has_diff and not self.test_xfail:115 if args.diff:116 self._diff(_expected, _result)117 printc('{}: '.format(self.diff_text),118 self.test_name, **self.diff_attrs)119 raise self.diff_exception(_expected, _result)120 if not has_diff and self.test_xfail:121 raise UnexpectedlyPassingFailure(_expected, _result)122 if has_diff and self.test_xfail:123 if args.xdiff:124 self._diff(_expected, _result)125 if not args.show_all:126 printc('XFAILED: ', self.test_name, **PASS_ATTRS)127 except OSError as exc:128 printc('MISSING: ', self.test_name, **self.diff_attrs)129 raise MissingFailure(exc, _expected)130# =============================================================================131class FormatTest(SourceTest):132 pass_config = ['test_config', 'test_rerun_config']133 pass_input = ['test_input', 'test_expected']134 pass_expected = ['test_expected', 'test_rerun_expected']135 re_test_declaration = re.compile(r'^(?P<num>\d+)(?P<mark>[~!]*)\s+'136 r'(?P<config>\S+)\s+(?P<input>\S+)'137 r'(?:\s+(?P<lang>\S+))?$')138 # -------------------------------------------------------------------------139 def _build_pass(self, i):140 p = SourceTest()141 p.test_name = self.test_name142 p.test_lang = self.test_lang143 p.test_config = getattr(self, self.pass_config[i])144 p.test_input = getattr(self, self.pass_input[i])145 p.test_expected = getattr(self, self.pass_expected[i])146 p.test_xfail = self.test_xfail147 if i == 1 and not os.path.exists(p.test_expected):148 p.test_expected = getattr(self, self.pass_expected[0])149 return p150 # -------------------------------------------------------------------------151 def _build_passes(self):152 self._check()153 self._check_attr('test_rerun_config')154 self._check_attr('test_rerun_expected')155 self._make_abs('test_input', 'input')156 self._make_abs('test_config', 'config')157 self._make_abs('test_expected', 'expected')158 self._make_abs('test_rerun_config', 'config')159 self._make_abs('test_rerun_expected', 'expected')160 self.test_passes = [161 self._build_pass(0),162 self._build_pass(1)]163 self.test_passes[1].test_name = self.test_name + ' (re-run)'164 self.test_passes[1].test_result_dir = 'results_2'165 self.test_passes[1].diff_text = 'UNSTABLE'166 self.test_passes[1].diff_attrs = UNSTABLE_ATTRS167 self.test_passes[1].diff_exception = UnstableFailure168 # -------------------------------------------------------------------------169 def build_from_declaration(self, decl, group, line_number):170 match = self.re_test_declaration.match(decl)171 if not match:172 raise TestDeclarationParseError(group, line_number)173 num = match.group('num')174 is_rerun = ('!' in match.group('mark'))175 is_xfail = ('~' in match.group('mark'))176 self.test_xfail = is_xfail177 self.test_config = match.group('config')178 self.test_input = match.group('input')179 test_dir = os.path.dirname(self.test_input)180 test_filename = os.path.basename(self.test_input)181 if match.group('lang'):182 self.test_lang = match.group('lang')183 else:184 self.test_lang = test_dir185 self.test_expected = os.path.join(186 test_dir, '{}-{}'.format(num, test_filename))187 def rerun_file(name):188 parts = name.split('.')189 return '.'.join(parts[:-1] + ['rerun'] + parts[-1:])190 if is_rerun:191 self.test_rerun_config = rerun_file(self.test_config)192 self.test_rerun_expected = rerun_file(self.test_expected)193 else:194 self.test_rerun_config = self.test_config195 self.test_rerun_expected = self.test_expected196 self.test_name = '{}:{}'.format(group, num)197 self._build_passes()198 # -------------------------------------------------------------------------199 def build_from_args(self, args):200 self.test_name = args.name201 self.test_lang = args.lang202 self.test_input = args.input203 self.test_config = args.config204 self.test_expected = args.expected205 self.test_rerun_config = args.rerun_config or args.config206 self.test_rerun_expected = args.rerun_expected or args.expected207 self.test_xfail = args.xfail208 self._build_passes()209 # -------------------------------------------------------------------------210 def print_as_ctest(self, out_file=sys.stdout):211 self._check()212 def to_cmake_path(obj):213 if type(obj) is dict:214 return {k: to_cmake_path(v) for k, v in obj.items()}215 if type(obj) is str:216 return obj.replace(os.sep, '/')217 return obj218 runner = os.path.join(test_dir, 'run_test.py')219 out_file.write(220 ('add_test({test_name}\n' +221 ' "{python_exe}" -S "{test_runner}" "{test_name}"\n' +222 ' --executable "{uncrustify_exe}"\n' +223 ' --lang "{test_lang}"\n' +224 ' --input "{test_input}"\n' +225 ' --config "{test_config}"\n' +226 ' --expected "{test_expected}"\n' +227 ' --rerun-config "{test_rerun_config}"\n' +228 ' --rerun-expected "{test_rerun_expected}"\n' +229 ' -d --git "{git_exe}"\n' +230 '{xfail}' +231 ')\n').format(232 test_runner=to_cmake_path(runner),233 python_exe=to_cmake_path(config.python_exe),234 uncrustify_exe=to_cmake_path(config.uncrustify_exe),235 git_exe=to_cmake_path(config.git_exe),236 xfail=(' --xfail\n' if self.test_xfail else ''),237 **to_cmake_path(self.__dict__)))238 out_file.write(239 ('set_tests_properties({}\n' +240 ' PROPERTIES LABELS "{}"\n)\n').format(241 self.test_name, self.test_name.split(':')[0]))242 # -------------------------------------------------------------------------243 def run(self, args):244 for p in self.test_passes:...

Full Screen

Full Screen

test_search1_convert_result.py

Source:test_search1_convert_result.py Github

copy

Full Screen

1import unittest2import responses3from src.exceptions import NoAccessGroupError, NoUserProfileError4from src.search1_conversion import convert_result5from src.utils.config import config6from tests.unit.mocks.mocked import \7 get_data, \8 workspace_call, user_profile_call9# TODO test post processing10# TODO test the following fields: object_name, obj_id, version, type, creator11class Search1ConversionTest(unittest.TestCase):12 @responses.activate13 def test_search_objects_valid(self):14 responses.add_callback(responses.POST, config['workspace_url'],15 callback=workspace_call)16 responses.add_callback(responses.POST, config['user_profile_url'],17 callback=user_profile_call)18 # Using case-01 params, ES result and api result.19 _found, test_params = get_data(20 'SearchAPI/legacy/search_objects/case-01/params.json')21 _found, test_es_search_results = get_data(22 'elasticsearch/legacy/search_objects/case-01/result.json')23 _found, test_expected = get_data(24 'SearchAPI/legacy/search_objects/case-01/result.json')25 final = convert_result.search_objects(test_params, test_es_search_results,26 {'auth': None})27 # Remove unwanted comparisons.28 del final['search_time']29 del test_expected['search_time']30 self.maxDiff = None31 self.assertEqual(final, test_expected)32 @responses.activate33 def test_get_objects_valid(self):34 responses.add_callback(responses.POST, config['workspace_url'],35 callback=workspace_call)36 responses.add_callback(responses.POST, config['user_profile_url'],37 callback=user_profile_call)38 _found, test_params = get_data(39 'SearchAPI/legacy/get_objects/case-02/params.json')40 _found, test_es_search_results = get_data(41 'elasticsearch/legacy/get_objects/case-02/result.json')42 _found, test_expected = get_data(43 'SearchAPI/legacy/get_objects/case-02/result.json')44 final = convert_result.get_objects(test_params, test_es_search_results, {'auth': None})45 self.assertEqual(final, test_expected)46 def test_search_types_valid(self):47 _found, test_es_search_results = get_data(48 'elasticsearch/legacy/search_types/case-01/result.json')49 _found, test_expected = get_data(50 'SearchAPI/legacy/search_types/case-01/result.json')51 # Not that converting search_types does not require any52 # params or context.53 final = convert_result.search_types(test_es_search_results)54 self.assertEqual(final['type_to_count'], test_expected['type_to_count'])55 def test_fetch_narrative_info_no_hits(self):56 results = {57 'hits': []58 }59 ctx = {}60 result = convert_result._fetch_narrative_info(results, ctx)61 assert len(result) == 262 assert result[0] == {}63 assert result[1] == {}64 # TODO: This condition should not occur in any object index!65 def test_fetch_narrative_info_no_access_group(self):66 results = {67 'hits': [{68 'doc': {}69 }]70 }71 with self.assertRaises(NoAccessGroupError):72 convert_result._fetch_narrative_info(results, {'auth': None})73 @responses.activate74 def test_fetch_narrative_info_owner_has_profile(self):75 responses.add_callback(responses.POST, config['workspace_url'],76 callback=workspace_call)77 responses.add_callback(responses.POST, config['user_profile_url'],78 callback=user_profile_call)79 _found, test_es_search_results = get_data(80 'elasticsearch/legacy/search_objects/case-01/result.json')81 _found, test_expected = get_data(82 'SearchAPI/legacy/search_objects/case-01/result.json')83 ctx = {84 'auth': None85 }86 result = convert_result._fetch_narrative_info(test_es_search_results, ctx)87 self.assertEqual(len(result), 2)88 expected_result = test_expected['access_group_narrative_info']89 self.assertEqual(result[1], expected_result)90 @responses.activate91 def test_fetch_narrative_info_owner_has_no_profile(self):92 responses.add_callback(responses.POST, config['workspace_url'],93 callback=workspace_call)94 responses.add_callback(responses.POST, config['user_profile_url'],95 callback=user_profile_call)96 results = {97 'hits': [{98 'doc': {99 'access_group': 10056638100 }101 }]102 }103 meta = {104 'auth': None105 }106 with self.assertRaises(NoUserProfileError) as e:107 convert_result._fetch_narrative_info(results, meta)108 self.assertEqual(e.exception.message,109 'A user profile could not be found for "kbaseuitestx"')110 def test_get_object_data_from_search_results(self):111 responses.add_callback(responses.POST, config['workspace_url'],112 callback=workspace_call)113 responses.add_callback(responses.POST, config['user_profile_url'],114 callback=user_profile_call)115 _found, test_params = get_data(116 'SearchAPI/legacy/search_objects/case-01/params.json')117 _found, test_es_search_results = get_data(118 'elasticsearch/legacy/search_objects/case-01/result.json')119 _found, test_expected = get_data(120 'SearchAPI/legacy/search_objects/case-01/result.json')121 post_processing = test_params['post_processing']122 converted = convert_result._get_object_data_from_search_results(123 test_es_search_results,124 post_processing)...

Full Screen

Full Screen

test_expected.py

Source:test_expected.py Github

copy

Full Screen

1from copy import deepcopy2TEST_EXPECTED = dict(3 reservation_without_terms=dict(4 data=dict(5 attributes=dict(6 unit_id=1,7 arrival='2020-01-01',8 departure='2020-01-31',9 email='test@vacasa.com',10 address='123 Main St',11 adults=4,12 quote_id='foo',13 first_name='Jane',14 last_name='Doe',15 account_number='bar',16 exp_mmyy='0130',17 children=0,18 pets=0,19 trip_protection=0,20 phone=None,21 source=None22 )23 )24 ),25 normal_contact=dict(26 data=dict(27 attributes=dict(28 address_1= "123 Main st",29 address_2= "",30 city= "Springfield",31 country_code= "US",32 created_by= 0,33 email= "user@example.com",34 first_name= "User",35 language_id= 0,36 last_name= "Namesson",37 phone= "208-555-6677",38 phone_notes= "Don't ever call after midnight",39 state= "MO",40 tax_entity_name= "Arbys",41 zip= "string",42 send_email=False43 )44 )45 ),46 normal_contract=dict(47 data=dict(48 attributes=dict(49 amendment_by_notice_id= 4,50 channel_fee_cost_sharing_id= 5,51 created_by= 0,52 end_date= "2019-08-15",53 form_id= 1,54 management_fee= 0,55 monthly_rent= 0,56 owners= [57 dict(58 percentage_ownership= 100,59 tax_ownership= 100,60 contact_id= 1234561 )62 ],63 referral_discount= 0,64 referral_eligible= False,65 start_date= "2019-08-15",66 template_version_id= 1,67 unit_id= 068 )69 )70 ),71 normal_contact_finances=dict(72 data=dict(73 attributes=dict(74 account_name= "Chemical Bank",75 account_number= "987654321",76 routing_number= "123456789",77 tax_id= "00-0000-0",78 tax_entity_name= "Arbys",79 tax_form_code_id= 1280 )81 )82 )83)84# terms85TEST_EXPECTED['reservation_with_terms'] = deepcopy(TEST_EXPECTED['reservation_without_terms'])86TEST_EXPECTED['reservation_with_terms']['data']['attributes']['terms'] = '2019-04-30T16:00:00Z'87# booked_currency_code88TEST_EXPECTED['reservation_with_booked_currency_code'] = deepcopy(TEST_EXPECTED['reservation_without_terms'])89TEST_EXPECTED['reservation_with_booked_currency_code']['data']['attributes']['booked_currency_code'] = 'CLP'90TEST_EXPECTED['reservation_without_booked_currency_code'] = deepcopy(TEST_EXPECTED['reservation_without_terms'])91# display_currency_code92TEST_EXPECTED['reservation_with_display_currency_code'] = deepcopy(TEST_EXPECTED['reservation_without_terms'])93TEST_EXPECTED['reservation_with_display_currency_code']['data']['attributes']['display_currency_code'] = 'CLP'...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run green automation tests on LambdaTest cloud grid

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful