Beispiel #1
0
 def _prepare(self):
     self.counters = {}
     basename = None
     cli_tempdir_basename = self.config.getvalue('tempdir_basename')
     if cli_tempdir_basename is not None:
         basename = cli_tempdir_basename
     else:
         # Let's see if we have a pytest_tempdir_basename hook implementation
         basename = self.config.hook.pytest_tempdir_basename()
     if basename is None:
         # If by now, basename is still None, use the current directory name
         basename = os.path.basename(py.path.local().strpath)  # pylint: disable=no-member
     mpatch = MonkeyPatch()
     temproot = py.path.local.get_temproot()  # pylint: disable=no-member
     # Let's get the full real path to the tempdir
     tempdir = temproot.join(basename).realpath()
     if tempdir.exists():
         # If it exists, it's a stale tempdir. Remove it
         log.warning('Removing stale tempdir: %s', tempdir.strpath)
         tempdir.remove(rec=True, ignore_errors=True)
     # Make sure the tempdir is created
     tempdir.ensure(dir=True)
     # Store a reference the tempdir for cleanup purposes when ending the test
     # session
     mpatch.setattr(self.config, '_tempdir', self, raising=False)
     # Register the cleanup actions
     self.config._cleanup.extend([
         mpatch.undo,
         self._clean_up_tempdir
     ])
     self.tempdir = tempdir
def test_eth_ticker(
        empty_proxy: PaywalledProxy,
        session: Session,
        sender_privkey: str,
        receiver_privkey: str,
        monkeypatch: MonkeyPatch
):
    def get_patched(*args, **kwargs):
        body = {
            'mid': '682.435', 'bid': '682.18', 'ask': '682.69', 'last_price': '683.16',
            'low': '532.97', 'high': '684.0', 'volume': '724266.25906224',
            'timestamp': '1513167820.721733'
        }
        return jsonify(body)

    monkeypatch.setattr(PaywalledProxyUrl, 'get', get_patched)

    ETHTickerProxy(receiver_privkey, proxy=empty_proxy)
    ticker = ETHTickerClient(sender_privkey, session=session, poll_interval=0.5)

    def post():
        ticker.close()

        assert ticker.pricevar.get() == '683.16 USD'
        assert len(session.client.get_open_channels()) == 0
        ticker.success = True

    session.close_channel_on_exit = True
    ticker.success = False
    ticker.root.after(1500, post)
    ticker.run()
    assert ticker.success
Beispiel #3
0
def test_setitem_deleted_meanwhile():
    d = {}
    monkeypatch = MonkeyPatch()
    monkeypatch.setitem(d, "x", 2)
    del d["x"]
    monkeypatch.undo()
    assert not d
Beispiel #4
0
def test_issue1338_name_resolving():
    pytest.importorskip("requests")
    monkeypatch = MonkeyPatch()
    try:
        monkeypatch.delattr("requests.sessions.Session.request")
    finally:
        monkeypatch.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
Beispiel #6
0
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
Beispiel #7
0
def test_setenv():
    monkeypatch = MonkeyPatch()
    monkeypatch.setenv("XYZ123", 2)
    import os

    assert os.environ["XYZ123"] == "2"
    monkeypatch.undo()
    assert "XYZ123" not in os.environ
Beispiel #8
0
def test_issue156_undo_staticmethod(Sample):
    monkeypatch = MonkeyPatch()

    monkeypatch.setattr(Sample, "hello", None)
    assert Sample.hello is None

    monkeypatch.undo()
    assert Sample.hello()
Beispiel #9
0
def test_client_private_key_path(
        patched_contract,
        monkeypatch: MonkeyPatch,
        sender_privkey: str,
        tmpdir: LocalPath,
        web3: Web3,
        channel_manager_address: str
):
    def check_permission_safety_patched(path: str):
        return True

    monkeypatch.setattr(
        microraiden.utils.private_key,
        'check_permission_safety',
        check_permission_safety_patched
    )

    privkey_file = tmpdir.join('private_key.txt')
    privkey_file.write(sender_privkey)

    with pytest.raises(AssertionError):
        Client(
            private_key='0xthis_is_not_a_private_key',
            channel_manager_address=channel_manager_address,
            web3=web3
        )

    with pytest.raises(AssertionError):
        Client(
            private_key='0xcorrect_length_but_still_not_a_private_key_12345678901234567',
            channel_manager_address=channel_manager_address,
            web3=web3
        )

    with pytest.raises(AssertionError):
        Client(
            private_key='/nonexisting/path',
            channel_manager_address=channel_manager_address,
            web3=web3
        )

    Client(
        private_key=sender_privkey,
        channel_manager_address=channel_manager_address,
        web3=web3
    )

    Client(
        private_key=sender_privkey[2:],
        channel_manager_address=channel_manager_address,
        web3=web3
    )

    Client(
        private_key=str(tmpdir.join('private_key.txt')),
        channel_manager_address=channel_manager_address,
        web3=web3
    )
