def exec_in_dir(base_command, directory, options='', tee=None, exit_on_failure=True): if tee: tee = sum_paths(directory, tee) # NOTE: Path doesn't seem to be compatible with cd here, # see PR https://j.mp/3dq3nvf directory = str(directory) config = Config() config.load_shell_env() context = Context(config=config) # with context.cd(str(directory)): with context.cd(directory): exec(base_command, options, exit_on_failure, tee=tee, context=context)
def test_config_instead_context(self): @task @get_params_from_ctx def myfunc(cfg, x=Lazy('ctx.x')): return x assert myfunc(Config(defaults={'x': True})) is True
def _run(self, pty): runner = _KeyboardInterruptingFastLocal(Context(config=Config())) try: runner.run(_, pty=pty) except KeyboardInterrupt: pass return runner
def honors_runner_config_setting(self): runner_class = Mock() config = Config({'runners': {'local': runner_class}}) c = Context(config) c.run('foo') assert runner_class.mock_calls == [ call(c), call().run('foo'), ]
def _run_with_mocked_interrupt(self, klass): runner = klass(Context(config=Config())) runner.send_interrupt = Mock() try: runner.run(_) except: pass return runner
def init_still_acts_like_superclass_init(self): # No required args assert isinstance(MockContext().config, Config) config = Config(overrides={"foo": "bar"}) # Posarg assert MockContext(config).config is config # Kwarg assert MockContext(config=config).config is config
def init_still_acts_like_superclass_init(self): # No required args ok_(isinstance(MockContext().config, Config)) config = Config(overrides={'foo': 'bar'}) # Posarg ok_(MockContext(config).config is config) # Kwarg ok_(MockContext(config=config).config is config)
def test_with_option_dryrun_on_cmdline(self, capsys): config = Config(DEFAULT_CONFIG) ctx = EchoMockContext(run=Result(), config=config) git_clean(ctx, dry_run=True) captured = capsys.readouterr() expected = "INVOKED: git clean --interactive --dry-run ." assert expected in captured.out
def _expect_version(self, expected, config_val=None): config = { 'package': 'fakepackage', } if config_val is not None: config['version_module'] = config_val c = MockContext(Config(overrides={'packaging': config})) assert load_version(c) == expected
def echo_hides_extra_sudo_flags(self): skip() # see TODO in sudo() re: clean output display config = Config(overrides={"runner": _Dummy}) Context(config=config).sudo("nope", echo=True) output = sys.stdout.getvalue() sys.__stderr__.write(repr(output) + "\n") assert "-S" not in output assert Context().sudo.prompt not in output assert "sudo nope" in output
def callable_default(): ctx = Context(Config({"x": 1, "z": 2})) @magictask(params_from="ctx") def test_task(ctx, x, y=lambda ctx: ctx.z): return x, y r = test_task(ctx) assert r[0] == 1 and r[1] == 2
def expand_ctx_path(): ctx = Context(Config({"random": {"test_task": {"x": 1, "y": 2}}})) @magictask(params_from="ctx.random.test_task") def test_task(ctx, x, y=None): return x, y r = test_task(ctx) assert r[0] == 1 and r[1] == 2
def test_with_option_force_on_cmdline(self, capsys): config = Config(DEFAULT_CONFIG) ctx = EchoMockContext(run=Result(), config=config) # ctx.config.git_clean.interactive = False git_clean(ctx, force=True) captured = capsys.readouterr() expected = "INVOKED: git clean --interactive --force ." assert expected in captured.out
def proper_order_false(): ctx = Context(Config({"x": False})) @magictask(params_from="ctx") def test_task(ctx, x=True): return x r = test_task(ctx) assert not r
def echo_hides_extra_sudo_flags(self, getpass): skip() # see TODO in sudo() re: clean output display config = Config(overrides={'runner': _Dummy}) Context(config=config).sudo('nope', echo=True) output = sys.stdout.getvalue() sys.__stderr__.write(repr(output) + "\n") ok_("-S" not in output) ok_(Context().sudo.prompt not in output) ok_("sudo nope" in output)
def test_with_invoke_option_dry_on_cmdline(self, capsys): config = Config(DEFAULT_CONFIG) ctx = EchoMockContext(run=Result(), config=config) ctx.config.run.dry = True # CMDLINE-EMULATION git_clean(ctx) captured = capsys.readouterr() expected = "INVOKED: git clean --interactive --dry-run ." assert expected in captured.out
def test_without_options_if_config_disables_interactive_mode(self, capsys): config = Config(DEFAULT_CONFIG) ctx = EchoMockContext(run=Result(), config=config) ctx.config.git_clean.interactive = False git_clean(ctx) captured = capsys.readouterr() expected = "INVOKED: git clean ." assert expected in captured.out
def test_with_option_dryrun_in_configfile(self, capsys): config = Config(DEFAULT_CONFIG) ctx = EchoMockContext(run=Result(), config=config) # ctx.config.git_clean.interactive = False ctx.config.git_clean.dry_run = True git_clean(ctx) captured = capsys.readouterr() expected = "INVOKED: git clean --interactive --dry-run ." assert expected in captured.out
def _create_connection(self): return KubernetesRunner( Context( Config( overrides={ "k8s_pod": self.pod, "k8s_container": self.container, "k8s_namespace": self.namespace, "k8s_configuration": self.k8s_configuration, })))
def base_case(self): # NOTE: Assumes a user whose password is 'mypass' has been created # & added to passworded (not passwordless) sudo configuration; and # that this user is the one running the test suite. Only for # running on Travis, basically. if not os.environ.get("TRAVIS", False): skip() config = Config({"sudo": {"password": "******"}}) result = Context(config=config).sudo("whoami", hide=True) assert result.stdout.strip() == "root"
def base_case(self): # NOTE: Assumes a user whose password is 'mypass' has been created # & added to passworded (not passwordless) sudo configuration; and # that this user is the one running the test suite. Only for # running on Travis, basically. if not os.environ.get('TRAVIS', False): skip() config = Config(overrides={'sudo': {'password': '******'}}) result = Context(config=config).sudo('whoami', hide=True) eq_(result.stdout.strip(), 'root')
def _runner(out='', err='', **kwargs): klass = kwargs.pop('klass', _Dummy) runner = klass(Context(config=Config(overrides=kwargs))) if 'exits' in kwargs: runner.returncode = Mock(return_value=kwargs.pop('exits')) out_file = BytesIO(b(out)) err_file = BytesIO(b(err)) runner.read_proc_stdout = out_file.read runner.read_proc_stderr = err_file.read return runner
def global_defaults(): base_defaults = Config.global_defaults() overrides = { "tasks": {"collection_name": PROG_NAME}, "run": { "shell": "C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\powershell.exe", "echo": True, "debug": True, }, } return merge_dicts(base=base_defaults, updates=overrides)
def output(c): ''' 可以跳转到定义处,查看所有默认配置 ''' print(Config.global_defaults()) print("\n") print(c.tasks.collection_name) print(c.config.tasks.collection_name) print(c['tasks']) print(c.config.other) ''' 直接修改context中已有内容, 但是没有生效? ''' c.tasks.auto_dash_names = False
def always_runs_no_matter_what(self): class _ExceptingRunner(_Dummy): def wait(self): raise OhNoz() runner = _ExceptingRunner(context=Context(config=Config())) runner.stop = Mock() try: runner.run(_) except OhNoz: runner.stop.assert_called_once_with() else: assert False, "_ExceptingRunner did not except!"
def load_name_defaults_to_config_tasks_collection_name(self): "load() name defaults to config.tasks.collection_name" class MockLoader(_BasicLoader): def find(self, name): # Sanity assert name == "simple_ns_list" return super(MockLoader, self).find(name) config = Config({"tasks": {"collection_name": "simple_ns_list"}}) loader = MockLoader(config=config) # More sanity: expect simple_ns_list.py (not tasks.py) mod, path = loader.load() assert mod.__file__ == os.path.join(support, "simple_ns_list.py")
def _runner(out='', err='', **kwargs): klass = kwargs.pop('klass', Dummy) runner = klass(Context(config=Config(overrides=kwargs))) if 'exits' in kwargs: runner.returncode = Mock(return_value=kwargs.pop('exits')) out_file = StringIO(out) err_file = StringIO(err) def out_reader(count): return out_file.read(count) def err_reader(count): return err_file.read(count) runner.stdout_reader = lambda: out_reader runner.stderr_reader = lambda: err_reader return runner
def expand_ctx(ctx): ctx = Context(Config({"magic": {"test_task": {"x": 1, "y": 2}}})) # Dirty remap since qualname on py3 does a better job. ctx.magic.expand_ctx = { "<locals>": { "test_task": lambda ctx: ctx.magic.test_task } } @magictask def test_task(ctx, x, y=None): return x, y r = test_task(ctx) assert r[0] == 1 and r[1] == 2
def load_name_defaults_to_config_tasks_collection_name(self): "load() name defaults to config.tasks.collection_name" class MockLoader(_BasicLoader): def find(self, name): # Sanity assert name == 'simple_ns_list' return super(MockLoader, self).find(name) config = Config({'tasks': {'collection_name': 'simple_ns_list'}}) loader = MockLoader(config=config) # More sanity: expect a task from simple_ns_list (and not 'foo' from # _support/tasks.py) mod = loader.load() assert 'z_toplevel' in mod
def config_only(self, Local): runner = Local.return_value # Set a config-driven list of watchers watcher = self.watcher_klass() overrides = {"run": {"watchers": [watcher]}} config = Config(overrides=overrides) Context(config=config).sudo("whoami") # Expect that sudo() extracted that config value & put it into # the kwarg level. (See comment in sudo() about why...) watchers = runner.run.call_args[1]["watchers"] # Will raise ValueError if not in the list watchers.remove(watcher) # Only remaining item in list should be our sudo responder assert len(watchers) == 1 assert isinstance(watchers[0], FailingResponder) assert watchers[0].pattern == self.escaped_prompt