Best Python code snippet using pytest
test_utils.py
Source:test_utils.py
...35 return os.path.abspath(os.path.join(maas_root, *path))36class TestLocateConfig(MAASTestCase):37 """Tests for `locate_config`."""38 def test_returns_branch_etc_maas(self):39 self.assertEqual(get_run_path("etc/maas"), locate_config())40 self.assertThat(locate_config(), DirExists())41 def test_defaults_to_global_etc_maas_if_variable_is_unset(self):42 self.useFixture(EnvironmentVariableFixture("MAAS_ROOT", None))43 self.assertEqual("/etc/maas", locate_config())44 def test_defaults_to_global_etc_maas_if_variable_is_empty(self):45 self.useFixture(EnvironmentVariableFixture("MAAS_ROOT", ""))46 self.assertEqual("/etc/maas", locate_config())47 def test_returns_absolute_path(self):48 self.useFixture(EnvironmentVariableFixture("MAAS_ROOT", "."))49 self.assertTrue(os.path.isabs(locate_config()))50 def test_locates_config_file(self):51 filename = factory.make_string()52 self.assertEqual(53 get_run_path("etc/maas/", filename), locate_config(filename)54 )55 def test_locates_full_path(self):56 path = [factory.make_string() for counter in range(3)]57 self.assertEqual(58 get_run_path("etc/maas/", *path), locate_config(*path)59 )60 def test_normalizes_path(self):61 self.assertEqual(62 get_run_path("etc/maas/bar/szot"),63 locate_config("foo/.././bar///szot"),64 )65class TestLocateTemplate(MAASTestCase):66 """Tests for `locate_template`."""67 def test_returns_test_path(self):68 self.assertEqual(69 os.path.abspath(70 os.path.join(71 os.path.dirname(__file__), "..", "..", "templates"72 )73 ),74 locate_template(""),75 )76class TestSafe(MAASTestCase):77 """Test `Safe`."""...
apache_test.py
Source:apache_test.py
...111 letshelp_le_apache.verify_config(args)112 self.assertRaises(SystemExit, letshelp_le_apache.verify_config, args)113 self.assertRaises(SystemExit, letshelp_le_apache.verify_config, args)114 @mock.patch(_MODULE_NAME + ".subprocess.Popen")115 def test_locate_config(self, mock_popen):116 mock_popen().communicate.side_effect = [117 OSError, ("bad_output", None), (_COMPILE_SETTINGS, None)]118 self.assertRaises(119 SystemExit, letshelp_le_apache.locate_config, "ctl")120 self.assertRaises(121 SystemExit, letshelp_le_apache.locate_config, "ctl")122 server_root, config_file = letshelp_le_apache.locate_config("ctl")123 self.assertEqual(server_root, "/etc/apache2")124 self.assertEqual(config_file, "apache2.conf")125 @mock.patch(_MODULE_NAME + ".argparse")126 def test_get_args(self, mock_argparse):127 argv = ["-d", "/etc/apache2"]128 mock_argparse.ArgumentParser.return_value = _create_mock_parser(argv)129 self.assertRaises(SystemExit, letshelp_le_apache.get_args)130 server_root = "/etc/apache2"131 config_file = server_root + "/apache2.conf"132 argv = ["-d", server_root, "-f", config_file]133 mock_argparse.ArgumentParser.return_value = _create_mock_parser(argv)134 args = letshelp_le_apache.get_args()135 self.assertEqual(args.apache_ctl, "apachectl")136 self.assertEqual(args.server_root, server_root)...
findpaths.py
Source:findpaths.py
...60 def make_scalar(v: object) -> Union[str, List[str]]:61 return v if isinstance(v, list) else str(v)62 return {k: make_scalar(v) for k, v in result.items()}63 return None64def locate_config(65 args: Iterable[Path],66) -> Tuple[67 Optional[Path], Optional[Path], Dict[str, Union[str, List[str]]],68]:69 """Search in the list of arguments for a valid ini-file for pytest,70 and return a tuple of (rootdir, inifile, cfg-dict)."""71 config_names = [72 "pytest.ini",73 "pyproject.toml",74 "tox.ini",75 "setup.cfg",76 ]77 args = [x for x in args if not str(x).startswith("-")]78 if not args:79 args = [Path.cwd()]80 for arg in args:81 argpath = absolutepath(arg)82 for base in (argpath, *argpath.parents):83 for config_name in config_names:84 p = base / config_name85 if p.is_file():86 ini_config = load_config_dict_from_file(p)87 if ini_config is not None:88 return base, p, ini_config89 return None, None, {}90def get_common_ancestor(paths: Iterable[Path]) -> Path:91 common_ancestor: Optional[Path] = None92 for path in paths:93 if not path.exists():94 continue95 if common_ancestor is None:96 common_ancestor = path97 else:98 if common_ancestor in path.parents or path == common_ancestor:99 continue100 elif path in common_ancestor.parents:101 common_ancestor = path102 else:103 shared = commonpath(path, common_ancestor)104 if shared is not None:105 common_ancestor = shared106 if common_ancestor is None:107 common_ancestor = Path.cwd()108 elif common_ancestor.is_file():109 common_ancestor = common_ancestor.parent110 return common_ancestor111def get_dirs_from_args(args: Iterable[str]) -> List[Path]:112 def is_option(x: str) -> bool:113 return x.startswith("-")114 def get_file_part_from_node_id(x: str) -> str:115 return x.split("::")[0]116 def get_dir_from_path(path: Path) -> Path:117 if path.is_dir():118 return path119 return path.parent120 def safe_exists(path: Path) -> bool:121 # This can throw on paths that contain characters unrepresentable at the OS level,122 # or with invalid syntax on Windows (https://bugs.python.org/issue35306)123 try:124 return path.exists()125 except OSError:126 return False127 # These look like paths but may not exist128 possible_paths = (129 absolutepath(get_file_part_from_node_id(arg))130 for arg in args131 if not is_option(arg)132 )133 return [get_dir_from_path(path) for path in possible_paths if safe_exists(path)]134CFG_PYTEST_SECTION = "[pytest] section in {filename} files is no longer supported, change to [tool:pytest] instead."135def determine_setup(136 inifile: Optional[str],137 args: Sequence[str],138 rootdir_cmd_arg: Optional[str] = None,139 config: Optional["Config"] = None,140) -> Tuple[Path, Optional[Path], Dict[str, Union[str, List[str]]]]:141 rootdir = None142 dirs = get_dirs_from_args(args)143 if inifile:144 inipath_ = absolutepath(inifile)145 inipath: Optional[Path] = inipath_146 inicfg = load_config_dict_from_file(inipath_) or {}147 if rootdir_cmd_arg is None:148 rootdir = get_common_ancestor(dirs)149 else:150 ancestor = get_common_ancestor(dirs)151 rootdir, inipath, inicfg = locate_config([ancestor])152 if rootdir is None and rootdir_cmd_arg is None:153 for possible_rootdir in (ancestor, *ancestor.parents):154 if (possible_rootdir / "setup.py").is_file():155 rootdir = possible_rootdir156 break157 else:158 if dirs != [ancestor]:159 rootdir, inipath, inicfg = locate_config(dirs)160 if rootdir is None:161 if config is not None:162 cwd = config.invocation_params.dir163 else:164 cwd = Path.cwd()165 rootdir = get_common_ancestor([cwd, ancestor])166 is_fs_root = os.path.splitdrive(str(rootdir))[1] == "/"167 if is_fs_root:168 rootdir = ancestor169 if rootdir_cmd_arg:170 rootdir = absolutepath(os.path.expandvars(rootdir_cmd_arg))171 if not rootdir.is_dir():172 raise UsageError(173 "Directory '{}' not found. Check your '--rootdir' option.".format(...
conf_file.py
Source:conf_file.py
...20CONFIG_NAME = '.vmpooler.conf'21#===================================================================================================22# Functions: Public23#===================================================================================================24def locate_config():25 """26 Locate the configuration file path.27 Args:28 |None|29 Returns:30 |str| = The path to the configuration file.31 Raises:32 |RuntimeError| = Unsupported platform.33 """34 system_platform = system()35 # Locate path for configuration file.36 if (system_platform in ['Linux', 'Darwin']) or ('CYGWIN' in system_platform):37 config_path = join(environ['HOME'], CONFIG_NAME)38 elif system_platform == 'Windows':39 try:40 config_path = join(environ['APPDATA'], CONFIG_NAME)41 except KeyError:42 raise RuntimeError('Windows 2008 or greater is required to run this program!')43 else:44 raise RuntimeError('The platform "{}" is not supported '45 'by this program!'.format(system_platform))46 return config_path47def write_config(config):48 """49 Write the configuration file for the program.50 Args:51 config |{str:str}| = A dictionary of settings for the configuration file.52 Returns:53 |None|54 Raises:55 |IOError| = Failed to write the configuration file.56 """57 config_path = locate_config()58 with open(config_path, 'w') as f:59 f.write(dumps(config))60def load_config():61 """62 Load the configuration file for the program.63 Args:64 |None|65 Returns:66 |{str:str}| = A dictionary of settings from the configuration file.67 Raises:68 |RuntimeError| = Unsupported platform, default configuration file or69 invalid configuration file.70 """71 config_path = locate_config()72 default_config = {'auth_token': ''}73 # Create configuration file if none exists.74 if not isfile(config_path):75 write_config(default_config)76 # Read configuration file.77 try:78 with open(config_path, 'r') as f:79 config = loads(f.read())80 except ValueError:81 # Invalid JSON file82 write_config(default_config)83 raise RuntimeError('The "{}" configuration file is invalid! '84 'Replaced with default configuration file!\n'.format(locate_config()))85 return config86def get_auth_token(config):87 """Ensures an auth token exists. If a token is already present in the config, returns the token88 Otherwise prompts the user to create one or set one manually.89 Args:90 config |{str:str}| = A dictionary of settings from the configuration file.91 Returns:92 auth_token |str| = The user's auth token.93 Raises:94 |None|95 """96 if "auth_token" not in config or len(config["auth_token"]) == 0:97 error = ('Error: No authentication token found!\n\n'98 'Run the "token create" subcommand or manually update the\n'...
Looking for an in-depth tutorial around pytest? LambdaTest covers the detailed pytest tutorial that has everything related to the pytest, from setting up the pytest framework to automation testing. Delve deeper into pytest testing by exploring advanced use cases like parallel testing, pytest fixtures, parameterization, executing multiple test cases from a single file, and more.
Skim our below pytest tutorial playlist to get started with automation testing using the pytest framework.
https://www.youtube.com/playlist?list=PLZMWkkQEwOPlcGgDmHl8KkXKeLF83XlrP
Get 100 minutes of automation test minutes FREE!!