Beispiel #10
0
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
Beispiel #11
0
def test_context():
    monkeypatch = MonkeyPatch()

    import functools
    import inspect

    with monkeypatch.context() as m:
        m.setattr(functools, "partial", 3)
        assert not inspect.isclass(functools.partial)
    assert inspect.isclass(functools.partial)
Beispiel #12
0
def pytest_configure(config):
    """Create a TempdirFactory and attach it to the config object.

    This is to comply with existing plugins which expect the handler to be
    available at pytest_configure time, but ideally should be moved entirely
    to the tmpdir_factory session fixture.
    """
    mp = MonkeyPatch()
    t = TempdirFactory(config)
    config._cleanup.extend([mp.undo, t.finish])
    mp.setattr(config, '_tmpdirhandler', t, raising=False)
    mp.setattr(pytest, 'ensuretemp', t.ensuretemp, raising=False)
Beispiel #13
0
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 pytest_configure(self, config):
        if not config.getoption('ast_as_python'):
            return

        mp = MonkeyPatch()
        mp.setattr(
            '_pytest.assertion.rewrite.rewrite_asserts',
            make_replacement_rewrite_asserts(self.store))

        # written pyc files will bypass our patch, so disable reading them
        mp.setattr(
            '_pytest.assertion.rewrite._read_pyc',
            lambda source, pyc, trace=None: None)

        config._cleanup.append(mp.undo)
Beispiel #15
0
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_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
Beispiel #17
0
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
Beispiel #18
0
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
Beispiel #19
0
def pytest_configure(config):
    """Create a TempdirFactory and attach it to the config object.

    This is to comply with existing plugins which expect the handler to be
    available at pytest_configure time, but ideally should be moved entirely
    to the tmpdir_factory session fixture.
    """
    mp = MonkeyPatch()
    tmppath_handler = TempPathFactory.from_config(config)
    t = TempdirFactory(tmppath_handler)
    config._cleanup.append(mp.undo)
    mp.setattr(config, "_tmp_path_factory", tmppath_handler, raising=False)
    mp.setattr(config, "_tmpdirhandler", t, raising=False)
    mp.setattr(pytest, "ensuretemp", t.ensuretemp, raising=False)
class TestRelatedFieldHTMLCutoff(APISimpleTestCase):
    def setUp(self):
        self.queryset = MockQueryset([
            MockObject(pk=i, name=str(i)) for i in range(0, 1100)
        ])
        self.monkeypatch = MonkeyPatch()

    def test_no_settings(self):
        # The default is 1,000, so sans settings it should be 1,000 plus one.
        for many in (False, True):
            field = serializers.PrimaryKeyRelatedField(queryset=self.queryset,
                                                       many=many)
            options = list(field.iter_options())
            assert len(options) == 1001
            assert options[-1].display_text == "More than 1000 items..."

    def test_settings_cutoff(self):
        self.monkeypatch.setattr(relations, "api_settings",
                                 MockApiSettings(2, "Cut Off"))
        for many in (False, True):
            field = serializers.PrimaryKeyRelatedField(queryset=self.queryset,
                                                       many=many)
            options = list(field.iter_options())
            assert len(options) == 3  # 2 real items plus the 'Cut Off' item.
            assert options[-1].display_text == "Cut Off"

    def test_settings_cutoff_none(self):
        # Setting it to None should mean no limit; the default limit is 1,000.
        self.monkeypatch.setattr(relations, "api_settings",
                                 MockApiSettings(None, "Cut Off"))
        for many in (False, True):
            field = serializers.PrimaryKeyRelatedField(queryset=self.queryset,
                                                       many=many)
            options = list(field.iter_options())
            assert len(options) == 1100

    def test_settings_kwargs_cutoff(self):
        # The explicit argument should override the settings.
        self.monkeypatch.setattr(relations, "api_settings",
                                 MockApiSettings(2, "Cut Off"))
        for many in (False, True):
            field = serializers.PrimaryKeyRelatedField(queryset=self.queryset,
                                                       many=many,
                                                       html_cutoff=100)
            options = list(field.iter_options())
            assert len(options) == 101
            assert options[-1].display_text == "Cut Off"
