How to use _create_test_files method in avocado

Best Python code snippet using avocado_python

test_python.py

Source:test_python.py Github

copy

Full Screen

...21import pytest22from test_data.env_metadata import METADATA_VERSION_PATHS23# Helpers24# -----------------------------------------------------------------------------25def _create_test_files(test_files):26 """27 Helper method to create files in a folder with fname and given content.28 test_files = (29 ('folder', 'fname', 'content'), # Create a file in folder with content30 ('', 'fname', 'content'), # Create a file with content31 ('folder', '', ''), # Create a folder32 )33 """34 temp_path = tempfile.mkdtemp()35 fpaths = []36 for folder, fname, content in test_files:37 fpath = os.path.join(temp_path, folder, fname)38 try:39 os.makedirs(os.path.dirname(fpath))40 except Exception:41 pass42 with open(fpath, 'w') as fh:43 fh.write(content)44 fpaths.append(fpath)45 return temp_path, fpaths46def _print_output(*args):47 """Helper function to print output in case of failed tests."""48 for arg in args:49 print(arg)50 print('\n')51# Test module helper functions52# -----------------------------------------------------------------------------53def test_norm_package_name():54 test_names = (55 (None, ''),56 ('', ''),57 ('pyOpenssl', 'pyopenssl'),58 ('py.Openssl', 'py-openssl'),59 ('py-Openssl', 'py-openssl'),60 ('py_Openssl', 'py-openssl'),61 ('zope.interface', 'zope-interface'),62 )63 for (name, expected_name) in test_names:64 parsed_name = norm_package_name(name)65 _print_output(name, parsed_name, expected_name)66 assert parsed_name == expected_name67def test_pypi_name_to_conda_name():68 test_cases = (69 (None, ''),70 ('', ''),71 ('graphviz', 'python-graphviz'),72 )73 for (name, expected_name) in test_cases:74 parsed_name = pypi_name_to_conda_name(name)75 _print_output(name, parsed_name, expected_name)76 assert parsed_name == expected_name77def test_norm_package_version():78 test_cases = (79 (None, ''),80 ('', ''),81 ('>=2', '>=2'),82 ('(>=2)', '>=2'),83 (' (>=2) ', '>=2'),84 ('>=2,<3', '>=2,<3'),85 ('>=2, <3', '>=2,<3'),86 (' (>=2, <3) ', '>=2,<3'),87 )88 for (version, expected_version) in test_cases:89 parsed_version = norm_package_version(version)90 _print_output(version, parsed_version, expected_version)91 assert parsed_version == expected_version92def test_split_spec():93 test_cases = (94 # spec, separator, (spec_start, spec_end)95 ('', ';', ('', '')),96 ('start;end', ';', ('start', 'end')),97 ('start ; end', ';', ('start', 'end')),98 (' start ; end ', ';', ('start', 'end')),99 ('start@end', '@', ('start', 'end')),100 ('start @ end', '@', ('start', 'end')),101 (' start @ end ', '@', ('start', 'end')),102 )103 for spec, sep, expected_output in test_cases:104 output = split_spec(spec, sep)105 _print_output(spec, output, expected_output)106 assert output == expected_output107def test_parse_specification():108 test_reqs = {109 '':110 PySpec('', [], '', '', ''),111 'requests':112 PySpec('requests', [], '', '', ''),113 'requests >1.1':114 PySpec('requests', [], '>1.1', '', ''),115 'requests[security]':116 PySpec('requests', ['security'], '', '', ''),117 'requests[security] (>=1.1.0)':118 PySpec('requests', ['security'], '>=1.1.0', '', ''),119 'requests[security]>=1.5.0':120 PySpec('requests', ['security'], '>=1.5.0', '', ''),121 'requests[security] (>=4.5.0) ; something >= 27':122 PySpec('requests', ['security'], '>=4.5.0', 'something >= 27', ''),123 'requests[security]>=3.3.0;something >= 2.7 ':124 PySpec('requests', ['security'], '>=3.3.0', 'something >= 2.7', ''),125 'requests[security]>=3.3.0;something >= 2.7 or something_else == 1':126 PySpec('requests', ['security'], '>=3.3.0', 'something >= 2.7 or something_else == 1', ''),127 'requests[security] >=3.3.0 ; something >= 2.7 or something_else == 1':128 PySpec('requests', ['security'], '>=3.3.0', 'something >= 2.7 or something_else == 1', ''),129 'requests[security] (>=3.3.0) ; something >= 2.7 or something_else == 1':130 PySpec('requests', ['security'], '>=3.3.0', 'something >= 2.7 or something_else == 1', ''),131 'requests[security] (>=3.3.0<4.4) ; something >= 2.7 or something_else == 1':132 PySpec('requests', ['security'], '>=3.3.0<4.4', 'something >= 2.7 or something_else == 1', ''),133 'pyOpenSSL>=0.14':134 PySpec('pyopenssl', [], '>=0.14', '', ''),135 'py.OpenSSL>=0.14':136 PySpec('py-openssl', [], '>=0.14', '', ''),137 'py-OpenSSL>=0.14':138 PySpec('py-openssl', [], '>=0.14', '', ''),139 'py_OpenSSL>=0.14':140 PySpec('py-openssl', [], '>=0.14', '', ''),141 'zope.interface (>3.5.0)':142 PySpec('zope-interface', [], '>3.5.0', '', ''),143 "A":144 PySpec('a', [], '', '', ''),145 "A.B-C_D":146 PySpec('a-b-c-d', [], '', '', ''),147 "aa":148 PySpec('aa', [], '', '', ''),149 "name":150 PySpec('name', [], '', '', ''),151 "name<=1":152 PySpec('name', [], '<=1', '', ''),153 "name>=3":154 PySpec('name', [], '>=3', '', ''),155 "name>=3,<2":156 PySpec('name', [], '>=3,<2', '', ''),157 " name ( >= 3, < 2 ) ":158 PySpec('name', [], '>=3,<2', '', ''),159 "name@http://foo.com":160 PySpec('name', [], '', '', 'http://foo.com'),161 " name [ fred , bar ] ( >= 3 , < 2 ) ":162 PySpec('name', ['fred', 'bar'], '>=3,<2', '', ''),163 " name [fred,bar] ( >= 3 , < 2 ) @ http://foo.com ; python_version=='2.7' ":164 PySpec('name', ['fred', 'bar'], '>=3,<2', "python_version=='2.7'", 'http://foo.com'),165 " name [fred,bar] @ http://foo.com ; python_version=='2.7' ":166 PySpec('name', ['fred', 'bar'], '', "python_version=='2.7'", 'http://foo.com'),167 "name[quux, strange];python_version<'2.7' and platform_version=='2'":168 PySpec('name', ['quux', 'strange'], '', "python_version<'2.7' and platform_version=='2'", ''),169 "name; os_name=='a' or os_name=='b'":170 PySpec('name', [], '', "os_name=='a' or os_name=='b'", ''),171 "name; os_name=='a' and os_name=='b' or os_name=='c'":172 PySpec('name', [], '', "os_name=='a' and os_name=='b' or os_name=='c'", ''),173 "name; os_name=='a' and (os_name=='b' or os_name=='c')":174 PySpec('name', [], '', "os_name=='a' and (os_name=='b' or os_name=='c')", ''),175 " name; os_name=='a' or os_name=='b' and os_name=='c' ":176 PySpec('name', [], '', "os_name=='a' or os_name=='b' and os_name=='c'", ''),177 " name ; (os_name=='a' or os_name=='b') and os_name=='c' ":178 PySpec('name', [], '', "(os_name=='a' or os_name=='b') and os_name=='c'", ''),179 '>=3,<2':180 PySpec('', [], '>=3,<2', '', ''),181 ' ( >=3 , <2 ) ':182 PySpec('', [], '>=3,<2', '', ''),183 '>=2.7,!=3.0.*,!=3.1.*,!=3.2.*':184 PySpec('', [], '>=2.7,!=3.0.*,!=3.1.*,!=3.2.*', '', ''),185 'name>=1.0.0-beta.1,<2.0.0':186 PySpec('name', [], '>=1.0.0.beta.1,<2.0.0', '', ''),187 'name==1.0.0+localhash':188 PySpec('name', [], '==1.0.0+localhash', '', ''),189 }190 for req, expected_req in test_reqs.items():191 parsed_req = parse_specification(req)192 _print_output(req, parsed_req, expected_req)193 assert parsed_req == expected_req194def test_get_site_packages_anchor_files():195 test_cases_valid = (196 # dir, filename, content197 ('bar.dist-info', 'RECORD', ''),198 ('foo.egg-info', 'PKG-INFO', ''),199 ('', 'cheese.egg-info', ''),200 ('', 'spam.egg-link', ''),201 )202 test_cases_invalid = (203 ('a.eggs', 'RECORD', ''),204 ('b.eggs', 'PKG-INFO', ''),205 ('', 'zoom.path', ''),206 ('', 'zoom.pth', ''),207 ('', 'something', ''),208 )209 # Create test case dirs/files on temp folder210 temp_path, fpaths = _create_test_files(test_cases_valid + test_cases_invalid)211 ref_dir = os.path.basename(temp_path)212 outputs = get_site_packages_anchor_files(temp_path, ref_dir)213 # Generate valid output214 expected_outputs = set()215 for folder, fname, content in test_cases_valid:216 expected_output = '/'.join([ref_dir, folder, fname]).replace('//', '/')217 expected_outputs.add(expected_output)218 _print_output(outputs, expected_outputs)219 assert sorted(outputs) == sorted(expected_outputs)220def test_get_dist_file_from_egg_link():221 test_files = (222 ('egg1.egg-info', 'PKG-INFO', ''),223 )224 temp_path, fpaths = _create_test_files(test_files)225 temp_path2, fpaths2 = _create_test_files((('', 'egg1.egg-link', temp_path),))226 output = get_dist_file_from_egg_link(fpaths2[0], '')227 expected_output = fpaths[0]228 _print_output(output, expected_output)229 assert output == expected_output230 # Test not existing path231 temp_path3, fpaths3 = _create_test_files((('', 'egg2.egg-link', '/not-a-path/'),))232 with pytest.raises(EnvironmentError) as exc:233 get_dist_file_from_egg_link(fpaths3[0], '')234 print(exc.value)235 # Test existing path but no valig egg-info files236 temp_path4 = tempfile.mkdtemp()237 temp_path4, fpaths4 = _create_test_files((('', 'egg2.egg-link', temp_path4),))238 with pytest.raises(EnvironmentError) as exc:239 get_dist_file_from_egg_link(fpaths4[0], '')240 print(exc.value)241@pytest.mark.skipif(True, reason="Ask @goanpeca about what this test is looking for.")242def test_get_python_distribution_info():243 temp_path_egg1, _ = _create_test_files((244 ('', 'bar.egg-info', 'Name: bar\n'),245 ))246 temp_path_egg2, _ = _create_test_files((247 ('lee.egg-info', 'PKG-INFO', 'Name: lee\n'),248 ))249 test_files = (250 # Egg link251 ('', 'boom.egg-link', '/not-a-path/'),252 ('', 'bar.egg-link', temp_path_egg1),253 ('', 'lee.egg-link', temp_path_egg2),254 # Dist info255 ('spam.dist-info', 'METADATA', 'Name: spam\n'),256 ('spam.dist-info', 'RECORD', ''),257 ('spam.dist-info', 'INSTALLER', ''),258 # Egg info259 ('foo.egg-info', 'METADATA', 'Name: foo\n'),260 # Direct file261 ('', 'cheese.egg-info', 'Name: cheese\n'),262 )263 temp_path2, fpaths = _create_test_files(test_files)264 output_names = ['boom', 'bar', 'lee', 'spam', 'spam', 'spam', 'foo', 'cheese']265 for i, fpath in enumerate(fpaths):266 output = PythonDistribution.init(temp_path2, basename(fpath), "1.1")267 output = output.prefix_record268 pprint(output.dump())269 if output:270 assert output.name == output_names[i]271 assert output.name == output_names[i]272 else:273 assert output is None274# Metadata275# -----------------------------------------------------------------------------276def test_metadata_keys():277 cls = PythonDistributionMetadata278 for keymap in cls.SINGLE_USE_KEYS, cls.MULTIPLE_USE_KEYS:279 for key, value in keymap.items():280 assert key.lower().replace('-', '_') == value281def test_metadata_process_path():282 name = 'META'283 test_files = (284 ('', name, 'Name: eggs\n'),285 )286 temp_path, fpaths = _create_test_files(test_files)287 func = PythonDistributionMetadata._process_path288 # Test valid directory289 output = func(temp_path, [name])290 expected_output = fpaths[0]291 _print_output(output, expected_output)292 assert output == expected_output293 # Test valid directory (empty files)294 output = func(temp_path, [])295 expected_output = None296 _print_output(output, expected_output)297 assert output == expected_output298 # Test valid directory (file order)299 output = func(temp_path, ['something', name, 'something-else'])300 expected_output = fpaths[0]301 _print_output(output, expected_output)302 assert output == expected_output303 # Test valid file304 output = func(fpaths[0], [name])305 expected_output = fpaths[0]306 _print_output(output, expected_output)307 assert output == expected_output308def test_metadata_read_metadata():309 func = PythonDistributionMetadata._read_metadata310 # Test existing file unknown key311 temp_path, fpaths = _create_test_files((312 ('', 'PKG-INFO', 'Unknown-Key: unknown\n'),313 ))314 output = func(fpaths[0])315 expected_output = odict()316 _print_output(output, expected_output)317 assert output == expected_output318 # Test existing file known key319 temp_path, fpaths = _create_test_files((320 ('', 'PKG-INFO', 'Name: spam\n'),321 ))322 output = func(fpaths[0])323 expected_output = odict(name='spam')324 _print_output(output, expected_output)325 assert output == expected_output326 # Test non existing file327 test_fpath = '/foo/bar/METADATA'328 output = func(test_fpath)329 expected_output = odict()330 _print_output(output, expected_output)331 assert output == expected_output332def test_metadata():333 # Check warnings are raised for None path334 with pytest.warns(MetadataWarning):335 path = PythonDistributionMetadata._process_path(None, [])336 assert path is None337 # Check versions338 for fpath in METADATA_VERSION_PATHS:339 if not lexists(fpath):340 pytest.skip("test files not found: %s" % fpath)341 meta = PythonDistributionMetadata(fpath)342 a = meta.get_dist_requirements()343 b = meta.get_python_requirements()344 z = meta.get_external_requirements()345 c = meta.get_extra_provides()346 d = meta.get_dist_provides()347 e = meta.get_dist_obsolete()348 f = meta.get_classifiers()349 name = meta.name350 version = meta.version351 _print_output(fpath, meta._data, a, b, c, d, e, f, name, version)352 assert len(meta._data)353 assert name == 'BeagleVote'354 assert version == '1.0a2'355# Python Distributions356# -----------------------------------------------------------------------------357def test_basepydist_parse_requires_file_data():358 key = 'g'359 test_cases = (360 # (data, requirements, extras)361 ('', ([], [])),362 ('foo\n', (['foo'], [])),363 ('foo\n\n[:a == "a"]\nbar\n', (['foo', 'bar; a == "a"'], ['a'])),364 ('foo\n\n[a]\nbar\n', (['foo', 'bar; extra == "a"'], ['a'])),365 )366 func = PythonDistribution._parse_requires_file_data367 for data, (expected_reqs, expected_extras) in test_cases:368 output_reqs, output_extras = func(data, key)369 _print_output(repr(data), output_reqs, frozenset(expected_reqs))370 assert sorted(list(output_reqs)) == sorted(list(expected_reqs))371def test_basepydist_parse_entries_file_data():372 func = PythonDistribution._parse_entries_file_data373 data = '''374[a]375a = cli:main_1376[b.c]377b = cli:MAIN_2378[b.d]379C = cli:MAIN_3380'''381 expected_output = odict()382 expected_output['a'] = odict([('a', 'cli:main_1')])383 expected_output['b.c'] = odict([('b', 'cli:MAIN_2')])384 expected_output['b.d'] = odict([('C', 'cli:MAIN_3')])385 output = func(data)386 _print_output(output, expected_output)387 assert output == expected_output388def test_basepydist_load_requires_provides_file():389 temp_path, fpaths = _create_test_files((('', 'depends.txt', 'foo\n\n[a]\nbar\n'), ))390 dist = PythonEggInfoDistribution(temp_path, "1.8", None)391 exp_req, exp_extra = (['foo', 'bar; extra == "a"'], ['a'])392 req, extra = dist._load_requires_provides_file()393 _print_output((list(sorted(req)), extra), (list(sorted(exp_req)), exp_extra))394 assert (list(sorted(req)), extra) == (list(sorted(exp_req)), exp_extra)395def test_dist_get_paths():396 content = 'foo/bar,sha256=1,"45"\nfoo/spam,,\n'397 temp_path, fpaths = _create_test_files((('', 'SOURCES.txt', content), ))398 sp_dir = get_python_site_packages_short_path("2.7")399 dist = PythonEggInfoDistribution(temp_path, "2.7", None)400 output = dist.get_paths()401 expected_output = [(join_url(sp_dir, "foo", "bar"), '1', 45),402 (join_url(sp_dir, "foo", "spam"), None, None)]403 _print_output(output, expected_output)404 assert output == expected_output405def test_dist_get_paths_no_paths():406 temp_path = tempfile.mkdtemp()407 dist = PythonEggInfoDistribution(temp_path, "2.7", None)408 with pytest.raises(EnvironmentError):409 paths = dist.get_paths()410def test_get_dist_requirements():411 test_files = (412 ('', 'METADATA', 'Name: spam\n'),413 ('', 'requires.txt', 'foo >1.0'),414 )415 temp_path, fpaths = _create_test_files(test_files)416 dist = PythonEggInfoDistribution(temp_path, "2.7", None)417 output = dist.get_dist_requirements()418 expected_output = frozenset({'foo >1.0'})419 _print_output(output, expected_output)420 assert output == expected_output421def test_get_extra_provides():422 test_files = (423 ('', 'METADATA', 'Name: spam\n'),424 ('', 'requires.txt', 'foo >1.0\n[a]\nbar\n'),425 )426 temp_path, fpaths = _create_test_files(test_files)427 dist = PythonEggInfoDistribution(temp_path, "2.7", None)428 output = dist.get_extra_provides()429 expected_output = ['a']430 _print_output(output, expected_output)431 assert output == expected_output432def test_get_entry_points():433 test_files = (434 ('', 'METADATA', 'Name: spam\n'),435 ('', 'entry_points.txt', '[console_scripts]\ncheese = cli:main\n'),436 )437 temp_path, fpaths = _create_test_files(test_files)438 dist = PythonEggInfoDistribution(temp_path, "2.7", None)439 output = dist.get_entry_points()440 expected_output = odict(console_scripts=odict(cheese='cli:main'))441 _print_output(output, expected_output)442 assert output == expected_output443def test_pydist_check_files():444 test_files = (445 ('', 'METADATA', '1'),446 ('', 'RECORD', '2'),447 ('', 'INSTALLER', '3'),448 )449 # Test mandatory files found450 temp_path, fpaths = _create_test_files(test_files)451 PythonInstalledDistribution(temp_path, "2.7", None)452 # Test mandatory file not found453 os.remove(fpaths[0])454 with pytest.raises(EnvironmentError) as exc:455 PythonInstalledDistribution(temp_path, "2.7", None)456 assert exc.value.errno == ENOENT457def test_python_dist_info():458 test_files = (459 ('', 'METADATA', ('Name: zoom\n'460 'Requires-Python: ==2.7\n'461 'Requires-External: C\n'462 )463 ),464 ('', 'RECORD', 'foo/bar,sha256=1,"45"\nfoo/spam,,\n'),465 ('', 'INSTALLER', ''),466 )467 # Test mandatory files found468 temp_path, fpaths = _create_test_files(test_files)469 dist = PythonInstalledDistribution(temp_path, "RECORD", "2.7")470 paths = dist.get_paths()471 _print_output(paths)472 assert len(paths) == 2473 assert dist.get_python_requirements() == frozenset(['==2.7'])474 assert dist.get_external_requirements() == frozenset(['C'])475def test_python_dist_info_conda_dependencies():476 test_files = (477 ('', 'METADATA', ('Name: foo\n'478 'Requires-Python: >2.7,<5.0\n'479 'Requires-Dist: bar ; python_version == "2.7"\n'480 'Requires-Dist: spam ; python_version == "4.9"\n'481 'Provides-Extra: docs\n'482 'Requires-Dist: cheese >=1.0; extra == "docs"\n'483 )484 ),485 )486 temp_path, fpaths = _create_test_files(test_files)487 path = os.path.dirname(fpaths[0])488 dist = PythonEggInfoDistribution(path, "4.9", None)489 depends, constrains = dist.get_conda_dependencies()490 assert 'python 4.9.*' in depends491 assert 'bar' not in depends492 assert 'spam' in depends493 assert 'cheese >=1.0' in constrains494 dist = PythonEggInfoDistribution(path, "2.7", None)495 depends, constrains = dist.get_conda_dependencies()496 assert 'python 2.7.*' in depends497 assert 'bar' in depends498 assert 'spam' not in depends499 assert 'cheese >=1.0' in constrains500 dist = PythonEggInfoDistribution(path, "3.4", None)501 depends, constrains = dist.get_conda_dependencies()502 assert 'python 3.4.*' in depends503 assert 'bar' not in depends504 assert 'spam' not in depends505 assert 'cheese >=1.0' in constrains506def test_python_dist_info_conda_dependencies_2():507 test_files = (508 ('', 'METADATA', ('Name: foo\n')),509 )510 temp_path, fpaths = _create_test_files(test_files)511 path = os.path.dirname(fpaths[0])512 dist = PythonEggInfoDistribution(path, "4.9", None)513 depends, constrains = dist.get_conda_dependencies()514 assert 'python 4.9.*' in depends515def test_python_dist_info_conda_dependencies_3():516 test_files = (517 ('', 'METADATA', ('Name: foo\n')),518 )519 temp_path, fpaths = _create_test_files(test_files)520 path = os.path.dirname(fpaths[0])521 dist = PythonEggInfoDistribution(path, "3.6", None)522 depends, constrains = dist.get_conda_dependencies()523 assert "python 3.6.*" in depends524def test_python_dist_egg_path():525 test_files = (526 ('', 'installed-files.txt', 'foo/bar\nfoo/spam\n'),527 )528 temp_path, fpaths = _create_test_files(test_files)529 path = os.path.dirname(fpaths[0])530 dist = PythonEggInfoDistribution(path, "2.7", None)531 paths = dist.get_paths()532 _print_output(paths)533 assert len(paths) == 2534def test_python_dist_egg_fpath():535 test_files = (536 ('', 'zoom.egg-info', 'Name: Zoom\nVersion: 1.0\n'),537 )538 temp_path, fpaths = _create_test_files(test_files)539 dist = PythonEggInfoDistribution(fpaths[0], "2.2", None)540 assert dist.name == 'Zoom'541 assert dist.norm_name == 'zoom'542 assert dist.version == '1.0'543# Markers544# -----------------------------------------------------------------------------545def test_evaluate_marker():546 # See: https://www.python.org/dev/peps/pep-0508/#complete-grammar547 # ((marker_expr, context, extras, expected_output), ...)548 test_cases = (549 # Valid context550 ('spam == "1.0"', {'spam': '1.0'}, True),551 # Should parse as (a and b) or c552 ("a=='a' and b=='b' or c=='c'", {'a': 'a', 'b': 'b', 'c': ''}, True),...

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 avocado 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