我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用fixtures.EnvironmentVariable()。
def setUp(self): super(SkipFileWrites, self).setUp() self.temp_path = self.useFixture(fixtures.TempDir()).path self.root_dir = os.path.abspath(os.path.curdir) self.git_dir = os.path.join(self.root_dir, ".git") if not os.path.exists(self.git_dir): self.skipTest("%s is missing; skipping git-related checks" % self.git_dir) return self.filename = os.path.join(self.temp_path, self.filename) self.option_dict = dict() if self.option_key is not None: self.option_dict[self.option_key] = ('setup.cfg', self.option_value) self.useFixture( fixtures.EnvironmentVariable(self.env_key, self.env_value))
def test_wsgi_script_install(self): """Test that we install a non-pkg-resources wsgi script.""" if os.name == 'nt': self.skipTest('Windows support is passthrough') stdout, _, return_code = self.run_setup( 'install', '--prefix=%s' % self.temp_dir) self.useFixture( fixtures.EnvironmentVariable( 'PYTHONPATH', ".:%s/lib/python%s.%s/site-packages" % ( self.temp_dir, sys.version_info[0], sys.version_info[1]))) self._check_wsgi_install_content(stdout)
def test_console_script_install(self): """Test that we install a non-pkg-resources console script.""" if os.name == 'nt': self.skipTest('Windows support is passthrough') stdout, _, return_code = self.run_setup( 'install_scripts', '--install-dir=%s' % self.temp_dir) self.useFixture( fixtures.EnvironmentVariable('PYTHONPATH', '.')) self.check_script_install(stdout)
def test_console_script_develop(self): """Test that we develop a non-pkg-resources console script.""" if os.name == 'nt': self.skipTest('Windows support is passthrough') self.useFixture( fixtures.EnvironmentVariable( 'PYTHONPATH', ".:%s" % self.temp_dir)) stdout, _, return_code = self.run_setup( 'develop', '--install-dir=%s' % self.temp_dir) self.check_script_install(stdout)
def setUp(self): super(GitLogsTest, self).setUp() self.temp_path = self.useFixture(fixtures.TempDir()).path self.root_dir = os.path.abspath(os.path.curdir) self.git_dir = os.path.join(self.root_dir, ".git") self.useFixture( fixtures.EnvironmentVariable('SKIP_GENERATE_AUTHORS')) self.useFixture( fixtures.EnvironmentVariable('SKIP_WRITE_GIT_CHANGELOG'))
def test_parse_requirements_override_with_env(self): with open(self.tmp_file, 'w') as fh: fh.write("foo\nbar") self.useFixture( fixtures.EnvironmentVariable('PBR_REQUIREMENTS_FILES', self.tmp_file)) self.assertEqual(['foo', 'bar'], packaging.parse_requirements())
def setUp(self): # Integration tests need a higher default - big repos can be slow to # clone, particularly under guest load. env = fixtures.EnvironmentVariable( 'OS_TEST_TIMEOUT', os.environ.get('OS_TEST_TIMEOUT', '600')) with env: super(TestIntegration, self).setUp() base._config_git()
def test_wsgi_script_run(self): """Test that we install a runnable wsgi script. This test actually attempts to start and interact with the wsgi script in question to demonstrate that it's a working wsgi script using simple server. It's a bit hokey because of process management that has to be done. """ self.skipTest("Test skipped until we can determine a reliable " "way to capture subprocess stdout without blocking") if os.name == 'nt': self.skipTest('Windows support is passthrough') stdout, _, return_code = self.run_setup( 'install', '--prefix=%s' % self.temp_dir) self.useFixture( fixtures.EnvironmentVariable( 'PYTHONPATH', ".:%s/lib/python%s.%s/site-packages" % ( self.temp_dir, sys.version_info[0], sys.version_info[1]))) # NOTE(sdague): making python unbuffered is critical to # getting output out of the subprocess. self.useFixture( fixtures.EnvironmentVariable( 'PYTHONUNBUFFERED', '1')) self._check_wsgi_install_content(stdout) # Live test run the scripts and see that they respond to wsgi # requests. self._test_wsgi()
def setUp(self): super(BaseTestCase, self).setUp() test_timeout = os.environ.get('OS_TEST_TIMEOUT', 30) try: test_timeout = int(test_timeout) except ValueError: # If timeout value is invalid, fail hard. print("OS_TEST_TIMEOUT set to invalid value" " defaulting to no timeout") test_timeout = 0 if test_timeout > 0: self.useFixture(fixtures.Timeout(test_timeout, gentle=True)) if os.environ.get('OS_STDOUT_CAPTURE') in options.TRUE_VALUES: stdout = self.useFixture(fixtures.StringStream('stdout')).stream self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout)) if os.environ.get('OS_STDERR_CAPTURE') in options.TRUE_VALUES: stderr = self.useFixture(fixtures.StringStream('stderr')).stream self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr)) self.log_fixture = self.useFixture( fixtures.FakeLogger('pbr')) # Older git does not have config --local, so create a temporary home # directory to permit using git config --global without stepping on # developer configuration. self.useFixture(fixtures.TempHomeDir()) self.useFixture(fixtures.NestedTempfile()) self.useFixture(fixtures.FakeLogger()) self.useFixture(fixtures.EnvironmentVariable('PBR_VERSION', '0.0')) self.temp_dir = self.useFixture(fixtures.TempDir()).path self.package_dir = os.path.join(self.temp_dir, 'testpackage') shutil.copytree(os.path.join(os.path.dirname(__file__), 'testpackage'), self.package_dir) self.addCleanup(os.chdir, os.getcwd()) os.chdir(self.package_dir) self.addCleanup(self._discard_testpackage)
def setUp(self): super(FakeJujuFixture, self).setUp() self._juju_home = self.useFixture(TempDir()) if self._logs_dir: # If we are given a logs dir, dump logs there self.useFixture(EnvironmentVariable( "FAKE_JUJU_LOGS_DIR", self._logs_dir)) else: # Otherwise just attatch them as testtools details self.addDetail( "log-file", content_from_file(self._fake_juju_log)) api_info = bootstrap_fake_juju(self._juju_home.path) self.uuid = api_info["environ-uuid"] self.address = api_info["state-servers"][0]
def putenv(self, key, value, raw=False): if not raw: key = self.env_prefix + "_" + key self.env[key] = value return self.useFixture(fixtures.EnvironmentVariable(key, value))
def setUp(self): super(TestSudoUID, self).setUp() # Always ensure that SUDO_UID is not set in the environment. self.useFixture(EnvironmentVariable("SUDO_UID")) # We probably can't set EUID to anything we want in tests so we must # capture calls that attempt to do so. self.patch_autospec(utils, "seteuid")
def test_sets_and_resets_euid(self): original_euid = os.geteuid() example_euid = original_euid + random.randrange(500, 1000) self.useFixture(EnvironmentVariable("SUDO_UID", str(example_euid))) with utils.sudo_uid(): self.assertThat(utils.seteuid, MockCalledOnceWith(example_euid)) self.assertThat(utils.seteuid, MockCalledWith(original_euid))
def test_sets_and_resets_euid_on_crash(self): original_euid = os.geteuid() example_euid = original_euid + random.randrange(500, 1000) self.useFixture(EnvironmentVariable("SUDO_UID", str(example_euid))) with ExpectedException(ZeroDivisionError): with utils.sudo_uid(): 0 / 0 # A very realistic example. self.assertThat(utils.seteuid, MockCalledWith(original_euid))
def setUp(self): super(TestSudoGID, self).setUp() # Always ensure that SUDO_GID is not set in the environment. self.useFixture(EnvironmentVariable("SUDO_GID")) # We probably can't set EGID to anything we want in tests so we must # capture calls that attempt to do so. self.patch_autospec(utils, "setegid")
def test_sets_and_resets_egid(self): original_egid = os.getegid() example_egid = original_egid + random.randrange(500, 1000) self.useFixture(EnvironmentVariable("SUDO_GID", str(example_egid))) with utils.sudo_gid(): self.assertThat(utils.setegid, MockCalledOnceWith(example_egid)) self.assertThat(utils.setegid, MockCalledWith(original_egid))
def test_get_dns_config_dir_defaults_to_etc_bind_maas(self): self.useFixture(EnvironmentVariable("MAAS_DNS_CONFIG_DIR")) self.assertThat( config.get_dns_config_dir(), MatchesAll( SamePath(locate_config("../bind/maas")), IsInstance(str), ))
def test_get_dns_config_dir_checks_environ_first(self): directory = self.make_dir() self.useFixture(EnvironmentVariable( "MAAS_DNS_CONFIG_DIR", directory)) self.assertThat( config.get_dns_config_dir(), MatchesAll( SamePath(directory), IsInstance(str), ))
def test_get_bind_config_dir_defaults_to_etc_bind_maas(self): self.useFixture(EnvironmentVariable("MAAS_BIND_CONFIG_DIR")) self.assertThat( config.get_bind_config_dir(), MatchesAll( SamePath(locate_config("../bind")), IsInstance(str), ))
def test_get_bind_config_dir_checks_environ_first(self): directory = self.make_dir() self.useFixture(EnvironmentVariable( "MAAS_BIND_CONFIG_DIR", directory)) self.assertThat( config.get_bind_config_dir(), MatchesAll( SamePath(directory), IsInstance(str), ))
def test_get_dns_root_port_defaults_to_954(self): self.useFixture(EnvironmentVariable("MAAS_DNS_RNDC_PORT")) self.assertEqual(954, config.get_dns_rndc_port())
def test_get_dns_default_controls_defaults_to_affirmative(self): self.useFixture(EnvironmentVariable("MAAS_DNS_DEFAULT_CONTROLS")) self.assertTrue(config.get_dns_default_controls())
def test_get_dns_default_controls_checks_environ_first(self): self.useFixture( EnvironmentVariable("MAAS_DNS_DEFAULT_CONTROLS", "0")) self.assertFalse(config.get_dns_default_controls())
def _get_snap_version(self, snap_yaml): """Arrange for `snap_yaml` to be loaded by `get_snap_version`. Puts `snap_yaml` at $tmpdir/meta/snap.yaml, sets SNAP=$tmpdir in the environment, then calls `get_snap_version`. """ snap_path = Path(self.make_dir()) snap_yaml_path = snap_path.joinpath("meta", "snap.yaml") snap_yaml_path.parent.mkdir() snap_yaml_path.write_text(snap_yaml, "utf-8") with EnvironmentVariable("SNAP", str(snap_path)): return snappy.get_snap_version()
def test__defaults_to_process_environment(self): name = factory.make_name("name") value = factory.make_name("value") with EnvironmentVariable(name, value): self.assertThat( select_c_utf8_locale(), ContainsDict({name: Equals(value)}), )
def test__defaults_to_process_environment(self): name = factory.make_name("name") value = factory.make_name("value") with EnvironmentVariable(name, value): self.assertThat( select_c_utf8_bytes_locale(), ContainsDict({ name.encode("ascii"): Equals(value.encode("ascii")), }), )
def test_removes_https_proxy_from_environment(self): https_proxy = factory.make_name("https-proxy") initial = EnvironmentVariable("https_proxy", https_proxy) self.useFixture(initial) # On entry, https_proxy is removed from the environment. with ProxiesDisabledFixture(): self.assertNotIn("https_proxy", os.environ) # On exit, http_proxy is restored. self.assertEqual(https_proxy, os.environ.get("https_proxy"))
def setUp(self): super(TestMAASRootFixture, self).setUp() self.skel = os.path.join(root, "run-skel") self.useFixture(EnvironmentVariable("MAAS_ROOT", "/"))
def setUp(self): super(DisplayFixture, self).setUp() self.process = Popen(self.command, stdin=PIPE, stdout=PIPE) self.display = self.process.stdout.readline().decode("ascii").strip() if not self.display or self.process.poll() is not None: raise CalledProcessError(self.process.returncode, self.command) self.useFixture(EnvironmentVariable("DISPLAY", self.display)) self.addCleanup(self.shutdown)
def setUp(self): super(ProxiesDisabledFixture, self).setUp() self.useFixture(EnvironmentVariable("http_proxy")) self.useFixture(EnvironmentVariable("https_proxy"))
def setUp(self): super(ChromiumWebDriverFixture, self).setUp() # Import late to avoid hard dependency. from selenium.webdriver.chrome.service import Service as ChromeService service = ChromeService( "/usr/lib/chromium-browser/chromedriver", 4444) # Set the LD_LIBRARY_PATH so the chrome driver can find the required # libraries. self.useFixture(EnvironmentVariable( "LD_LIBRARY_PATH", "/usr/lib/chromium-browser/libs")) service.start() # Stop service on cleanup. self.addCleanup(service.stop)
def _prepare_test_config(self): # Create a temporary directory where our test config will live # and insert it into the search path via OS_CLIENT_CONFIG_FILE. config_dir = self.useFixture(fixtures.TempDir()).path config_path = os.path.join(config_dir, "clouds.yaml") with open(config_path, "w") as conf: conf.write(CLOUD_CONFIG) self.useFixture(fixtures.EnvironmentVariable( "OS_CLIENT_CONFIG_FILE", config_path))
def test_output(self): self.useFixture(fx.EnvironmentVariable('OS_STDOUT_CAPTURE', '1')) self.useFixture(fx.EnvironmentVariable('OS_STDERR_CAPTURE', '1')) out = self.useFixture(fixtures.OutputStreamCapture()) sys.stdout.write("foo") sys.stderr.write("bar") self.assertEqual("foo", out.stdout) self.assertEqual("bar", out.stderr) # TODO(sdague): nuke the out and err buffers so it doesn't # make it to testr
def test_debug_logging(self): self.useFixture(fx.EnvironmentVariable('OS_DEBUG', '1')) stdlog = self.useFixture(fixtures.StandardLogging()) root = logging.getLogger() # there should no longer be a null handler self.assertEqual(1, len(root.handlers), root.handlers) log = logging.getLogger(__name__) log.info("at info") log.debug("at debug") self.assertIn("at info", stdlog.logger.output) self.assertIn("at debug", stdlog.logger.output)