Beispiel #21
0
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
Beispiel #22
0
def test_delitem() -> None:
    d: Dict[str, object] = {"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}
Beispiel #23
0
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.

"""Monkeypatching fixtures."""

from _pytest.monkeypatch import MonkeyPatch


mp = MonkeyPatch()


class FakeJob(object):
    id = 'FAKE_JOB_ID'


mp.setattr('rq.get_current_job', lambda: FakeJob())
Beispiel #24
0
def init_db(pytestconfig):
    assert os.environ["TEST_DBURL"]
    dburl = os.environ["TEST_DBURL"]

    if pytestconfig.getoption("skipdbinit"):
        logger.info("Skipping DB initialization.")
        return

    # Start with a clean database.
    if settings.database_type == DatabaseType.SQLite:
        match = re.match(r"^sqlite:///(.*)$", dburl)
        path = match.group(1)
        if Path(path).exists():
            os.unlink(path)

    elif settings.database_type == DatabaseType.PostgreSQL:
        # Extract the components of the DBURL. The expected format is ``postgresql://user:password@netloc/dbname``, a simplified form of the `connection URI <https://www.postgresql.org/docs/9.6/static/libpq-connect.html#LIBPQ-CONNSTRING>`_.
        (empty1, pguser, pgpassword, pgnetloc, dbname,
         empty2) = re.split(r"^postgresql://(.*):(.*)@(.*)\/(.*)$", dburl)
        # Per the `docs <https://docs.python.org/3/library/re.html#re.split>`_, the first and last split are empty because the pattern matches at the beginning and the end of the string.
        assert not empty1 and not empty2
        # The `postgres command-line utilities <https://www.postgresql.org/docs/current/libpq-envars.html>`_ require these.
        os.environ["PGPASSWORD"] = pgpassword
        os.environ["PGUSER"] = pguser
        os.environ["PGHOST"] = pgnetloc

        try:
            subprocess.run(f"dropdb --if-exists {dbname}",
                           check=True,
                           shell=True)
            subprocess.run(f"createdb --echo {dbname}", check=True, shell=True)
        except Exception as e:
            assert False, f"Failed to drop the database: {e}. Do you have permission?"

    else:
        assert False, "Unknown database type."

    # Copy the test book to the books directory.
    test_book_path = f"{settings.book_path}/test_course_1"
    rmtree(test_book_path, ignore_errors=True)
    # Sometimes this fails for no good reason on Windows. Retry.
    for retry in range(100):
        try:
            copytree(
                f"{settings.runestone_path}/tests/test_course_1",
                test_book_path,
            )
            break
        except OSError:
            if retry == 99:
                raise

    # Start the app to initialize the database.
    with TestClient(app):
        pass

    # Build the test book to add in db fields needed.
    with pushd(test_book_path), MonkeyPatch().context() as m:
        m.setenv("WEB2PY_CONFIG", "test")

        def run_subprocess(args: str, description: str):
            logger.info(f"Running {description}: {args}")
            try:
                cp = subprocess.run(args,
                                    capture_output=True,
                                    check=True,
                                    shell=True,
                                    text=True)
            except subprocess.CalledProcessError as e:
                # Report errors before raising the exception.
                log_subprocess(e.stdout, e.stderr, description)
                raise
            log_subprocess(cp.stdout, cp.stderr, description)

        run_subprocess("{} -m runestone build --all".format(sys.executable),
                       "runestone.build")
        run_subprocess("{} -m runestone deploy".format(sys.executable),
                       "runestone.deploy")
Beispiel #25
0
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
Beispiel #26
0
def mp():
    cwd = os.getcwd()
    sys_path = list(sys.path)
    yield MonkeyPatch()
    sys.path[:] = sys_path
    os.chdir(cwd)
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
Beispiel #28
0
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
Beispiel #29
0
def test_delenv() -> None:
    name = "xyz1234"
    assert name not in os.environ
    monkeypatch = MonkeyPatch()
    pytest.raises(KeyError, monkeypatch.delenv, name, raising=True)
    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]
