| 1 |
import os |
| 2 |
import pickle |
| 3 |
import re |
| 4 |
import sys |
| 5 |
from unittest.mock import Mock, call, patch |
| 6 |
|
| 7 |
from _util import _Dummy, mock_subprocess |
| 8 |
from pytest import mark, raises, skip |
| 9 |
from pytest_relaxed import trap |
| 10 |
|
| 11 |
from invoke import ( |
| 12 |
AuthFailure, |
| 13 |
Config, |
| 14 |
Context, |
| 15 |
FailingResponder, |
| 16 |
MockContext, |
| 17 |
ResponseNotAccepted, |
| 18 |
Result, |
| 19 |
StreamWatcher, |
| 20 |
) |
| 21 |
|
| 22 |
local_path = "invoke.config.Local" |
| 23 |
_escaped_prompt = re.escape(Config().sudo.prompt) |
| 24 |
|
| 25 |
|
| 26 |
class Context_: |
| 27 |
class init: |
| 28 |
"__init__" |
| 29 |
|
| 30 |
def takes_optional_config_arg(self): |
| 31 |
# Meh-tastic doesn't-barf tests. MEH. |
| 32 |
Context() |
| 33 |
Context(config={"foo": "bar"}) |
| 34 |
|
| 35 |
def takes_optional_remainder_arg(self): |
| 36 |
# Tautology-tastic! |
| 37 |
assert Context(remainder="stuff!").remainder == "stuff!" |
| 38 |
|
| 39 |
class methods_exposed: |
| 40 |
def _expect_attr(self, attr): |
| 41 |
c = Context() |
| 42 |
assert hasattr(c, attr) and callable(getattr(c, attr)) |
| 43 |
|
| 44 |
class run: |
| 45 |
# NOTE: actual behavior of command running is tested in runners.py |
| 46 |
def exists(self): |
| 47 |
self._expect_attr("run") |
| 48 |
|
| 49 |
@patch(local_path) |
| 50 |
def defaults_to_Local(self, Local): |
| 51 |
c = Context() |
| 52 |
c.run("foo") |
| 53 |
assert Local.mock_calls == [call(c), call().run("foo")] |
| 54 |
|
| 55 |
def honors_runner_config_setting(self): |
| 56 |
runner_class = Mock() |
| 57 |
config = Config({"runners": {"local": runner_class}}) |
| 58 |
c = Context(config) |
| 59 |
c.run("foo") |
| 60 |
assert runner_class.mock_calls == [call(c), call().run("foo")] |
| 61 |
|
| 62 |
def sudo(self): |
| 63 |
self._expect_attr("sudo") |
| 64 |
|
| 65 |
class configuration_proxy: |
| 66 |
"Dict-like proxy for self.config" |
| 67 |
|
| 68 |
def setup_method(self): |
| 69 |
config = Config(defaults={"foo": "bar", "biz": {"baz": "boz"}}) |
| 70 |
self.c = Context(config=config) |
| 71 |
|
| 72 |
def direct_access_allowed(self): |
| 73 |
assert self.c.config.__class__ == Config |
| 74 |
assert self.c.config["foo"] == "bar" |
| 75 |
assert self.c.config.foo == "bar" |
| 76 |
|
| 77 |
def config_attr_may_be_overwritten_at_runtime(self): |
| 78 |
new_config = Config(defaults={"foo": "notbar"}) |
| 79 |
self.c.config = new_config |
| 80 |
assert self.c.foo == "notbar" |
| 81 |
|
| 82 |
def getitem(self): |
| 83 |
"___getitem__" |
| 84 |
assert self.c["foo"] == "bar" |
| 85 |
assert self.c["biz"]["baz"] == "boz" |
| 86 |
|
| 87 |
def getattr(self): |
| 88 |
"__getattr__" |
| 89 |
assert self.c.foo == "bar" |
| 90 |
assert self.c.biz.baz == "boz" |
| 91 |
|
| 92 |
def get(self): |
| 93 |
assert self.c.get("foo") == "bar" |
| 94 |
assert self.c.get("nope", "wut") == "wut" |
| 95 |
assert self.c.biz.get("nope", "hrm") == "hrm" |
| 96 |
|
| 97 |
def pop(self): |
| 98 |
assert self.c.pop("foo") == "bar" |
| 99 |
assert self.c.pop("foo", "notbar") == "notbar" |
| 100 |
assert self.c.biz.pop("baz") == "boz" |
| 101 |
|
| 102 |
def popitem(self): |
| 103 |
assert self.c.biz.popitem() == ("baz", "boz") |
| 104 |
del self.c["biz"] |
| 105 |
assert self.c.popitem() == ("foo", "bar") |
| 106 |
assert self.c.config == {} |
| 107 |
|
| 108 |
def del_(self): |
| 109 |
"del" |
| 110 |
del self.c["foo"] |
| 111 |
del self.c["biz"]["baz"] |
| 112 |
assert self.c.biz == {} |
| 113 |
del self.c["biz"] |
| 114 |
assert self.c.config == {} |
| 115 |
|
| 116 |
def clear(self): |
| 117 |
self.c.biz.clear() |
| 118 |
assert self.c.biz == {} |
| 119 |
self.c.clear() |
| 120 |
assert self.c.config == {} |
| 121 |
|
| 122 |
def setdefault(self): |
| 123 |
assert self.c.setdefault("foo") == "bar" |
| 124 |
assert self.c.biz.setdefault("baz") == "boz" |
| 125 |
assert self.c.setdefault("notfoo", "notbar") == "notbar" |
| 126 |
assert self.c.notfoo == "notbar" |
| 127 |
assert self.c.biz.setdefault("otherbaz", "otherboz") == "otherboz" |
| 128 |
assert self.c.biz.otherbaz == "otherboz" |
| 129 |
|
| 130 |
def update(self): |
| 131 |
self.c.update({"newkey": "newval"}) |
| 132 |
assert self.c["newkey"] == "newval" |
| 133 |
assert self.c.foo == "bar" |
| 134 |
self.c.biz.update(otherbaz="otherboz") |
| 135 |
assert self.c.biz.otherbaz == "otherboz" |
| 136 |
|
| 137 |
class cwd: |
| 138 |
def setup_method(self): |
| 139 |
self.c = Context() |
| 140 |
|
| 141 |
def simple(self): |
| 142 |
self.c.command_cwds = ["a", "b"] |
| 143 |
assert self.c.cwd == os.path.join("a", "b") |
| 144 |
|
| 145 |
def nested_absolute_path(self): |
| 146 |
self.c.command_cwds = ["a", "/b", "c"] |
| 147 |
assert self.c.cwd == os.path.join("/b", "c") |
| 148 |
|
| 149 |
def multiple_absolute_paths(self): |
| 150 |
self.c.command_cwds = ["a", "/b", "c", "/d", "e"] |
| 151 |
assert self.c.cwd == os.path.join("/d", "e") |
| 152 |
|
| 153 |
def home(self): |
| 154 |
self.c.command_cwds = ["a", "~b", "c"] |
| 155 |
assert self.c.cwd == os.path.join("~b", "c") |
| 156 |
|
| 157 |
class cd: |
| 158 |
_escaped_prompt = re.escape(Config().sudo.prompt) |
| 159 |
|
| 160 |
@patch(local_path) |
| 161 |
def should_apply_to_run(self, Local): |
| 162 |
runner = Local.return_value |
| 163 |
c = Context() |
| 164 |
with c.cd("foo"): |
| 165 |
c.run("whoami") |
| 166 |
|
| 167 |
cmd = "cd foo && whoami" |
| 168 |
assert runner.run.called, "run() never called runner.run()!" |
| 169 |
assert runner.run.call_args[0][0] == cmd |
| 170 |
|
| 171 |
@patch(local_path) |
| 172 |
def should_apply_to_sudo(self, Local): |
| 173 |
runner = Local.return_value |
| 174 |
c = Context() |
| 175 |
with c.cd("foo"): |
| 176 |
c.sudo("whoami") |
| 177 |
|
| 178 |
cmd = "sudo -S -p '[sudo] password: ' cd foo && whoami" |
| 179 |
assert runner.run.called, "sudo() never called runner.run()!" |
| 180 |
assert runner.run.call_args[0][0] == cmd |
| 181 |
|
| 182 |
@patch(local_path) |
| 183 |
def should_occur_before_prefixes(self, Local): |
| 184 |
runner = Local.return_value |
| 185 |
c = Context() |
| 186 |
with c.prefix("source venv"): |
| 187 |
with c.cd("foo"): |
| 188 |
c.run("whoami") |
| 189 |
|
| 190 |
cmd = "cd foo && source venv && whoami" |
| 191 |
assert runner.run.called, "run() never called runner.run()!" |
| 192 |
assert runner.run.call_args[0][0] == cmd |
| 193 |
|
| 194 |
@patch(local_path) |
| 195 |
def should_use_finally_to_revert_changes_on_exceptions(self, Local): |
| 196 |
class Oops(Exception): |
| 197 |
pass |
| 198 |
|
| 199 |
runner = Local.return_value |
| 200 |
c = Context() |
| 201 |
try: |
| 202 |
with c.cd("foo"): |
| 203 |
c.run("whoami") |
| 204 |
assert runner.run.call_args[0][0] == "cd foo && whoami" |
| 205 |
raise Oops |
| 206 |
except Oops: |
| 207 |
pass |
| 208 |
c.run("ls") |
| 209 |
# When bug present, this would be "cd foo && ls" |
| 210 |
assert runner.run.call_args[0][0] == "ls" |
| 211 |
|
| 212 |
@patch(local_path) |
| 213 |
def cd_should_accept_any_stringable_object(self, Local): |
| 214 |
class Path: |
| 215 |
def __init__(self, value): |
| 216 |
self.value = value |
| 217 |
|
| 218 |
def __str__(self): |
| 219 |
return self.value |
| 220 |
|
| 221 |
runner = Local.return_value |
| 222 |
c = Context() |
| 223 |
|
| 224 |
with c.cd(Path("foo")): |
| 225 |
c.run("whoami") |
| 226 |
|
| 227 |
cmd = "cd foo && whoami" |
| 228 |
assert runner.run.call_args[0][0] == cmd |
| 229 |
|
| 230 |
class prefix: |
| 231 |
@patch(local_path) |
| 232 |
def prefixes_should_apply_to_run(self, Local): |
| 233 |
runner = Local.return_value |
| 234 |
c = Context() |
| 235 |
with c.prefix("cd foo"): |
| 236 |
c.run("whoami") |
| 237 |
|
| 238 |
cmd = "cd foo && whoami" |
| 239 |
assert runner.run.called, "run() never called runner.run()!" |
| 240 |
assert runner.run.call_args[0][0] == cmd |
| 241 |
|
| 242 |
@patch(local_path) |
| 243 |
def prefixes_should_apply_to_sudo(self, Local): |
| 244 |
runner = Local.return_value |
| 245 |
c = Context() |
| 246 |
with c.prefix("cd foo"): |
| 247 |
c.sudo("whoami") |
| 248 |
|
| 249 |
cmd = "sudo -S -p '[sudo] password: ' cd foo && whoami" |
| 250 |
assert runner.run.called, "sudo() never called runner.run()!" |
| 251 |
assert runner.run.call_args[0][0] == cmd |
| 252 |
|
| 253 |
@patch(local_path) |
| 254 |
def nesting_should_retain_order(self, Local): |
| 255 |
runner = Local.return_value |
| 256 |
c = Context() |
| 257 |
with c.prefix("cd foo"): |
| 258 |
with c.prefix("cd bar"): |
| 259 |
c.run("whoami") |
| 260 |
cmd = "cd foo && cd bar && whoami" |
| 261 |
assert ( |
| 262 |
runner.run.called |
| 263 |
), "run() never called runner.run()!" # noqa |
| 264 |
assert runner.run.call_args[0][0] == cmd |
| 265 |
|
| 266 |
c.run("whoami") |
| 267 |
cmd = "cd foo && whoami" |
| 268 |
assert runner.run.called, "run() never called runner.run()!" |
| 269 |
assert runner.run.call_args[0][0] == cmd |
| 270 |
|
| 271 |
# also test that prefixes do not persist |
| 272 |
c.run("whoami") |
| 273 |
cmd = "whoami" |
| 274 |
assert runner.run.called, "run() never called runner.run()!" |
| 275 |
assert runner.run.call_args[0][0] == cmd |
| 276 |
|
| 277 |
@patch(local_path) |
| 278 |
def should_use_finally_to_revert_changes_on_exceptions(self, Local): |
| 279 |
class Oops(Exception): |
| 280 |
pass |
| 281 |
|
| 282 |
runner = Local.return_value |
| 283 |
c = Context() |
| 284 |
try: |
| 285 |
with c.prefix("cd foo"): |
| 286 |
c.run("whoami") |
| 287 |
assert runner.run.call_args[0][0] == "cd foo && whoami" |
| 288 |
raise Oops |
| 289 |
except Oops: |
| 290 |
pass |
| 291 |
c.run("ls") |
| 292 |
# When bug present, this would be "cd foo && ls" |
| 293 |
assert runner.run.call_args[0][0] == "ls" |
| 294 |
|
| 295 |
class sudo: |
| 296 |
@patch(local_path) |
| 297 |
def prefixes_command_with_sudo(self, Local): |
| 298 |
runner = Local.return_value |
| 299 |
Context().sudo("whoami") |
| 300 |
# NOTE: implicitly tests default sudo.prompt conf value |
| 301 |
cmd = "sudo -S -p '[sudo] password: ' whoami" |
| 302 |
assert runner.run.called, "sudo() never called runner.run()!" |
| 303 |
assert runner.run.call_args[0][0] == cmd |
| 304 |
|
| 305 |
@patch(local_path) |
| 306 |
def optional_user_argument_adds_u_and_H_flags(self, Local): |
| 307 |
runner = Local.return_value |
| 308 |
Context().sudo("whoami", user="rando") |
| 309 |
cmd = "sudo -S -p '[sudo] password: ' -H -u rando whoami" |
| 310 |
assert runner.run.called, "sudo() never called runner.run()!" |
| 311 |
assert runner.run.call_args[0][0] == cmd |
| 312 |
|
| 313 |
@patch(local_path) |
| 314 |
def honors_config_for_user_value(self, Local): |
| 315 |
runner = Local.return_value |
| 316 |
config = Config(overrides={"sudo": {"user": "rando"}}) |
| 317 |
Context(config=config).sudo("whoami") |
| 318 |
cmd = "sudo -S -p '[sudo] password: ' -H -u rando whoami" |
| 319 |
assert runner.run.call_args[0][0] == cmd |
| 320 |
|
| 321 |
@patch(local_path) |
| 322 |
def user_kwarg_wins_over_config(self, Local): |
| 323 |
runner = Local.return_value |
| 324 |
config = Config(overrides={"sudo": {"user": "rando"}}) |
| 325 |
Context(config=config).sudo("whoami", user="calrissian") |
| 326 |
cmd = "sudo -S -p '[sudo] password: ' -H -u calrissian whoami" |
| 327 |
assert runner.run.call_args[0][0] == cmd |
| 328 |
|
| 329 |
@trap |
| 330 |
@mock_subprocess() |
| 331 |
def echo_hides_extra_sudo_flags(self): |
| 332 |
skip() # see TODO in sudo() re: clean output display |
| 333 |
config = Config(overrides={"runner": _Dummy}) |
| 334 |
Context(config=config).sudo("nope", echo=True) |
| 335 |
output = sys.stdout.getvalue() |
| 336 |
sys.__stderr__.write(repr(output) + "\n") |
| 337 |
assert "-S" not in output |
| 338 |
assert Context().sudo.prompt not in output |
| 339 |
assert "sudo nope" in output |
| 340 |
|
| 341 |
@patch(local_path) |
| 342 |
def honors_config_for_prompt_value(self, Local): |
| 343 |
runner = Local.return_value |
| 344 |
config = Config(overrides={"sudo": {"prompt": "FEED ME: "}}) |
| 345 |
Context(config=config).sudo("whoami") |
| 346 |
cmd = "sudo -S -p 'FEED ME: ' whoami" |
| 347 |
assert runner.run.call_args[0][0] == cmd |
| 348 |
|
| 349 |
def prompt_value_is_properly_shell_escaped(self): |
| 350 |
# I.e. setting it to "here's johnny!" doesn't explode. |
| 351 |
# NOTE: possibly best to tie into issue #2 |
| 352 |
skip() |
| 353 |
|
| 354 |
@patch(local_path) |
| 355 |
def explicit_env_vars_are_preserved(self, Local): |
| 356 |
runner = Local.return_value |
| 357 |
Context().sudo( |
| 358 |
"whoami", |
| 359 |
env={"GRATUITOUS_ENVIRONMENT_VARIABLE": "arbitrary value"}, |
| 360 |
) |
| 361 |
assert ( |
| 362 |
"--preserve-env='GRATUITOUS_ENVIRONMENT_VARIABLE'" |
| 363 |
in runner.run.call_args[0][0] |
| 364 |
) |
| 365 |
|
| 366 |
def _expect_responses(self, expected, config=None, kwargs=None): |
| 367 |
""" |
| 368 |
Execute mocked sudo(), expecting watchers= kwarg in its run(). |
| 369 |
|
| 370 |
* expected: list of 2-tuples of FailingResponder prompt/response |
| 371 |
* config: Config object, if an overridden one is needed |
| 372 |
* kwargs: sudo() kwargs, if needed |
| 373 |
""" |
| 374 |
if kwargs is None: |
| 375 |
kwargs = {} |
| 376 |
Local = Mock() |
| 377 |
runner = Local.return_value |
| 378 |
context = Context(config=config) if config else Context() |
| 379 |
context.config.runners.local = Local |
| 380 |
context.sudo("whoami", **kwargs) |
| 381 |
# Tease out the interesting bits - pattern/response - ignoring the |
| 382 |
# sentinel, etc for now. |
| 383 |
prompt_responses = [ |
| 384 |
(watcher.pattern, watcher.response) |
| 385 |
for watcher in runner.run.call_args[1]["watchers"] |
| 386 |
] |
| 387 |
assert prompt_responses == expected |
| 388 |
|
| 389 |
def autoresponds_with_password_kwarg(self): |
| 390 |
# NOTE: technically duplicates the unitty test(s) in watcher tests. |
| 391 |
expected = [(_escaped_prompt, "secret\n")] |
| 392 |
self._expect_responses(expected, kwargs={"password": "secret"}) |
| 393 |
|
| 394 |
def honors_configured_sudo_password(self): |
| 395 |
config = Config(overrides={"sudo": {"password": "secret"}}) |
| 396 |
expected = [(_escaped_prompt, "secret\n")] |
| 397 |
self._expect_responses(expected, config=config) |
| 398 |
|
| 399 |
def sudo_password_kwarg_wins_over_config(self): |
| 400 |
config = Config(overrides={"sudo": {"password": "notsecret"}}) |
| 401 |
kwargs = {"password": "secret"} |
| 402 |
expected = [(_escaped_prompt, "secret\n")] |
| 403 |
self._expect_responses(expected, config=config, kwargs=kwargs) |
| 404 |
|
| 405 |
class auto_response_merges_with_other_responses: |
| 406 |
def setup_method(self): |
| 407 |
class DummyWatcher(StreamWatcher): |
| 408 |
def submit(self, stream): |
| 409 |
pass |
| 410 |
|
| 411 |
self.watcher_klass = DummyWatcher |
| 412 |
|
| 413 |
@patch(local_path) |
| 414 |
def kwarg_only_adds_to_kwarg(self, Local): |
| 415 |
runner = Local.return_value |
| 416 |
context = Context() |
| 417 |
watcher = self.watcher_klass() |
| 418 |
context.sudo("whoami", watchers=[watcher]) |
| 419 |
# When sudo() called w/ user-specified watchers, we add ours to |
| 420 |
# that list |
| 421 |
watchers = runner.run.call_args[1]["watchers"] |
| 422 |
# Will raise ValueError if not in the list |
| 423 |
watchers.remove(watcher) |
| 424 |
# Only remaining item in list should be our sudo responder |
| 425 |
assert len(watchers) == 1 |
| 426 |
assert isinstance(watchers[0], FailingResponder) |
| 427 |
assert watchers[0].pattern == _escaped_prompt |
| 428 |
|
| 429 |
@patch(local_path) |
| 430 |
def config_only(self, Local): |
| 431 |
runner = Local.return_value |
| 432 |
# Set a config-driven list of watchers |
| 433 |
watcher = self.watcher_klass() |
| 434 |
overrides = {"run": {"watchers": [watcher]}} |
| 435 |
config = Config(overrides=overrides) |
| 436 |
Context(config=config).sudo("whoami") |
| 437 |
# Expect that sudo() extracted that config value & put it into |
| 438 |
# the kwarg level. (See comment in sudo() about why...) |
| 439 |
watchers = runner.run.call_args[1]["watchers"] |
| 440 |
# Will raise ValueError if not in the list |
| 441 |
watchers.remove(watcher) |
| 442 |
# Only remaining item in list should be our sudo responder |
| 443 |
assert len(watchers) == 1 |
| 444 |
assert isinstance(watchers[0], FailingResponder) |
| 445 |
assert watchers[0].pattern == _escaped_prompt |
| 446 |
|
| 447 |
@patch(local_path) |
| 448 |
def config_use_does_not_modify_config(self, Local): |
| 449 |
runner = Local.return_value |
| 450 |
watcher = self.watcher_klass() |
| 451 |
overrides = {"run": {"watchers": [watcher]}} |
| 452 |
config = Config(overrides=overrides) |
| 453 |
Context(config=config).sudo("whoami") |
| 454 |
# Here, 'watchers' is _the same object_ as was passed into |
| 455 |
# run(watchers=...). |
| 456 |
watchers = runner.run.call_args[1]["watchers"] |
| 457 |
# We want to make sure that what's in the config we just |
| 458 |
# generated, is untouched by the manipulation done inside |
| 459 |
# sudo(). |
| 460 |
# First, that they aren't the same obj |
| 461 |
err = "Found sudo() reusing config watchers list directly!" |
| 462 |
assert watchers is not config.run.watchers, err |
| 463 |
# And that the list is as it was before (i.e. it is not both |
| 464 |
# our watcher and the sudo()-added one) |
| 465 |
err = "Our config watchers list was modified!" |
| 466 |
assert config.run.watchers == [watcher], err |
| 467 |
|
| 468 |
@patch(local_path) |
| 469 |
def both_kwarg_and_config(self, Local): |
| 470 |
runner = Local.return_value |
| 471 |
# Set a config-driven list of watchers |
| 472 |
conf_watcher = self.watcher_klass() |
| 473 |
overrides = {"run": {"watchers": [conf_watcher]}} |
| 474 |
config = Config(overrides=overrides) |
| 475 |
# AND supply a DIFFERENT kwarg-driven list of watchers |
| 476 |
kwarg_watcher = self.watcher_klass() |
| 477 |
Context(config=config).sudo("whoami", watchers=[kwarg_watcher]) |
| 478 |
# Expect that the kwarg watcher and our internal one were the |
| 479 |
# final result. |
| 480 |
watchers = runner.run.call_args[1]["watchers"] |
| 481 |
# Will raise ValueError if not in the list. .remove() uses |
| 482 |
# identity testing, so two instances of self.watcher_klass will |
| 483 |
# be different values here. |
| 484 |
watchers.remove(kwarg_watcher) |
| 485 |
# Only remaining item in list should be our sudo responder |
| 486 |
assert len(watchers) == 1 |
| 487 |
assert conf_watcher not in watchers # Extra sanity |
| 488 |
assert isinstance(watchers[0], FailingResponder) |
| 489 |
assert watchers[0].pattern == _escaped_prompt |
| 490 |
|
| 491 |
@patch(local_path) |
| 492 |
def passes_through_other_run_kwargs(self, Local): |
| 493 |
runner = Local.return_value |
| 494 |
Context().sudo( |
| 495 |
"whoami", echo=True, warn=False, hide=True, encoding="ascii" |
| 496 |
) |
| 497 |
assert runner.run.called, "sudo() never called runner.run()!" |
| 498 |
kwargs = runner.run.call_args[1] |
| 499 |
assert kwargs["echo"] is True |
| 500 |
assert kwargs["warn"] is False |
| 501 |
assert kwargs["hide"] is True |
| 502 |
assert kwargs["encoding"] == "ascii" |
| 503 |
|
| 504 |
@patch(local_path) |
| 505 |
def returns_run_result(self, Local): |
| 506 |
runner = Local.return_value |
| 507 |
expected = runner.run.return_value |
| 508 |
result = Context().sudo("whoami") |
| 509 |
err = "sudo() did not return run()'s return value!" |
| 510 |
assert result is expected, err |
| 511 |
|
| 512 |
@mock_subprocess(out="something", exit=None) |
| 513 |
def raises_auth_failure_when_failure_detected(self): |
| 514 |
with patch("invoke.context.FailingResponder") as klass: |
| 515 |
unacceptable = Mock(side_effect=ResponseNotAccepted) |
| 516 |
klass.return_value.submit = unacceptable |
| 517 |
excepted = False |
| 518 |
try: |
| 519 |
config = Config(overrides={"sudo": {"password": "nope"}}) |
| 520 |
Context(config=config).sudo("meh", hide=True) |
| 521 |
except AuthFailure as e: |
| 522 |
# Basic sanity checks; most of this is really tested in |
| 523 |
# Runner tests. |
| 524 |
assert e.result.exited is None |
| 525 |
expected = "The password submitted to prompt '[sudo] password: ' was rejected." # noqa |
| 526 |
assert str(e) == expected |
| 527 |
excepted = True |
| 528 |
# Can't use except/else as that masks other real exceptions, |
| 529 |
# such as incorrectly unhandled ThreadErrors |
| 530 |
if not excepted: |
| 531 |
assert False, "Did not raise AuthFailure!" |
| 532 |
|
| 533 |
def can_be_pickled(self): |
| 534 |
c = Context() |
| 535 |
c.foo = {"bar": {"biz": ["baz", "buzz"]}} |
| 536 |
c2 = pickle.loads(pickle.dumps(c)) |
| 537 |
assert c == c2 |
| 538 |
assert c is not c2 |
| 539 |
assert c.foo.bar.biz is not c2.foo.bar.biz |
| 540 |
|
| 541 |
|
| 542 |
class MockContext_: |
| 543 |
def init_still_acts_like_superclass_init(self): |
| 544 |
# No required args |
| 545 |
assert isinstance(MockContext().config, Config) |
| 546 |
config = Config(overrides={"foo": "bar"}) |
| 547 |
# Posarg |
| 548 |
assert MockContext(config).config is config |
| 549 |
# Kwarg |
| 550 |
assert MockContext(config=config).config is config |
| 551 |
|
| 552 |
def non_config_init_kwargs_used_as_return_values_for_methods(self): |
| 553 |
c = MockContext(run=Result("some output")) |
| 554 |
assert c.run("doesn't mattress").stdout == "some output" |
| 555 |
|
| 556 |
def return_value_kwargs_can_take_iterables_too(self): |
| 557 |
c = MockContext(run=(Result("some output"), Result("more!"))) |
| 558 |
assert c.run("doesn't mattress").stdout == "some output" |
| 559 |
assert c.run("still doesn't mattress").stdout == "more!" |
| 560 |
|
| 561 |
def return_value_kwargs_may_be_command_string_maps(self): |
| 562 |
c = MockContext(run={"foo": Result("bar")}) |
| 563 |
assert c.run("foo").stdout == "bar" |
| 564 |
|
| 565 |
def return_value_map_kwargs_may_take_iterables_too(self): |
| 566 |
c = MockContext(run={"foo": (Result("bar"), Result("biz"))}) |
| 567 |
assert c.run("foo").stdout == "bar" |
| 568 |
assert c.run("foo").stdout == "biz" |
| 569 |
|
| 570 |
def regexen_return_value_map_keys_match_on_command(self): |
| 571 |
c = MockContext( |
| 572 |
run={"string": Result("yup"), re.compile(r"foo.*"): Result("bar")} |
| 573 |
) |
| 574 |
assert c.run("string").stdout == "yup" |
| 575 |
assert c.run("foobar").stdout == "bar" |
| 576 |
|
| 577 |
class boolean_result_shorthand: |
| 578 |
def as_singleton_args(self): |
| 579 |
assert MockContext(run=True).run("anything").ok |
| 580 |
assert not MockContext(run=False).run("anything", warn=True).ok |
| 581 |
|
| 582 |
def as_iterables(self): |
| 583 |
mc = MockContext(run=[True, False]) |
| 584 |
assert mc.run("anything").ok |
| 585 |
assert not mc.run("anything", warn=True).ok |
| 586 |
|
| 587 |
def as_dict_values(self): |
| 588 |
mc = MockContext(run=dict(foo=True, bar=False)) |
| 589 |
assert mc.run("foo").ok |
| 590 |
assert not mc.run("bar", warn=True).ok |
| 591 |
|
| 592 |
class string_result_shorthand: |
| 593 |
def as_singleton_args(self): |
| 594 |
assert MockContext(run="foo").run("anything").stdout == "foo" |
| 595 |
|
| 596 |
def as_iterables(self): |
| 597 |
mc = MockContext(run=["definition", "of", "insanity"]) |
| 598 |
assert mc.run("anything").stdout == "definition" |
| 599 |
assert mc.run("anything").stdout == "of" |
| 600 |
assert mc.run("anything").stdout == "insanity" |
| 601 |
|
| 602 |
def as_dict_values(self): |
| 603 |
mc = MockContext(run=dict(foo="foo", bar="bar")) |
| 604 |
assert mc.run("foo").stdout == "foo" |
| 605 |
assert mc.run("bar").stdout == "bar" |
| 606 |
|
| 607 |
class commands_injected_into_Result: |
| 608 |
@mark.parametrize( |
| 609 |
"kwargs", (dict(), dict(command=""), dict(command=None)) |
| 610 |
) |
| 611 |
def when_not_set_or_falsey(self, kwargs): |
| 612 |
c = MockContext(run={"foo": Result("bar", **kwargs)}) |
| 613 |
assert c.run("foo").command == "foo" |
| 614 |
|
| 615 |
def does_not_occur_when_truthy(self): |
| 616 |
# Not sure why you'd want this but whatevs! |
| 617 |
c = MockContext(run={"foo": Result("bar", command="nope")}) |
| 618 |
assert c.run("foo").command == "nope" # not "bar" |
| 619 |
|
| 620 |
def methods_with_no_kwarg_values_raise_NotImplementedError(self): |
| 621 |
with raises(NotImplementedError): |
| 622 |
MockContext().run("onoz I did not anticipate this would happen") |
| 623 |
|
| 624 |
def does_not_consume_results_by_default(self): |
| 625 |
mc = MockContext( |
| 626 |
run=dict( |
| 627 |
singleton=True, # will repeat |
| 628 |
wassup=Result("yo"), # ditto |
| 629 |
iterable=[Result("tick"), Result("tock")], # will not |
| 630 |
), |
| 631 |
) |
| 632 |
assert mc.run("singleton").ok |
| 633 |
assert mc.run("singleton").ok # not consumed |
| 634 |
assert mc.run("wassup").ok |
| 635 |
assert mc.run("wassup").ok # not consumed |
| 636 |
assert mc.run("iterable").stdout == "tick" |
| 637 |
assert mc.run("iterable").stdout == "tock" |
| 638 |
assert mc.run("iterable").stdout == "tick" # not consumed |
| 639 |
assert mc.run("iterable").stdout == "tock" |
| 640 |
|
| 641 |
def consumes_singleton_results_when_repeat_False(self): |
| 642 |
mc = MockContext( |
| 643 |
repeat=False, |
| 644 |
run=dict( |
| 645 |
singleton=True, |
| 646 |
wassup=Result("yo"), |
| 647 |
iterable=[Result("tick"), Result("tock")], |
| 648 |
), |
| 649 |
) |
| 650 |
assert mc.run("singleton").ok |
| 651 |
with raises(NotImplementedError): # was consumed |
| 652 |
mc.run("singleton") |
| 653 |
assert mc.run("wassup").ok |
| 654 |
with raises(NotImplementedError): # was consumed |
| 655 |
mc.run("wassup") |
| 656 |
assert mc.run("iterable").stdout == "tick" |
| 657 |
assert mc.run("iterable").stdout == "tock" |
| 658 |
with raises(NotImplementedError): # was consumed |
| 659 |
assert mc.run("iterable") |
| 660 |
|
| 661 |
def sudo_also_covered(self): |
| 662 |
c = MockContext(sudo=Result(stderr="super duper")) |
| 663 |
assert c.sudo("doesn't mattress").stderr == "super duper" |
| 664 |
try: |
| 665 |
MockContext().sudo("meh") |
| 666 |
except NotImplementedError as e: |
| 667 |
assert str(e) == "meh" |
| 668 |
else: |
| 669 |
assert False, "Did not get a NotImplementedError for sudo!" |
| 670 |
|
| 671 |
class exhausted_nonrepeating_return_values_also_raise_NotImplementedError: |
| 672 |
def _expect_NotImplementedError(self, context): |
| 673 |
context.run("something") |
| 674 |
try: |
| 675 |
context.run("something") |
| 676 |
except NotImplementedError as e: |
| 677 |
assert str(e) == "something" |
| 678 |
else: |
| 679 |
assert False, "Didn't raise NotImplementedError" |
| 680 |
|
| 681 |
def single_value(self): |
| 682 |
self._expect_NotImplementedError( |
| 683 |
MockContext(run=Result("meh"), repeat=False) |
| 684 |
) |
| 685 |
|
| 686 |
def iterable(self): |
| 687 |
self._expect_NotImplementedError( |
| 688 |
MockContext(run=[Result("meh")], repeat=False) |
| 689 |
) |
| 690 |
|
| 691 |
def mapping_to_single_value(self): |
| 692 |
self._expect_NotImplementedError( |
| 693 |
MockContext(run={"something": Result("meh")}, repeat=False) |
| 694 |
) |
| 695 |
|
| 696 |
def mapping_to_iterable(self): |
| 697 |
self._expect_NotImplementedError( |
| 698 |
MockContext(run={"something": [Result("meh")]}, repeat=False) |
| 699 |
) |
| 700 |
|
| 701 |
def unexpected_kwarg_type_yields_TypeError(self): |
| 702 |
with raises(TypeError): |
| 703 |
MockContext(run=123) |
| 704 |
|
| 705 |
class can_modify_return_value_maps_after_instantiation: |
| 706 |
class non_dict_type_instantiation_values_yield_TypeErrors: |
| 707 |
class no_stored_result: |
| 708 |
def run(self): |
| 709 |
mc = MockContext() |
| 710 |
with raises(TypeError): |
| 711 |
mc.set_result_for("run", "whatever", Result("bar")) |
| 712 |
|
| 713 |
def sudo(self): |
| 714 |
mc = MockContext() |
| 715 |
with raises(TypeError): |
| 716 |
mc.set_result_for("sudo", "whatever", Result("bar")) |
| 717 |
|
| 718 |
class single_result: |
| 719 |
def run(self): |
| 720 |
mc = MockContext(run=Result("foo")) |
| 721 |
with raises(TypeError): |
| 722 |
mc.set_result_for("run", "whatever", Result("bar")) |
| 723 |
|
| 724 |
def sudo(self): |
| 725 |
mc = MockContext(sudo=Result("foo")) |
| 726 |
with raises(TypeError): |
| 727 |
mc.set_result_for("sudo", "whatever", Result("bar")) |
| 728 |
|
| 729 |
class iterable_result: |
| 730 |
def run(self): |
| 731 |
mc = MockContext(run=[Result("foo")]) |
| 732 |
with raises(TypeError): |
| 733 |
mc.set_result_for("run", "whatever", Result("bar")) |
| 734 |
|
| 735 |
def sudo(self): |
| 736 |
mc = MockContext(sudo=[Result("foo")]) |
| 737 |
with raises(TypeError): |
| 738 |
mc.set_result_for("sudo", "whatever", Result("bar")) |
| 739 |
|
| 740 |
def run(self): |
| 741 |
mc = MockContext(run={"foo": Result("bar")}) |
| 742 |
assert mc.run("foo").stdout == "bar" |
| 743 |
mc.set_result_for("run", "foo", Result("biz")) |
| 744 |
assert mc.run("foo").stdout == "biz" |
| 745 |
|
| 746 |
def sudo(self): |
| 747 |
mc = MockContext(sudo={"foo": Result("bar")}) |
| 748 |
assert mc.sudo("foo").stdout == "bar" |
| 749 |
mc.set_result_for("sudo", "foo", Result("biz")) |
| 750 |
assert mc.sudo("foo").stdout == "biz" |
| 751 |
|
| 752 |
def wraps_run_and_sudo_with_Mock(self, clean_sys_modules): |
| 753 |
sys.modules["mock"] = None # legacy |
| 754 |
sys.modules["unittest.mock"] = Mock(Mock=Mock) # buffalo buffalo |
| 755 |
mc = MockContext( |
| 756 |
run={"foo": Result("bar")}, sudo={"foo": Result("bar")} |
| 757 |
) |
| 758 |
assert isinstance(mc.run, Mock) |
| 759 |
assert isinstance(mc.sudo, Mock) |