def engine_uri_env(engine_uri): monkeypatch = MonkeyPatch() monkeypatch.setenv("MELTANO_DATABASE_URI", engine_uri) yield monkeypatch.undo()
def monkeypatch_session(request): """Experimental (https://github.com/pytest-dev/pytest/issues/363).""" from _pytest.monkeypatch import MonkeyPatch mpatch = MonkeyPatch() yield mpatch mpatch.undo()
def test_setenv(): monkeypatch = MonkeyPatch() monkeypatch.setenv('XYZ123', 2) import os assert os.environ['XYZ123'] == "2" monkeypatch.undo() assert 'XYZ123' not in os.environ
def test_undo_class_descriptors_delattr() -> None: class SampleParent: @classmethod def hello(_cls): pass @staticmethod def world(): pass class SampleChild(SampleParent): pass monkeypatch = MonkeyPatch() original_hello = SampleChild.hello original_world = SampleChild.world monkeypatch.delattr(SampleParent, "hello") monkeypatch.delattr(SampleParent, "world") assert getattr(SampleParent, "hello", None) is None assert getattr(SampleParent, "world", None) is None monkeypatch.undo() assert original_hello == SampleChild.hello assert original_world == SampleChild.world
def pytest_report_header(config, startdir): summary = [] t = tempfile.mktemp() m = MonkeyPatch() try: m.setattr(sys.stdout, "write", lambda x: len(x)) ac = Account(t) info = ac.get_info() ac.shutdown() finally: m.undo() os.remove(t) summary.extend(['Deltachat core={} sqlite={}'.format( info['deltachat_core_version'], info['sqlite_version'], )]) cfg = config.option.liveconfig if cfg: if "?" in cfg: url, token = cfg.split("?", 1) summary.append('Liveconfig provider: {}?<token ommitted>'.format(url)) else: summary.append('Liveconfig file: {}'.format(cfg)) return summary
class TestDbFill(unittest.TestCase): def __init__(self, *args, **kwargs): super(TestDbFill, self).__init__(*args, **kwargs) self.data_path = "./tests/data" self.db_name = "tests/TestEmpty.db" def setUp(self): self.monkeypatch = MonkeyPatch() self.monkeypatch.setattr( "databaseConnection.DatabaseConnection.db_name", self.db_name) self.monkeypatch.setattr( "rawDataAccessMixin.RawDataAccessMixin.data_path", self.data_path) self.monkeypatch.setattr( "databaseConnection.DatabaseConnection.commit", lambda x: None) def tearDown(self): databaseConnection.DatabaseConnection.close() self.monkeypatch.undo() def test_populate_tables(self): fill_db.fill_db() self.assertEqual( databaseConnection.DatabaseConnection().query( "SELECT COUNT(*) FROM weekends"), [(2, )]) self.assertEqual( databaseConnection.DatabaseConnection().query( "SELECT COUNT(*) FROM participants"), [(5, )]) self.assertEqual( databaseConnection.DatabaseConnection().query( "SELECT COUNT(*) FROM weekend_participant"), [(8, )]) self.assertEqual( databaseConnection.DatabaseConnection().query( "SELECT COUNT(*) FROM regions"), [(40, )])
def monkeymodule(): """Make monkeypatching available in a module scope. """ from _pytest.monkeypatch import MonkeyPatch mpatch = MonkeyPatch() yield mpatch mpatch.undo()
def test_check_filepath_consistency(self, monkeypatch: MonkeyPatch, tmp_path: Path) -> None: name = "pointsback123" p = tmp_path.joinpath(name + ".py") p.touch() for ending in (".pyc", ".pyo"): mod = ModuleType(name) pseudopath = tmp_path.joinpath(name + ending) pseudopath.touch() mod.__file__ = str(pseudopath) monkeypatch.setitem(sys.modules, name, mod) newmod = import_path(p, root=tmp_path) assert mod == newmod monkeypatch.undo() mod = ModuleType(name) pseudopath = tmp_path.joinpath(name + "123.py") pseudopath.touch() mod.__file__ = str(pseudopath) monkeypatch.setitem(sys.modules, name, mod) with pytest.raises(ImportPathMismatchError) as excinfo: import_path(p, root=tmp_path) modname, modfile, orig = excinfo.value.args assert modname == name assert modfile == str(pseudopath) assert orig == p assert issubclass(ImportPathMismatchError, ImportError)
def test_setitem_deleted_meanwhile(): d = {} monkeypatch = MonkeyPatch() monkeypatch.setitem(d, "x", 2) del d["x"] monkeypatch.undo() assert not d
def test_issue1338_name_resolving(): pytest.importorskip('requests') monkeypatch = MonkeyPatch() try: monkeypatch.delattr('requests.sessions.Session.request') finally: monkeypatch.undo()
class BertSrlTest(ModelTestCase): def setUp(self): self.monkeypatch = MonkeyPatch() # monkeypatch the PretrainedBertModel to return the tiny test fixture model config_path = FIXTURES_ROOT / "syntax" / "srl" / "bert" / "config.json" vocab_path = FIXTURES_ROOT / "syntax" / "srl" / "bert" / "vocab.txt" config = BertConfig.from_json_file(config_path) self.monkeypatch.setattr(BertModel, "from_pretrained", lambda _: BertModel(config)) self.monkeypatch.setattr(BertTokenizer, "from_pretrained", lambda _: BertTokenizer(vocab_path)) super().setUp() self.set_up_model( FIXTURES_ROOT / "syntax" / "srl" / "bert_srl.jsonnet", FIXTURES_ROOT / "syntax" / "srl" / "conll_2012", ) def tearDown(self): self.monkeypatch.undo() self.monkeypatch.undo() super().tearDown() def test_bert_srl_model_can_train_save_and_load(self): ignore_grads = { "bert_model.pooler.dense.weight", "bert_model.pooler.dense.bias" } self.ensure_model_can_train_save_and_load( self.param_file, gradients_to_ignore=ignore_grads) def test_batch_predictions_are_consistent(self): self.ensure_batch_predictions_are_consistent() def test_forward_pass_runs_correctly(self): training_tensors = self.dataset.as_tensor_dict() output_dict = self.model(**training_tensors) class_probs = output_dict["class_probabilities"][0].data.numpy() numpy.testing.assert_almost_equal(numpy.sum(class_probs, -1), numpy.ones(class_probs.shape[0]), decimal=6) @pytest.mark.skip("test-install fails on this test in some environments") def test_decode_runs_correctly(self): training_tensors = self.dataset.as_tensor_dict() output_dict = self.model(**training_tensors) decode_output_dict = self.model.make_output_human_readable(output_dict) lengths = get_lengths_from_binary_sequence_mask( decode_output_dict["mask"]).data.tolist() # Hard to check anything concrete which we haven't checked in the above # test, so we'll just check that the tags are equal to the lengths # of the individual instances, rather than the max length. for prediction, length in zip(decode_output_dict["wordpiece_tags"], lengths): assert len(prediction) == length for prediction, length in zip(decode_output_dict["tags"], lengths): # to_bioul throws an exception if the tag sequence is not well formed, # so here we can easily check that the sequence we produce is good. to_bioul(prediction, encoding="BIO")
def master_access(): from pkuphysu_wechat import settings mpatch = MonkeyPatch() mpatch.setitem(settings["WECHAT"], "MASTER_IDS", "developmentopenid") yield mpatch.undo()
def test_undo_class_descriptors_delattr(): class SampleParent(object): @classmethod def hello(_cls): pass @staticmethod def world(): pass class SampleChild(SampleParent): pass monkeypatch = MonkeyPatch() original_hello = SampleChild.hello original_world = SampleChild.world monkeypatch.delattr(SampleParent, "hello") monkeypatch.delattr(SampleParent, "world") assert getattr(SampleParent, "hello", None) is None assert getattr(SampleParent, "world", None) is None monkeypatch.undo() assert original_hello == SampleChild.hello assert original_world == SampleChild.world
def setup_env(): monkeypatch = MonkeyPatch() monkeypatch.setenv("MELTANO_DISABLE_TRACKING", "True") yield monkeypatch.undo()
def test_issue1338_name_resolving() -> None: pytest.importorskip("requests") monkeypatch = MonkeyPatch() try: monkeypatch.delattr("requests.sessions.Session.request") finally: monkeypatch.undo()
def devpi(server_dir, args): from devpi_server.genconfig import genconfig from devpi_server.importexport import import_ from devpi_server.init import init from devpi_server.main import main from _pytest.monkeypatch import MonkeyPatch from _pytest.pytester import RunResult m = MonkeyPatch() m.setenv("DEVPISERVER_SERVERDIR", getattr(server_dir, 'strpath', server_dir)) cap = py.io.StdCaptureFD() cap.startall() now = time.time() if args[0] == 'devpi-gen-config': m.setattr("sys.argv", [devpigenconfig]) entry_point = genconfig elif args[0] == 'devpi-import': m.setattr("sys.argv", [devpiimport]) entry_point = import_ elif args[0] == 'devpi-init': m.setattr("sys.argv", [devpiinit]) entry_point = init elif args[0] == 'devpi-server': m.setattr("sys.argv", [devpiserver]) entry_point = main try: entry_point(argv=args) finally: m.undo() out, err = cap.reset() del cap return RunResult(0, out.split("\n"), err.split("\n"), time.time() - now)
def monkeypatcher(): from _pytest.monkeypatch import MonkeyPatch mocks = MonkeyPatch() try: yield mocks finally: mocks.undo()
def test_issue1338_name_resolving(): pytest.importorskip("requests") monkeypatch = MonkeyPatch() try: monkeypatch.delattr("requests.sessions.Session.request") finally: monkeypatch.undo()
def test_setitem_deleted_meanwhile() -> None: d: Dict[str, object] = {} monkeypatch = MonkeyPatch() monkeypatch.setitem(d, "x", 2) del d["x"] monkeypatch.undo() assert not d
def monkeypatch_package(): """Monkeypatch must be re-implemented to be included in fixtures for non-function scopes See: https://github.com/pytest-dev/pytest/issues/363 """ monkeypatch = MonkeyPatch() yield monkeypatch monkeypatch.undo()
def test_not_existing_file_call(self): monkeypatch = MonkeyPatch() monkeypatch.setattr('os.path.isfile', lambda _: False) with pytest.raises(IOError): ColorMap(self.test_binary_src, self._test_regions) monkeypatch.undo()
def monkeymodule(): """Patch to use monkeypatch with module-scoped fixtures. Use `monkeypatch` instead for function scoped fixtures. """ m = MonkeyPatch() yield m m.undo()
def monkeymodule(request): # pylint: disable=import-outside-toplevel from _pytest.monkeypatch import MonkeyPatch # type: ignore[import] # pylint: enable=import-outside-toplevel mpatch = MonkeyPatch() yield mpatch mpatch.undo()
def term(): """Configure TERM for predictable output from Pygments.""" from _pytest.monkeypatch import MonkeyPatch m = MonkeyPatch() m.setenv("TERM", "xterm-256color") yield m m.undo()
def app(self, create_app): monkeypatch = MonkeyPatch() monkeypatch.setitem(ProjectSettingsService.config_override, "ui.authentication", True) yield create_app() monkeypatch.undo()
def test_issue156_undo_staticmethod(Sample: Type[Sample]) -> None: monkeypatch = MonkeyPatch() monkeypatch.setattr(Sample, "hello", None) assert Sample.hello is None monkeypatch.undo() # type: ignore[unreachable] assert Sample.hello()
def test_setenv(): monkeypatch = MonkeyPatch() monkeypatch.setenv("XYZ123", 2) import os assert os.environ["XYZ123"] == "2" monkeypatch.undo() assert "XYZ123" not in os.environ
def test_issue156_undo_staticmethod(Sample): monkeypatch = MonkeyPatch() monkeypatch.setattr(Sample, "hello", None) assert Sample.hello is None monkeypatch.undo() assert Sample.hello()
def monkeymodule(request): # module scoped monkeypatch # from: https://github.com/pytest-dev/pytest/issues/363 from _pytest.monkeypatch import MonkeyPatch mpatch = MonkeyPatch() yield mpatch mpatch.undo()
def test_setenv_prepend() -> None: import os monkeypatch = MonkeyPatch() monkeypatch.setenv("XYZ123", "2", prepend="-") monkeypatch.setenv("XYZ123", "3", prepend="-") assert os.environ["XYZ123"] == "3-2" monkeypatch.undo() assert "XYZ123" not in os.environ
def test_setenv(): monkeypatch = MonkeyPatch() with pytest.warns(pytest.PytestWarning): monkeypatch.setenv("XYZ123", 2) import os assert os.environ["XYZ123"] == "2" monkeypatch.undo() assert "XYZ123" not in os.environ
def project(self, project): Project.deactivate() monkeypatch = MonkeyPatch() monkeypatch.setenv(PROJECT_READONLY_ENV, "true") yield project monkeypatch.undo()
def test_setenv_prepend(): import os monkeypatch = MonkeyPatch() monkeypatch.setenv('XYZ123', 2, prepend="-") assert os.environ['XYZ123'] == "2" monkeypatch.setenv('XYZ123', 3, prepend="-") assert os.environ['XYZ123'] == "3-2" monkeypatch.undo() assert 'XYZ123' not in os.environ
def test_setenv_prepend(): import os monkeypatch = MonkeyPatch() monkeypatch.setenv("XYZ123", 2, prepend="-") assert os.environ["XYZ123"] == "2" monkeypatch.setenv("XYZ123", 3, prepend="-") assert os.environ["XYZ123"] == "3-2" monkeypatch.undo() assert "XYZ123" not in os.environ
def test_setenv_prepend(): import os monkeypatch = MonkeyPatch() with pytest.warns(pytest.PytestWarning): monkeypatch.setenv("XYZ123", 2, prepend="-") assert os.environ["XYZ123"] == "2" with pytest.warns(pytest.PytestWarning): monkeypatch.setenv("XYZ123", 3, prepend="-") assert os.environ["XYZ123"] == "3-2" monkeypatch.undo() assert "XYZ123" not in os.environ
def test_setenv_deleted_meanwhile(before): key = "qwpeoip123" if before: os.environ[key] = "world" monkeypatch = MonkeyPatch() monkeypatch.setenv(key, "hello") del os.environ[key] monkeypatch.undo() if before: assert os.environ[key] == "world" del os.environ[key] else: assert key not in os.environ
def test_delitem(): d = {"x": 1} monkeypatch = MonkeyPatch() monkeypatch.delitem(d, "x") assert "x" not in d monkeypatch.delitem(d, "y", raising=False) pytest.raises(KeyError, "monkeypatch.delitem(d, 'y')") assert not d monkeypatch.setitem(d, "y", 1700) assert d["y"] == 1700 d["hello"] = "world" monkeypatch.setitem(d, "x", 1500) assert d["x"] == 1500 monkeypatch.undo() assert d == {"hello": "world", "x": 1}
def test_delitem(): d = {'x': 1} monkeypatch = MonkeyPatch() monkeypatch.delitem(d, 'x') assert 'x' not in d monkeypatch.delitem(d, 'y', raising=False) pytest.raises(KeyError, "monkeypatch.delitem(d, 'y')") assert not d monkeypatch.setitem(d, 'y', 1700) assert d['y'] == 1700 d['hello'] = 'world' monkeypatch.setitem(d, 'x', 1500) assert d['x'] == 1500 monkeypatch.undo() assert d == {'hello': 'world', 'x': 1}
def test_setitem(): d = {"x": 1} monkeypatch = MonkeyPatch() monkeypatch.setitem(d, "x", 2) monkeypatch.setitem(d, "y", 1700) monkeypatch.setitem(d, "y", 1700) assert d["x"] == 2 assert d["y"] == 1700 monkeypatch.setitem(d, "x", 3) assert d["x"] == 3 monkeypatch.undo() assert d["x"] == 1 assert "y" not in d d["x"] = 5 monkeypatch.undo() assert d["x"] == 5
def test_setitem(): d = {'x': 1} monkeypatch = MonkeyPatch() monkeypatch.setitem(d, 'x', 2) monkeypatch.setitem(d, 'y', 1700) monkeypatch.setitem(d, 'y', 1700) assert d['x'] == 2 assert d['y'] == 1700 monkeypatch.setitem(d, 'x', 3) assert d['x'] == 3 monkeypatch.undo() assert d['x'] == 1 assert 'y' not in d d['x'] = 5 monkeypatch.undo() assert d['x'] == 5
def block_unmocked_requests(): """ Prevents requests from being made unless they are mocked. Helps avoid inadvertent dependencies on external resources during the test run. """ def mocked_send(*args, **kwargs): raise RuntimeError('Tests must mock all HTTP requests!') # The standard monkeypatch fixture cannot be used with session scope: # https://github.com/pytest-dev/pytest/issues/363 monkeypatch = MonkeyPatch() # Monkeypatching here since any higher level would break responses: # https://github.com/getsentry/responses/blob/0.5.1/responses.py#L295 monkeypatch.setattr('requests.adapters.HTTPAdapter.send', mocked_send) yield monkeypatch monkeypatch.undo()
def test_delattr(): class A: x = 1 monkeypatch = MonkeyPatch() monkeypatch.delattr(A, 'x') assert not hasattr(A, 'x') monkeypatch.undo() assert A.x == 1 monkeypatch = MonkeyPatch() monkeypatch.delattr(A, 'x') pytest.raises(AttributeError, "monkeypatch.delattr(A, 'y')") monkeypatch.delattr(A, 'y', raising=False) monkeypatch.setattr(A, 'x', 5, raising=False) assert A.x == 5 monkeypatch.undo() assert A.x == 1
def test_delattr(): class A(object): x = 1 monkeypatch = MonkeyPatch() monkeypatch.delattr(A, "x") assert not hasattr(A, "x") monkeypatch.undo() assert A.x == 1 monkeypatch = MonkeyPatch() monkeypatch.delattr(A, "x") pytest.raises(AttributeError, "monkeypatch.delattr(A, 'y')") monkeypatch.delattr(A, "y", raising=False) monkeypatch.setattr(A, "x", 5, raising=False) assert A.x == 5 monkeypatch.undo() assert A.x == 1
def test_delenv(): name = "xyz1234" assert name not in os.environ monkeypatch = MonkeyPatch() pytest.raises(KeyError, "monkeypatch.delenv(%r, raising=True)" % name) monkeypatch.delenv(name, raising=False) monkeypatch.undo() os.environ[name] = "1" try: monkeypatch = MonkeyPatch() monkeypatch.delenv(name) assert name not in os.environ monkeypatch.setenv(name, "3") assert os.environ[name] == "3" monkeypatch.undo() assert os.environ[name] == "1" finally: if name in os.environ: del os.environ[name]
def test_setattr(): class A(object): x = 1 monkeypatch = MonkeyPatch() pytest.raises(AttributeError, "monkeypatch.setattr(A, 'notexists', 2)") monkeypatch.setattr(A, "y", 2, raising=False) assert A.y == 2 monkeypatch.undo() assert not hasattr(A, "y") monkeypatch = MonkeyPatch() monkeypatch.setattr(A, "x", 2) assert A.x == 2 monkeypatch.setattr(A, "x", 3) assert A.x == 3 monkeypatch.undo() assert A.x == 1 A.x = 5 monkeypatch.undo() # double-undo makes no modification assert A.x == 5
def listener_monkeyfunc(request): mpatch = MonkeyPatch() yield mpatch mpatch.undo()
def monkeysession(request): mp = MonkeyPatch() yield mp mp.undo()
def player_monkeyfunc(request): mpatch = MonkeyPatch() yield mpatch mpatch.undo()
def monkeysession(request): mpatch = MonkeyPatch() yield mpatch mpatch.undo()