Beispiel #30
0
def mp() -> Generator[MonkeyPatch, None, None]:
    cwd = os.getcwd()
    sys_path = list(sys.path)
    yield MonkeyPatch()
    sys.path[:] = sys_path
    os.chdir(cwd)
Beispiel #31
0
def session(tmp_path: Path, monkeypatch: MonkeyPatch) -> Session:
    """Return a fake Nox session."""
    monkeypatch.setattr("nox_poetry.core.Session_install", FakeSession.install)
    session = FakeSession(tmp_path)
    return cast(Session, session)
def mock_env(
    monkeypatch: MonkeyPatch,
    network_name: str,
    dev_features_enabled: str,
    rabbit_service: RabbitSettings,
) -> None:
    # Works as below line in docker.compose.yml
    # ${DOCKER_REGISTRY:-itisfoundation}/dynamic-sidecar:${DOCKER_IMAGE_TAG:-latest}

    registry = os.environ.get("DOCKER_REGISTRY", "local")
    image_tag = os.environ.get("DOCKER_IMAGE_TAG", "production")

    image_name = f"{registry}/dynamic-sidecar:{image_tag}"

    logger.warning("Patching to: DYNAMIC_SIDECAR_IMAGE=%s", image_name)
    monkeypatch.setenv("DYNAMIC_SIDECAR_IMAGE", image_name)
    monkeypatch.setenv("TRAEFIK_SIMCORE_ZONE", "test_traefik_zone")
    monkeypatch.setenv("SWARM_STACK_NAME", "test_swarm_name")

    monkeypatch.setenv("SC_BOOT_MODE", "production")
    monkeypatch.setenv("DYNAMIC_SIDECAR_EXPOSE_PORT", "true")
    monkeypatch.setenv("PROXY_EXPOSE_PORT", "true")
    monkeypatch.setenv("SIMCORE_SERVICES_NETWORK_NAME", network_name)
    monkeypatch.delenv("DYNAMIC_SIDECAR_MOUNT_PATH_DEV", raising=False)
    monkeypatch.setenv("DIRECTOR_V2_DYNAMIC_SCHEDULER_ENABLED", "true")
    monkeypatch.setenv("DYNAMIC_SIDECAR_TRAEFIK_ACCESS_LOG", "true")
    monkeypatch.setenv("DYNAMIC_SIDECAR_TRAEFIK_LOGLEVEL", "debug")
    # patch host for dynamic-sidecar, not reachable via localhost
    # the dynamic-sidecar (running inside a container) will use
    # this address to reach the rabbit service
    monkeypatch.setenv("RABBIT_HOST", f"{get_localhost_ip()}")
    monkeypatch.setenv("POSTGRES_HOST", f"{get_localhost_ip()}")
    monkeypatch.setenv("R_CLONE_S3_PROVIDER", "MINIO")
    monkeypatch.setenv("DIRECTOR_V2_DEV_FEATURES_ENABLED",
                       dev_features_enabled)
    monkeypatch.setenv("DIRECTOR_V2_TRACING", "null")
Beispiel #33
0
def enable_dev_features(monkeypatch: MonkeyPatch):
    monkeypatch.setenv("WEBSERVER_DEV_FEATURES_ENABLED", "1")
 def setUp(self):
     self.monkeypatch = MonkeyPatch()
     self.monkeypatch.setattr(
         "databaseConnection.DatabaseConnection.db_name", self.db_name)
     self.monkeypatch.setattr(
         "databaseConnection.DatabaseConnection.commit", lambda x: None)
Beispiel #35
0
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
Beispiel #36
0
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 setUp(self):
     self.queryset = MockQueryset([
         MockObject(pk=i, name=str(i)) for i in range(0, 1100)
     ])
     self.monkeypatch = MonkeyPatch()
class TestUserInteraction(unittest.TestCase):
    def __init__(self, *args, **kwargs):
        super(TestUserInteraction, self).__init__(*args, **kwargs)
        self.db_name = "tests/TestFilled.db"

    def setUp(self):
        self.monkeypatch = MonkeyPatch()
        self.monkeypatch.setattr(
            "databaseConnection.DatabaseConnection.db_name", self.db_name)
        self.monkeypatch.setattr(
            "databaseConnection.DatabaseConnection.commit", lambda x: None)

    def tearDown(self):
        databaseConnection.DatabaseConnection.close()
        self.monkeypatch.undo()

    def test_prompting_volunteer_name(self):
        generator = (ele for ele in ["1NotVolunteerName", "Frank Test", ""])
        self.monkeypatch.setattr("builtins.input", lambda x: next(generator))
        volunteer_name = UserInteraction.get_volunteer_name()
        self.assertEqual(volunteer_name, "Frank Test")

    def test_prompting_gender(self):
        generator = (ele for ele in ["x", "f", ""])
        self.monkeypatch.setattr("builtins.input", lambda x: next(generator))
        gender = UserInteraction.get_gender()
        self.assertEqual(gender, "f")

    def test_prompting_birth_date(self):
        generator = (ele for ele in ["11.11.1990", "1990-11-11", ""])
        self.monkeypatch.setattr("builtins.input", lambda x: next(generator))
        birth_date = UserInteraction.get_birth_date()
        self.assertEqual(birth_date, "1990-11-11")

    def test_prompting_position_name(self):
        generator = (ele for ele in ["MYSec"])
        self.monkeypatch.setattr("builtins.input", lambda x: next(generator))
        position_names = UserInteraction.get_position_names()
        self.assertEqual(position_names, ["MYSec"])

    def test_prompting_region_name(self):
        generator = (ele for ele in ["1Münster", "Münster", ""])
        self.monkeypatch.setattr("builtins.input", lambda x: next(generator))
        region_name = UserInteraction.get_region_name()
        self.assertEqual(region_name, "Münster")

    def test_prompting_start_date(self):
        generator = (ele for ele in ["11-11-2020", "2020-11-11", ""])
        self.monkeypatch.setattr("builtins.input", lambda x: next(generator))
        start_date = UserInteraction.get_start_date()
        self.assertEqual(start_date, "2020-11-11")

    def test_prompting_end_date(self):
        generator = (ele for ele in ["March 11th, 2021", "2021-03-11", ""])
        self.monkeypatch.setattr("builtins.input", lambda x: next(generator))
        end_date = UserInteraction.get_end_date()
        self.assertEqual(end_date, "2021-03-11")

    def test_prompting_position_id(self):
        generator = (ele for ele in ["A", "1", ""])
        self.monkeypatch.setattr("builtins.input", lambda x: next(generator))
        position_id = UserInteraction.get_position_id()
        self.assertEqual(position_id, "1")

    def test_post_volunteer(self):
        printed_statements = []
        self.monkeypatch.setattr("builtins.print",
                                 lambda x: printed_statements.append(x))
        UserInteraction.post_volunteer_details(
            Volunteer("M M", "m", "1999-09-09"))
        self.assertEqual(
            printed_statements,
            ["Name: M M", "Gender: m", "Birth date: 1999-09-09", "Positions:"])

    def test_post_position(self):
        printed_statements = []
        self.monkeypatch.setattr("builtins.print",
                                 lambda x: printed_statements.append(x))
        UserInteraction.post_position_details(
            Position("MYSec", "Sachsen", "M Q", "2019-03-30"))
        self.assertEqual(printed_statements, [
            "Title: MYSec", "Held by: M Q", "Region: Sachsen",
            "Start date: 2019-03-30", "End date: "
        ])

    def test_post_region(self):
        printed_statements = []
        self.monkeypatch.setattr("builtins.print",
                                 lambda x: printed_statements.append(x))
        UserInteraction.post_region_details(
            Region("1000", "Test", "test", "Testana", 1, 1, 1, 1))
        self.assertEqual(printed_statements, [
            "Id: 1000", "Region name: Test", "Mail name: test",
            "Magazine name: Testana", "M Count: 1", "MY Count: 1",
            "Non-M Count: 1", "Looking state: 1"
        ])
Beispiel #39
0
def monkeysession(request):
    mpatch = MonkeyPatch()
    yield mpatch
    mpatch.undo()
Beispiel #40
0
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 listener_monkeyfunc(request):
    mpatch = MonkeyPatch()
    yield mpatch
    mpatch.undo()
Beispiel #42
0
def test_setitem() -> None:
    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