pytest.raises

Here are the examples of the python api pytest.raises taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

199 Examples 7

Example 1

View license
def test_validation_of_mixed_type_enums(Person):
    person = Person()

    person.deceased = "yes"
    person.deceased = "no"
    person.deceased = 1

    with pytest.raises(pjs.ValidationError):
        person.deceased = "robot"

    with pytest.raises(pjs.ValidationError):
        person.deceased = 2

    with pytest.raises(pjs.ValidationError):
        person.deceased = 2.3

Example 2

Project: libpebble2
Source File: test_protocol.py
View license
def test_int16_dserialise_nothing(packet):
    field = Int16()
    with pytest.raises(PacketDecodeError):
        field.buffer_to_value(packet, b'', 0)

    with pytest.raises(PacketDecodeError):
        field.buffer_to_value(packet, b'\xff', 0)

    with pytest.raises(PacketDecodeError):
        field.buffer_to_value(packet, b'\x00\xff\xff', 2)

Example 3

Project: chillaxd
Source File: test_datatree.py
View license
    def test_delete_node_with_nonexistent_node(self):
        pytest.raises(datatree.NoNodeException, self.test_dt.delete_node,
                      "/a".encode("utf8"))
        pytest.raises(datatree.NoNodeException, self.test_dt.delete_node,
                      "/a/b".encode("utf8"))
        pytest.raises(datatree.NoNodeException, self.test_dt.delete_node,
                      "/b/c".encode("utf8"))

Example 4

Project: interface
Source File: test_interface.py
View license
def test_require_implement_all_interfaces(combine_interfaces):

    class I1(Interface):  # pragma: nocover
        def i1_method(self, arg1):
            pass

        def shared(self, a, b, c):
            pass

    class I2(Interface):  # pragma: nocover
        def i2_method(self, arg2):
            pass

        def shared(self, a, b, c):
            pass

    bases = combine_interfaces(I1, I2)

    with pytest.raises(IncompleteImplementation):
        class C(*bases):  # pragma: nocover
            def i1_method(self, arg1):
                pass

            def i2_method(self, arg2):
                pass

    with pytest.raises(IncompleteImplementation):
        class C(*bases):  # pragma: nocover

            def i1_method(self, arg1):
                pass

            def shared(self, a, b, c):
                pass

    with pytest.raises(IncompleteImplementation):
        class C(*bases):  # pragma: nocover

            def i2_method(self, arg2):
                pass

            def shared(self, a, b, c):
                pass

Example 5

Project: bayeslite
Source File: test_cgpm.py
View license
def test_cgpm_smoke():
    with cgpm_smoke_bdb() as bdb:

        # Default model.
        bdb.execute('CREATE METAMODEL g_default FOR p USING cgpm')
        bdb.execute('INITIALIZE 1 MODEL FOR g_default')
        bdb.execute('ANALYZE g_default FOR 1 ITERATION WAIT')
        cgpm_smoke_tests(bdb, 'g_default', ['output', 'cat', 'input'])

        # Custom model for output and cat.
        bdb.execute('''
            CREATE METAMODEL g_manifest FOR p USING cgpm (
                OVERRIDE MODEL FOR output, cat
                GIVEN input
                USING piecewise
            )
        ''')
        bdb.execute('INITIALIZE 1 MODEL FOR g_manifest')
        bdb.execute('ANALYZE g_manifest FOR 1 ITERATION WAIT')
        cgpm_smoke_tests(bdb, 'g_manifest', ['output', 'cat', 'input'])

        # Custom model for latent output, manifest output.
        bdb.execute('''
            CREATE METAMODEL g_latout FOR p USING cgpm (
                LATENT output_ NUMERICAL;
                OVERRIDE MODEL FOR output_, cat GIVEN input USING piecewise;
            )
        ''')
        bdb.execute('INITIALIZE 1 MODEL FOR g_latout')
        bdb.execute('ANALYZE g_latout FOR 1 ITERATION WAIT')
        cgpm_smoke_tests(bdb, 'g_latout',
            ['output', 'output_', 'cat', 'input'])

        # Custom model for manifest out, latent cat.
        bdb.execute('''
            CREATE METAMODEL g_latcat FOR p USING cgpm (
                LATENT cat_ CATEGORICAL;
                OVERRIDE MODEL FOR output, cat_ GIVEN input USING piecewise
            )
        ''')
        bdb.execute('INITIALIZE 1 MODEL FOR g_latcat')
        bdb.execute('ANALYZE g_latcat FOR 1 ITERATION WAIT')
        cgpm_smoke_tests(bdb, 'g_latcat', ['output', 'cat', 'cat_', 'input'])

        # Custom chained model.
        bdb.execute('''
            CREATE METAMODEL g_chain FOR p USING cgpm (
                LATENT midput NUMERICAL;
                LATENT excat NUMERICAL;
                OVERRIDE MODEL FOR midput, cat GIVEN input USING piecewise;
                OVERRIDE MODEL FOR output, excat GIVEN midput USING piecewise
            )
        ''')
        bdb.execute('INITIALIZE 1 MODEL FOR g_chain')
        bdb.execute('ANALYZE g_chain FOR 1 ITERATION WAIT')
        cgpm_smoke_tests(bdb, 'g_chain',
            ['output', 'excat', 'midput', 'cat', 'input'])

        # Override the crosscat category model.
        bdb.execute('''
            CREATE METAMODEL g_category_model FOR p USING cgpm (
                SET CATEGORY MODEL FOR output TO NORMAL;
                OVERRIDE MODEL FOR input, cat GIVEN output USING piecewise;
            )
        ''')
        bdb.execute('INITIALIZE 1 MODEL FOR g_category_model')
        bdb.execute('ANALYZE g_category_model FOR 1 ITERATION WAIT')
        cgpm_smoke_tests(bdb, 'g_category_model',
            ['output', 'cat', 'input'])

        with pytest.raises(BQLError):
            bdb.execute('''
                CREATE METAMODEL g_error_typo FOR p USING cgpm (
                    SET CATEGORY MODEL FOR uot TO NORMAL
                )
            ''')
        with pytest.raises(BQLError):
            bdb.execute('''
                CREATE METAMODEL g_error_typo_manifest FOR p USING cgpm (
                    OVERRIDE MODEL FOR output, cat GIVEN ni USING piecewise
                )
            ''')
        with pytest.raises(BQLError):
            bdb.execute('''
                CREATE METAMODEL g_error_typo_output FOR p USING cgpm (
                    OVERRIDE MODEL FOR output, dog GIVEN input USING piecewise;
                )
            ''')
        with pytest.raises(BQLError):
            bdb.execute('''
                CREATE METAMODEL g_error_dup_manifest FOR p USING cgpm (
                    SET CATEGORY MODEL FOR input TO NORMAL;
                    SET CATEGORY MODEL FOR input TO LOGNORMAL
                )
            ''')
        with pytest.raises(BQLError):
            bdb.execute('''
                CREATE METAMODEL g_error_dup_latent FOR p USING cgpm (
                    LATENT output_error NUMERICAL;
                    LATENT output_error CATEGORICAL;

                    OVERRIDE MODEL FOR output_error, cat
                    GIVEN input USING piecewise;
                )
            ''')
        with pytest.raises(BQLError):
            bdb.execute('''
                CREATE METAMODEL g_error_latent_exists FOR p USING cgpm (
                    LATENT output_ NUMERICAL;
                    OVERRIDE MODEL FOR output_, cat GIVEN input USING piecewise;
                )
            ''')
        with pytest.raises(BQLError):
            bdb.execute('''
                CREATE METAMODEL g_error_latent_manifest FOR p USING cgpm (
                    LATENT output NUMERICAL;
                    OVERRIDE MODEL FOR output, cat GIVEN input USING piecewise;
                )
            ''')
        with pytest.raises(BQLError):
            bdb.execute('''
                CREATE METAMODEL g_category_override_dupe FOR p USING cgpm (
                    SET CATEGORY MODEL FOR output TO LOGNORMAL;
                    OVERRIDE MODEL FOR output, cat GIVEN input USING piecewise;
                )
            ''')

        cgpm_smoke_tests(bdb, None, ['output', 'cat', 'input'])

        # XXX Check each operation independently: simulate, logpdf, impute.
        for var in ['output_', 'cat_', 'midput', 'excat']:
            with pytest.raises(BQLError):
                cgpm_smoke_tests(bdb, None, [var])

Example 6

Project: bayeslite
Source File: test_metamodels.py
View license
def _test_example(bdb, exname):
    mm, t, t_sql, data_sql, data, p, g, p_bql, g_bql, g_bqlbad0, g_bqlbad1 = \
        examples[exname]
    qt = bql_quote_name(t)
    qg = bql_quote_name(g)

    bayeslite.bayesdb_register_metamodel(bdb, mm())

    # Create a table.
    assert not core.bayesdb_has_table(bdb, t)
    with bdb.savepoint_rollback():
        bdb.sql_execute(t_sql)
        assert core.bayesdb_has_table(bdb, t)
    assert not core.bayesdb_has_table(bdb, t)
    bdb.sql_execute(t_sql)
    assert core.bayesdb_has_table(bdb, t)

    # Insert data into the table.
    assert bdb.execute('SELECT COUNT(*) FROM %s' % (qt,)).fetchvalue() == 0
    for row in data:
        bdb.sql_execute(data_sql, row)
    n = len(data)
    assert bdb.execute('SELECT COUNT(*) FROM %s' % (qt,)).fetchvalue() == n

    # Create a population.
    assert not core.bayesdb_has_population(bdb, p)
    bdb.execute(p_bql)
    p_id = core.bayesdb_get_population(bdb, p)

    # Create a generator.  Make sure savepoints work for this.
    assert not core.bayesdb_has_generator(bdb, p_id, g)
    with pytest.raises(Exception):
        with bdb.savepoint():
            bdb.execute(g_bqlbad0)
    assert not core.bayesdb_has_generator(bdb, p_id, g)
    with pytest.raises(Exception):
        with bdb.savepoint():
            bdb.execute(g_bqlbad1)
    assert not core.bayesdb_has_generator(bdb, p_id, g)
    with bdb.savepoint_rollback():
        bdb.execute(g_bql)
        assert core.bayesdb_has_generator(bdb, p_id, g)
    assert not core.bayesdb_has_generator(bdb, p_id, g)
    bdb.execute(g_bql)
    assert core.bayesdb_has_generator(bdb, p_id, g)
    assert not core.bayesdb_has_generator(bdb, p_id+1, g)
    with pytest.raises(Exception):
        bdb.execute(g_bql)
    assert core.bayesdb_has_generator(bdb, p_id, g)

    gid = core.bayesdb_get_generator(bdb, p_id, g)
    assert not core.bayesdb_generator_has_model(bdb, gid, 0)
    assert [] == core.bayesdb_generator_modelnos(bdb, gid)
    with bdb.savepoint_rollback():
        bdb.execute('INITIALIZE 1 MODEL FOR %s' % (qg,))
        assert core.bayesdb_generator_has_model(bdb, gid, 0)
        assert [0] == core.bayesdb_generator_modelnos(bdb, gid)
    with bdb.savepoint_rollback():
        bdb.execute('INITIALIZE 10 MODELS FOR %s' % (qg,))
        for i in range(10):
            assert core.bayesdb_generator_has_model(bdb, gid, i)
            assert range(10) == core.bayesdb_generator_modelnos(bdb, gid)
    bdb.execute('INITIALIZE 2 MODELS FOR %s' % (qg,))

    # Test dropping things.
    with pytest.raises(bayeslite.BQLError):
        bdb.execute('DROP TABLE %s' % (qt,))
    with bdb.savepoint_rollback():
        # Note that sql_execute does not protect us!
        bdb.sql_execute('DROP TABLE %s' % (qt,))
        assert not core.bayesdb_has_table(bdb, t)
    assert core.bayesdb_has_table(bdb, t)
    # XXX Should we reject dropping a generator when there remain
    # models?  Should we not reject dropping a table when there remain
    # generators?  A table can be dropped when there remain indices.
    #
    # with pytest.raises(bayeslite.BQLError):
    #     # Models remain.
    #     bdb.execute('DROP GENERATOR %s' % (qg,))
    with bdb.savepoint_rollback():
        bdb.execute('DROP GENERATOR %s' % (qg,))
        assert not core.bayesdb_has_generator(bdb, None, g)
    assert core.bayesdb_has_generator(bdb, p_id, g)
    with bdb.savepoint_rollback():
        bdb.execute('DROP GENERATOR %s' % (qg,))
        assert not core.bayesdb_has_generator(bdb, None, g)
        bdb.execute(g_bql)
        assert core.bayesdb_has_generator(bdb, None, g)
    assert core.bayesdb_has_generator(bdb, p_id, g)
    assert core.bayesdb_has_generator(bdb, None, g)
    assert gid == core.bayesdb_get_generator(bdb, p_id, g)

    # Test dropping models.
    with bdb.savepoint_rollback():
        bdb.execute('DROP MODEL 1 FROM %s' % (qg,))
        assert core.bayesdb_generator_has_model(bdb, gid, 0)
        assert not core.bayesdb_generator_has_model(bdb, gid, 1)
        assert [0] == core.bayesdb_generator_modelnos(bdb, gid)

    # Test analyzing models.
    bdb.execute('ANALYZE %s FOR 1 ITERATION WAIT' % (qg,))
    bdb.execute('ANALYZE %s MODEL 0 FOR 1 ITERATION WAIT' % (qg,))
    bdb.execute('ANALYZE %s MODEL 1 FOR 1 ITERATION WAIT' % (qg,))

Example 7

Project: cocopot
Source File: test_response.py
View license
def test_basic_response():
    r = make_response('text')
    assert r.body == 'text'
    assert r.status_line == '200 OK'
    assert r.status_code == 200
    assert r.charset.lower() == 'utf-8'

    r = make_response('redirect', 302)
    assert r.status_line == '302 Found'
    assert r.status_code == 302

    r = make_response('', 999)
    assert r.status_line == '999 Unknown'
    assert r.status_code == 999

    with pytest.raises(ValueError):
        r = make_response('', 1099)

    with pytest.raises(ValueError):
        r = make_response('', 99)

    r = make_response('', '999 Who knows?') # Illegal, but acceptable three digit code
    assert r.status_line == '999 Who knows?'
    assert r.status_code == 999

    with pytest.raises(ValueError):
        r = make_response(None)

    with pytest.raises(ValueError):
        r = make_response('', '555')

    assert r.status_line == '999 Who knows?'
    assert r.status_code == 999

    r = make_response('', [('Custom-Header', 'custom-value')])
    assert r.status_code == 200
    assert 'Custom-Header' in r

    with pytest.raises(ValueError):
        r = make_response(object())

    r0 = make_response('text')
    r = make_response(r0, 200, [('Custom-Header', 'custom-value')])
    assert r.status_code == 200
    assert 'Custom-Header' in r

    r0 = make_response('text')
    r = make_response(r0, '200 OK', {'Custom-Header':'custom-value'})
    assert r.status_code == 200
    assert 'Custom-Header' in r
    assert r.get_header('Custom-Header') == 'custom-value'
    assert 'Custom-Header' in dict(r.iter_headers())
    assert r.status_line == '200 OK'

    r.set_cookie('name1', 'value')
    r1 = r.copy()
    assert r1.status_line == r.status_line
    assert r1.headers == r.headers
    assert r1.body == r.body
    assert repr(r1) == repr(r)

    r = make_response('', 304)
    assert r.status_code == 304
    assert 'Content-Type' not in dict(r.iter_headers())

    r = make_response(BadRequest(''))
    assert r.status_code == 400

Example 8

Project: gunicorn
Source File: test_config.py
View license
def test_property_access():
    c = config.Config()
    for s in config.KNOWN_SETTINGS:
        getattr(c, s.name)

    # Class was loaded
    assert c.worker_class == SyncWorker

    # logger class was loaded
    assert c.logger_class == glogging.Logger

    # Workers defaults to 1
    assert c.workers == 1
    c.set("workers", 3)
    assert c.workers == 3

    # Address is parsed
    assert c.address == [("127.0.0.1", 8000)]

    # User and group defaults
    assert os.geteuid() == c.uid
    assert os.getegid() == c.gid

    # Proc name
    assert "gunicorn" == c.proc_name

    # Not a config property
    pytest.raises(AttributeError, getattr, c, "foo")
    # Force to be not an error
    class Baz(object):
        def get(self):
            return 3.14
    c.settings["foo"] = Baz()
    assert c.foo == 3.14

    # Attempt to set a cfg not via c.set
    pytest.raises(AttributeError, setattr, c, "proc_name", "baz")

    # No setting for name
    pytest.raises(AttributeError, c.set, "baz", "bar")

Example 9

Project: overloading.py
Source File: test_overloading.py
View license
@requires_typing
def test_typing_tuple():

    @overloaded
    def f(arg: Tuple[int, str]):
        return int, str

    assert f.__complex_positions == {}
    assert f.__complex_parameters == {}

    @overloads(f)
    def f(arg: Tuple[str, int]):
        return str, int

    assert f.__complex_positions == {0: 8}
    assert f.__complex_parameters == {'arg': 8}

    for _ in range(rounds):
        assert f((1, b)) == (int, str)
        assert f((a, 2)) == (str, int)
        with pytest.raises(TypeError):
            f((1, 2))
        with pytest.raises(TypeError):
            f(())

    @overloads(f)
    def f(arg: Tuple):
        return ()

    for _ in range(rounds):
        assert f((1, b)) == (int, str)
        assert f((a, 2)) == (str, int)
        assert f((1, 2)) == ()
        assert f(())     == ()

    @overloaded
    def f(arg: Tuple[int, ...]):
        return int

    @overloads(f)
    def f(arg: Tuple[str, ...]):
        return str

    for _ in range(rounds):
        assert f((1, 2, 3)) == int
        assert f((a, b, c)) == str
        with pytest.raises(TypeError):
            f((x, 2, 3))
        if overloading.DEBUG:
            with pytest.raises(AssertionError):
                f(())

    @overloads(f)
    def f(arg: Tuple):
        return ()

    for _ in range(rounds):
        assert f((1, 2, 3)) == int
        assert f((a, b, c)) == str
        assert f((x, 2, 3)) == ()
        if overloading.DEBUG:
            with pytest.raises(AssertionError):
                f(())

Example 10

Project: Uranium
Source File: TestDefinitionContainer.py
View license
def test_deserialize_bad(definition_container):
    json = """{""" # Syntax error: No closing bracket!
    with pytest.raises(Exception):
        definition_container.deserialize(json)

    json = """{
    "version":
}""" # Syntax error: Missing value.
    with pytest.raises(Exception):
        definition_container.deserialize(json)

    json = """{
    "version": 2,
    "name": "Test",
    "settings": {}
}""" # Missing metadata.
    with pytest.raises(InvalidDefinitionError):
        definition_container.deserialize(json)

    json = """{
    "version": 2,
    "name": "Test",
    "metadata": {}
}""" # Missing settings.
    with pytest.raises(InvalidDefinitionError):
        definition_container.deserialize(json)

    json = """{
    "version": 2,
    "metadata": {},
    "settings": {}
}""" # Missing name.
    with pytest.raises(InvalidDefinitionError):
        definition_container.deserialize(json)

    json = """{
    "name": "Test",
    "metadata": {},
    "settings": {}
}""" # Missing version.
    with pytest.raises(InvalidDefinitionError):
        definition_container.deserialize(json)

    json = """{
    "version": 1,
    "name": "Test",
    "metadata": {},
    "settings": {}
}""" # Wrong version.
    with pytest.raises(IncorrectDefinitionVersionError):
        definition_container.deserialize(json)

    json = """{
    "version": 2,
    "name": "Test",
    "metadata": {},
    "settings": {},
    "inherits": "non-existent_file"
}""" # Faulty inheritance.
    with pytest.raises(OSError):
        definition_container.deserialize(json)

    json = """{
    "version": 2,
    "name": "Test",
    "metadata": {},
    "settings": {
        "layer_height": {
            "label": "Testiness of your print.",
            "description": "How testy your print should be."
        }
    }
}""" # Type missing from a setting.
    with pytest.raises(AttributeError):
        definition_container.deserialize(json)

Example 11

Project: mpfshell
Source File: test_mpfexp.py
View license
    def test_file_handling(self, mpfexp, tmpdir):

        os.chdir(str(tmpdir))
        data = b"\x00\x11\x22\x33\x44\x55\x66\x77\x88\x99"
        self.__create_local_file("file1", data)

        # upload with same name
        mpfexp.put("file1")

        # upload with different name
        mpfexp.put("file1", "file2")
        assert ('file1', 'F') in mpfexp.ls(True, True, True)
        assert ('file2', 'F') in mpfexp.ls(True, True, True)

        os.remove("file1")
        assert not os.path.isfile("file1")

        # download and compare
        mpfexp.get("file1")
        mpfexp.get("file2")
        mpfexp.get("file1", "file3")

        for name in ["file1", "file2", "file3"]:
            with open(name, "rb") as f:
                assert data == f.read()

        # overwrite existing file
        data = b"\xaa\xbb\xcc\xdd\xee\xff"
        self.__create_local_file("file1", data)

        mpfexp.put("file1")

        with open("file1", "rb") as f:
            assert data == f.read()

        # file with name of existing directory not allowed
        self.__create_local_file("dir2")

        mpfexp.md("dir2")

        with pytest.raises(RemoteIOError):
            mpfexp.put("file1", "dir2")

        with pytest.raises(RemoteIOError):
            mpfexp.put("dir2")

        # put files to subdir
        mpfexp.put("file1", "dir2/file1")
        mpfexp.cd("dir2")
        mpfexp.put("file2", "file2")
        assert [('file1', 'F'), ('file2', 'F')] == mpfexp.ls(True, True, True)
        mpfexp.cd("/")

        # fail to put to non-existing directory
        with pytest.raises(RemoteIOError):
            mpfexp.put("file1", "dir3/file1")

        # fail to get non-existing file
        with pytest.raises(RemoteIOError):
            mpfexp.get("file99")

        with pytest.raises(RemoteIOError):
            mpfexp.get("dir2")

        with pytest.raises(RemoteIOError):
            mpfexp.get("dir2/file99")

        # fail to get to non-existing dir
        with pytest.raises(IOError):
            mpfexp.get("file1", "dir/file")

        # fail to put non existing file
        with pytest.raises(IOError):
            mpfexp.put("file99")

        # allow whitespaces in file-names
        mpfexp.put("file1", "file 1")
        mpfexp.get("file 1")
        assert ('file 1', 'F') in mpfexp.ls(True, True, True)

Example 12

Project: piecash
Source File: test_integration.py
View license
    def test_slots_strings_access(self, book):
        b = book
        del b["default-currency"]
        b["a/b/c/d/e"] = 1
        book.book.flush()
        assert b["a"]["b"]["c"]["d"]["e"].value == 1

        b["a/b/c"] = {"d": {"t": "ok"}}

        b["a/b/c/d/f"] = "2"
        book.book.flush()
        assert len(b["a"]["b"]["c"]["d"].slots) == 2

        b["a/b/c/d/f"] = "5"
        assert b["a"]["b/c"]["d"]["f"].value == "5"

        for k, v in b["a/b/c/d"].iteritems():
            assert k == "f" or k == "t"
        print(b.slots)
        assert b["a/b/c/d"].get("t", "hello") == "ok"
        assert b["a/b/c/d"].get("not there", "hello") == "hello"

        del b["a/b/c/d/t"]
        assert repr(b["a"]) == "<SlotFrame a={'b': {'c': {'d': {'f': '5'}}}}>"

        with pytest.raises(TypeError):
            b["a/b/c/d/f"] = 4
        with pytest.raises(TypeError):
            b["a/b/c"] = True

        assert {n for (n,) in book.session.query(Slot._name)} == {'a', 'a/b', 'a/b/c', 'a/b/c/d', 'a/b/c/d/f'}

        # delete some elements
        del b["a"]["b"][:]
        book.flush()
        assert {n for (n,) in book.session.query(Slot._name)} == {'a', 'a/b'}

        book.flush()
        assert len(b["a"].slots) == 1
        assert len(b["a/b"].slots) == 0

        with pytest.raises(KeyError):
            b["a/b/c"]

        del b["a"]["b"]
        book.session.flush()
        assert len(b["a"].slots) == 0

        with pytest.raises(TypeError):
            b["a"] = b

        with pytest.raises(KeyError):
            del b["a/n"]

        del b[:]
        book.session.flush()
        assert {n for (n,) in book.session.query(Slot._name)} == set([])

Example 13

Project: cocrawler
Source File: test_useragent.py
View license
def test_useragent():

    config = {'UserAgent': {'Style': 'crawler',
                            'MyPrefix': 'something',
                            'URL': 'http://example.com/cocrawler.html'}}

    version = '1.0'

    robotname, ua = useragent.useragent(config, version)

    assert version in ua
    assert 'http://example.com/cocrawler.html' in ua
    assert robotname == 'something-cocrawler'

    config['UserAgent']['Style'] = 'laptopplus'
    robotname, ua = useragent.useragent(config, version)
    assert 'Mozilla/5.0' in ua
    config['UserAgent']['Style'] = 'tabletplus'
    robotname, ua = useragent.useragent(config, version)
    assert 'Mozilla/5.0' in ua
    config['UserAgent']['Style'] = 'phoneplus'
    robotname, ua = useragent.useragent(config, version)
    assert 'Mozilla/5.0' in ua

    bad_config = copy.deepcopy(config)
    bad_config['UserAgent']['Style'] = 'error'
    with pytest.raises(ValueError):
        robotname, ua = useragent.useragent(bad_config, version)

    bad_config = copy.deepcopy(config)
    bad_config['UserAgent']['URL'] = 'ha ha I left this off'
    with pytest.raises(ValueError):
        robotname, ua = useragent.useragent(bad_config, version)

    bad_config = copy.deepcopy(config)
    bad_config['UserAgent']['URL'] = 'http://cocrawler.com/cocrawler.html'
    with pytest.raises(ValueError):
        robotname, ua = useragent.useragent(bad_config, version)

    bad_config = copy.deepcopy(config)
    bad_config['UserAgent']['MyPrefix'] = 'test'
    with pytest.raises(ValueError):
        robotname, ua = useragent.useragent(bad_config, version)

    bad_config = copy.deepcopy(config)
    bad_config['UserAgent']['MyPrefix'] = ''
    with pytest.raises(ValueError):
        robotname, ua = useragent.useragent(bad_config, version)

Example 14

Project: setuptools
Source File: test_resources.py
View license
    def testResolve(self):
        ad = pkg_resources.Environment([])
        ws = WorkingSet([])
        # Resolving no requirements -> nothing to install
        assert list(ws.resolve([], ad)) == []
        # Request something not in the collection -> DistributionNotFound
        with pytest.raises(pkg_resources.DistributionNotFound):
            ws.resolve(parse_requirements("Foo"), ad)

        Foo = Distribution.from_filename(
            "/foo_dir/Foo-1.2.egg",
            metadata=Metadata(('depends.txt', "[bar]\nBaz>=2.0"))
        )
        ad.add(Foo)
        ad.add(Distribution.from_filename("Foo-0.9.egg"))

        # Request thing(s) that are available -> list to activate
        for i in range(3):
            targets = list(ws.resolve(parse_requirements("Foo"), ad))
            assert targets == [Foo]
            list(map(ws.add, targets))
        with pytest.raises(VersionConflict):
            ws.resolve(parse_requirements("Foo==0.9"), ad)
        ws = WorkingSet([])  # reset

        # Request an extra that causes an unresolved dependency for "Baz"
        with pytest.raises(pkg_resources.DistributionNotFound):
            ws.resolve(parse_requirements("Foo[bar]"), ad)
        Baz = Distribution.from_filename(
            "/foo_dir/Baz-2.1.egg", metadata=Metadata(('depends.txt', "Foo"))
        )
        ad.add(Baz)

        # Activation list now includes resolved dependency
        assert list(ws.resolve(parse_requirements("Foo[bar]"), ad)) == [Foo, Baz]
        # Requests for conflicting versions produce VersionConflict
        with pytest.raises(VersionConflict) as vc:
            ws.resolve(parse_requirements("Foo==1.2\nFoo!=1.2"), ad)

        msg = 'Foo 0.9 is installed but Foo==1.2 is required'
        assert vc.value.report() == msg

Example 15

Project: esengine
Source File: test_document.py
View license
def test_validators(MockES):
    def if_city_state_is_required(obj):
        if obj.city and not obj.state:
            raise ValidationError("If city, state is required")

    def max_len_10(field_name, value):
        if len(value) > 10:
            raise ValidationError("Invalid Length")

    class Address(Document):
        _doctype = "doc_type"
        _index = "index"
        _es = MockES()
        _validators = [if_city_state_is_required]
        street = StringField(validators=[max_len_10])
        number = IntegerField(required=True)
        city = StringField()
        state = StringField()

    # Invalid Street Length
    doc = Address(
        street="22, Acacia Avenue",
        city="London",
        state="WestMinster"
    )

    with pytest.raises(ValidationError) as ex:
        doc.save()
    assert str(ex.value) == 'Invalid Length'

    # Required field missing
    doc = Address(
        street="Acacia Av",
        city="London",
        state="WestMinster"
    )
    with pytest.raises(RequiredField) as ex:
        doc.save()
    assert str(ex.value) == 'number'

    # City and not state
    doc = Address(
        street="Acacia Av",
        city="London",
        number=22
    )
    with pytest.raises(ValidationError) as ex:
        doc.save()
    assert str(ex.value) == "If city, state is required"

    # Valid document
    doc = Address(
        id="100",
        street="Acacia Av",
        city="London",
        state="WestMinster",
        number=22
    )
    # to_dict calls validation
    assert doc.to_dict() == dict(
        id="100",
        street="Acacia Av",
        city="London",
        state="WestMinster",
        number=22
    )

Example 16

Project: gaffer
Source File: test_keys.py
View license
def test_key_manager():
    conf = test_config()
    loop = pyuv.Loop.default_loop()

    with KeyManager(loop, conf) as h:
        h.set_key("test", {"permission": {}})

        with pytest.raises(KeyConflict):
            h.set_key("test", {"permission": {}})

        assert h.has_key("test") == True

        key = h.get_key("test")
        assert key == {"key": "test", "permission": {}}
        assert len(h._cache) == 1
        assert "test" in h._cache
        assert len(h._entries) == 1
        assert list(h._entries) == ["test"]


        key = h.delete_key("test")
        with pytest.raises(KeyNotFound):
            key = h.get_key("test")

        h.set_key("test", {"permission": {}})
        h.set_key("test1", {"permission": {}}, "test")

        assert h.has_key("test1") == True
        assert h.all_subkeys("test") == [{"key": "test1", "permission": {}}]
        assert len(h.all_keys()) == 2
        assert h.all_keys() == ["test", "test1"]
        assert h.all_keys(include_key=True) == [{"key": "test",
            "permission": {}}, {"key": "test1", "permission": {}}]

        h.get_key("test")
        h.get_key("test1")
        assert len(h._cache) == 2
        assert "test" in h._cache
        assert "test1" in h._cache
        assert len(h._entries) == 2
        assert list(h._entries) == ["test", "test1"]

        # make sure keys are deleted from the cache
        h.delete_key("test")
        assert len(h._cache) == 0
        assert len(h._entries) == 0

        with pytest.raises(KeyNotFound):
            key = h.get_key("test")

        with pytest.raises(KeyNotFound):
            key = h.get_key("test1")

Example 17

Project: datashape
Source File: test_testing.py
View license
def test_record():
    assert_dshape_equal(
        R['a': int32, 'b': float32],
        R['a': int32, 'b': float32],
    )

    with pytest.raises(AssertionError) as e:
        assert_dshape_equal(
            R['a': int32, 'b': float32],
            R['a': int32, 'b': int32],
        )
    assert "'float32' != 'int32'" in str(e)
    assert "_['b'].name" in str(e.value)

    with pytest.raises(AssertionError) as e:
        assert_dshape_equal(
            R['a': int32, 'b': float32],
            R['a': int32, 'c': float32],
        )
    assert "'b' != 'c'" in str(e.value)

    with pytest.raises(AssertionError) as e:
        assert_dshape_equal(
            R['b': float32, 'a': float32],
            R['a': int32, 'b': float32],
            check_record_order=False,
        )
    assert "'float32' != 'int32'" in str(e.value)
    assert "_['a']" in str(e.value)

    assert_dshape_equal(
        R['b': float32, 'a': int32],
        R['a': int32, 'b': float32],
        check_record_order=False,
    )

    # check a nested record with and without ordering
    assert_dshape_equal(
        R['a': R['b': float32, 'a': int32]],
        R['a': R['a': int32, 'b': float32]],
        check_record_order=False,
    )

    with pytest.raises(AssertionError) as e:
        assert_dshape_equal(
            R['a': R['a': int32, 'b': float32]],
            R['a': R['b': float32, 'a': int32]],
        )

    assert "'a' != 'b'" in str(e.value)
    assert "_['a']" in str(e.value)

Example 18

Project: activitysim
Source File: test_misc.py
View license
def test_misc():

    orca.clear_cache()

    with pytest.raises(RuntimeError) as excinfo:
        orca.get_injectable("configs_dir")
    assert "directory does not exist" in str(excinfo.value)

    with pytest.raises(RuntimeError) as excinfo:
        orca.get_injectable("data_dir")
    assert "directory does not exist" in str(excinfo.value)

    with pytest.raises(RuntimeError) as excinfo:
        orca.get_injectable("output_dir")
    assert "directory does not exist" in str(excinfo.value)

    configs_dir = os.path.join(os.path.dirname(__file__), 'configs_test_misc')
    orca.add_injectable("configs_dir", configs_dir)

    settings = orca.get_injectable("settings")
    assert isinstance(settings, dict)

    assert orca.get_injectable("trace_person_ids") == []

    assert orca.get_injectable("trace_tour_ids") == []

    data_dir = os.path.join(os.path.dirname(__file__), 'data')
    orca.add_injectable("data_dir", data_dir)

    with pytest.raises(RuntimeError) as excinfo:
        orca.get_injectable("store")
    assert "store file name not specified in settings" in str(excinfo.value)

    settings = {'store': 'bogus.h5'}
    orca.add_injectable("settings", settings)
    with pytest.raises(RuntimeError) as excinfo:
        orca.get_injectable("store")
    assert "store file not found" in str(excinfo.value)

    # these should be None until overridden
    assert orca.get_injectable("hh_index_name") is None
    assert orca.get_injectable("persons_index_name") is None

    # default values if not specified in settings
    assert orca.get_injectable("hh_chunk_size") == 0
    assert orca.get_injectable("chunk_size") == 0
    assert orca.get_injectable("preload_3d_skims") is False

Example 19

Project: python-consul
Source File: test_std.py
View license
    def test_acl_explict_token_use(self, acl_consul):
        c = consul.Consul(port=acl_consul.port)
        master_token = acl_consul.token

        acls = c.acl.list(token=master_token)
        assert set([x['ID'] for x in acls]) == \
            set(['anonymous', master_token])

        assert c.acl.info('1'*36) is None
        compare = [c.acl.info(master_token), c.acl.info('anonymous')]
        compare.sort(key=operator.itemgetter('ID'))
        assert acls == compare

        rules = """
            key "" {
                policy = "read"
            }
            key "private/" {
                policy = "deny"
            }
            service "foo-" {
                policy = "write"
            }
            service "bar-" {
                policy = "read"
            }
        """

        token = c.acl.create(rules=rules, token=master_token)
        assert c.acl.info(token)['Rules'] == rules

        token2 = c.acl.clone(token, token=master_token)
        assert c.acl.info(token2)['Rules'] == rules

        assert c.acl.update(token2, name='Foo', token=master_token) == token2
        assert c.acl.info(token2)['Name'] == 'Foo'

        assert c.acl.destroy(token2, token=master_token) is True
        assert c.acl.info(token2) is None

        c.kv.put('foo', 'bar')
        c.kv.put('private/foo', 'bar')

        assert c.kv.get('foo', token=token)[1]['Value'] == six.b('bar')
        pytest.raises(
            consul.ACLPermissionDenied, c.kv.put, 'foo', 'bar2', token=token)
        pytest.raises(
            consul.ACLPermissionDenied, c.kv.delete, 'foo', token=token)

        assert c.kv.get('private/foo')[1]['Value'] == six.b('bar')
        assert c.kv.get('private/foo', token=token)[1] is None
        pytest.raises(
            consul.ACLPermissionDenied,
            c.kv.put, 'private/foo', 'bar2', token=token)
        pytest.raises(
            consul.ACLPermissionDenied,
            c.kv.delete, 'private/foo', token=token)

        # test token pass through for service registration
        c.agent.service.register("bar-1", token=token)
        c.agent.service.register("foo-1", token=token)
        index, data = c.health.service('foo-1', token=token)
        assert data[0]['Service']['ID'] == "foo-1"
        index, data = c.health.checks('foo-1', token=token)
        assert data == []
        index, data = c.health.service('bar-1', token=token)
        assert not data

        # clean up
        assert c.agent.service.deregister('foo-1') is True
        assert c.agent.service.deregister('bar-1') is True
        c.acl.destroy(token, token=master_token)
        acls = c.acl.list(token=master_token)
        assert set([x['ID'] for x in acls]) == \
            set(['anonymous', master_token])

Example 20

Project: plyvel
Source File: test_plyvel.py
View license
def test_iterator_seeking(db):
    db.put(b'1', b'1')
    db.put(b'2', b'2')
    db.put(b'3', b'3')
    db.put(b'4', b'4')
    db.put(b'5', b'5')

    it = db.iterator(include_value=False)
    it.seek_to_start()
    with pytest.raises(StopIteration):
        it.prev()
    assert next(it) == b'1'
    it.seek_to_start()
    assert next(it) == b'1'
    it.seek_to_stop()
    with pytest.raises(StopIteration):
        next(it)
    assert it.prev() == b'5'

    # Seek to a specific key
    it.seek(b'2')
    assert next(it) == b'2'
    assert next(it) == b'3'
    assert list(it) == [b'4', b'5']
    it.seek(b'2')
    assert it.prev() == b'1'

    # Seek to keys that sort between/before/after existing keys
    it.seek(b'123')
    assert next(it) == b'2'
    it.seek(b'6')
    with pytest.raises(StopIteration):
        next(it)
    it.seek(b'0')
    with pytest.raises(StopIteration):
        it.prev()
    assert next(it) == b'1'
    it.seek(b'4')
    it.seek(b'3')
    assert next(it) == b'3'

    # Seek in a reverse iterator
    it = db.iterator(include_value=False, reverse=True)
    it.seek(b'6')
    assert next(it) == b'5'
    assert next(it) == b'4'
    it.seek(b'1')
    with pytest.raises(StopIteration):
        next(it)
    assert it.prev() == b'1'

    # Seek in iterator with start key
    it = db.iterator(start=b'2', include_value=False)
    assert next(it) == b'2'
    it.seek(b'2')
    assert next(it) == b'2'
    it.seek(b'0')
    assert next(it) == b'2'
    it.seek_to_start()
    assert next(it) == b'2'

    # Seek in iterator with stop key
    it = db.iterator(stop=b'3', include_value=False)
    assert next(it) == b'1'
    it.seek(b'2')
    assert next(it) == b'2'
    it.seek(b'5')
    with pytest.raises(StopIteration):
        next(it)
    it.seek(b'5')
    assert it.prev() == b'2'
    it.seek_to_stop()
    with pytest.raises(StopIteration):
        next(it)
    it.seek_to_stop()
    assert it.prev() == b'2'

    # Seek in iterator with both start and stop keys
    it = db.iterator(start=b'2', stop=b'5', include_value=False)
    it.seek(b'0')
    assert next(it) == b'2'
    it.seek(b'5')
    with pytest.raises(StopIteration):
        next(it)
    it.seek(b'5')
    assert it.prev() == b'4'

    # Seek in reverse iterator with start and stop key
    it = db.iterator(
        reverse=True, start=b'2', stop=b'4', include_value=False)
    it.seek(b'5')
    assert next(it) == b'3'
    it.seek(b'1')
    assert it.prev() == b'2'
    it.seek_to_start()
    with pytest.raises(StopIteration):
        next(it)
    it.seek_to_stop()
    assert next(it) == b'3'

Example 21

Project: profiling
Source File: test_utils.py
View license
def test_runnable():
    # not implemented.
    runnable = Runnable()
    with pytest.raises(NotImplementedError):
        runnable.start()
    # implemented well.
    class Implementation(Runnable):
        step = 1
        def run(self):
            self.step = 2
            yield
            self.step = 3
    runnable = Implementation()
    assert runnable.step == 1
    assert not runnable.is_running()
    runnable.start()
    assert runnable.step == 2
    assert runnable.is_running()
    with pytest.raises(RuntimeError):
        runnable.start()
    runnable.stop()
    assert runnable.step == 3
    assert not runnable.is_running()
    with pytest.raises(RuntimeError):
        runnable.stop()
    # implemented not well.
    class NotYield(Runnable):
        def run(self):
            if False:
                yield
    runnable = NotYield()
    with pytest.raises(TypeError):
        runnable.start()
    class YieldSomething(Runnable):
        def run(self):
            yield 123
    runnable = YieldSomething()
    with pytest.raises(TypeError):
        runnable.start()
    class YieldTwice(Runnable):
        def run(self):
            yield
            yield
    runnable = YieldTwice()
    runnable.start()
    with pytest.raises(TypeError):
        runnable.stop()

Example 22

Project: gnsq
Source File: test_reader.py
View license
def test_basic():
    with pytest.raises(ValueError):
        Reader('test', 'test')

    with pytest.raises(TypeError):
        Reader(
            topic='test',
            channel='test',
            nsqd_tcp_addresses=None,
            lookupd_http_addresses='http://localhost:4161/',
        )

    with pytest.raises(TypeError):
        Reader(
            topic='test',
            channel='test',
            nsqd_tcp_addresses='localhost:4150',
            lookupd_http_addresses=None,
        )

    def message_handler(reader, message):
        pass

    reader = Reader(
        topic='test',
        channel='test',
        name='test',
        max_concurrency=-1,
        nsqd_tcp_addresses='localhost:4150',
        lookupd_http_addresses='http://localhost:4161/',
        message_handler=message_handler
    )

    assert reader.name == 'test'
    assert reader.max_concurrency == multiprocessing.cpu_count()
    assert len(reader.on_message.receivers) == 1

    assert isinstance(reader.nsqd_tcp_addresses, set)
    assert len(reader.nsqd_tcp_addresses) == 1

    assert isinstance(reader.lookupds, list)
    assert len(reader.lookupds) == 1

Example 23

Project: crosscat
Source File: test_pred_prob.py
View license
def test_simple_predictive_probability_unobserved(seed=0):
    T, M_r, M_c, X_L, X_D, engine = quick_le(seed)

    # Must query unobserved rows. CrossCat can only assess same row. We will
    # query one numerical column 0 and categorical column 2.
    Q = [[(N_ROWS, 0, 0.5)], [(N_ROWS, 2, 1)]]


    # Specify complex pattern of reasonable constraints. These tests demonstrate
    # desired behavior (no crashes), and were addressed in the branch
    # fsaad-conditional-pdf
    Y = [(0, 0, 1), (N_ROWS//2, 4, 5), (N_ROWS, 1, 0.5), (N_ROWS+1, 0, 1.2)]
    # - Numerical column Q[0].
    vals = engine.simple_predictive_probability(M_c, X_L, X_D, Y, Q[0])
    # - Categorical column Q[1].
    vals = engine.simple_predictive_probability(M_c, X_L, X_D, Y, Q[1])


    # XXX TODO: Fix more issues discovered
    # The next queries are probabilistically sound, but the code demonstrates
    # bizarre behavior. Determing what to do in all of these special cases is
    # a design problem.


    # Query the cell P(N_ROWS,0)=0.5 GIVEN (N_ROWS,0)==0.5
    # A reasonable human would expect this logp = log(1) = 0... guess not...

    # - Numerical cell Q[0].
    Y = [(N_ROWS, 0, 0.5)]
    val = engine.simple_predictive_probability(M_c, X_L, X_D, Y, Q[0])
    with pytest.raises(AssertionError):
        assert val[0] == 0

    # - Categorical cell Q[1].
    Y = [(N_ROWS, 2, 1)]
    val = engine.simple_predictive_probability(M_c, X_L, X_D, Y, Q[1])
    with pytest.raises(AssertionError):
        assert val[0] == 0


    # Query a hypothetical cell, constraining on another hypothetical row with
    # values in a DIFFERENT column as the column of the query cell.
    # This test does not cause a crash.

    # - Numerical cell Q[0]
    Y = [(N_ROWS, 0, 1.5), (N_ROWS+1, 1, 1.5)]
    vals = engine.simple_predictive_probability(M_c, X_L, X_D, Y, Q[0])

    # - Categorical cell Q[1]
    Y = [(N_ROWS, 2, 4), (N_ROWS+1, 3, 5)]
    vals = engine.simple_predictive_probability(M_c, X_L, X_D, Y, Q[1])


    # Query a hypothetical cell, constraining on another hypothetical row with
    # values in a SAME column as the column of the query cell.
    # This causes an IndexError ...

    # - Numerical cell Q[0]
    Y = [(N_ROWS, 0, 1.5), (N_ROWS+1, 0, 2)]
    with pytest.raises(IndexError):
        vals = engine.simple_predictive_probability(M_c, X_L, X_D, Y, Q[0])

    # - Numerical cell Q[1]
    Y = [(N_ROWS, 2, 4), (N_ROWS+1, 2, 5)]
    with pytest.raises(IndexError):
        vals = engine.simple_predictive_probability(M_c, X_L, X_D, Y, Q[1])

Example 24

Project: mpfshell
Source File: test_mpfexp.py
View license
    def test_directory_handling(self, mpfexp):

        assert "/" == mpfexp.pwd()

        mpfexp.md('dir1')
        mpfexp.md('dir 1')
        mpfexp.md('dir1/subdir1')

        # no duplicate directory names
        with pytest.raises(RemoteIOError):
            mpfexp.md('dir1')

        with pytest.raises(RemoteIOError):
            mpfexp.md('dir1/subdir1')

        # no subdir in non existing dir
        with pytest.raises(RemoteIOError):
            mpfexp.md('dir2/subdir1')

        # relative directory creating
        mpfexp.cd('dir1')
        assert "/dir1" == mpfexp.pwd()
        mpfexp.md('subdir2')

        # created dirs visible for ls and marked as directory
        mpfexp.cd('/')
        assert "/" == mpfexp.pwd()
        assert ('dir1', 'D') in mpfexp.ls(True, True, True)
        assert ('dir 1', 'D') in mpfexp.ls(True, True, True)

        # no dir with same name as existing file
        with pytest.raises(RemoteIOError):
            mpfexp.md('boot.py')

        # subdirs are visible for ls
        mpfexp.cd('dir1')
        assert "/dir1" == mpfexp.pwd()
        assert [('subdir1', 'D'), ('subdir2', 'D')] == mpfexp.ls(True, True, True)

        mpfexp.cd('subdir1')
        assert "/dir1/subdir1" == mpfexp.pwd()
        assert [] == mpfexp.ls(True, True, True)

        mpfexp.cd('..')
        mpfexp.cd('subdir2')
        assert "/dir1/subdir2" == mpfexp.pwd()
        assert [] == mpfexp.ls(True, True, True)

        # no duplicate directory names
        with pytest.raises(RemoteIOError):
            mpfexp.cd('subdir1')

        #FIXME: not working as expected yet
        #mpfexp.cd('../subdir1')
        #assert "/dir1/subdir1" == mpfexp.pwd()

        # allow whitespaces in dir names
        mpfexp.cd('/dir 1')
        assert "/dir 1" == mpfexp.pwd()
        assert [] == mpfexp.ls(True, True, True)

Example 25

Project: eppy
Source File: test_bunch_subclass.py
View license
def test_EpBunch():
    """py.test for EpBunch"""

    iddfile = StringIO(iddtxt)
    fname = StringIO(idftxt)
    block, data, commdct, idd_index = readidf.readdatacommdct1(fname, 
                iddfile=iddfile)

    # setup code walls - can be generic for any object
    ddtt = data.dt
    dtls = data.dtls
    wall_i = dtls.index('BuildingSurface:Detailed'.upper())
    wallkey = 'BuildingSurface:Detailed'.upper()
    wallidd = commdct[wall_i]

    dwalls = ddtt[wallkey]
    dwall = dwalls[0]


    wallfields = [comm.get('field') for comm in commdct[wall_i]]
    wallfields[0] = ['key']
    wallfields = [field[0] for field in wallfields]
    wall_fields = [bunchhelpers.makefieldname(field) for field in wallfields]
    assert wall_fields[:20] == [
        'key', 'Name', 'Surface_Type',
        'Construction_Name', 'Zone_Name', 'Outside_Boundary_Condition',
        'Outside_Boundary_Condition_Object', 'Sun_Exposure', 'Wind_Exposure',
        'View_Factor_to_Ground', 'Number_of_Vertices', 'Vertex_1_Xcoordinate',
        'Vertex_1_Ycoordinate', 'Vertex_1_Zcoordinate', 'Vertex_2_Xcoordinate',
        'Vertex_2_Ycoordinate', 'Vertex_2_Zcoordinate', 'Vertex_3_Xcoordinate',
        'Vertex_3_Ycoordinate', 'Vertex_3_Zcoordinate']


    bwall = EpBunch(dwall, wall_fields, wallidd)

    # print bwall.Name
    # print data.dt[wallkey][0][1]
    assert bwall.Name == data.dt[wallkey][0][1]
    bwall.Name = 'Gumby'
    # print bwall.Name
    # print data.dt[wallkey][0][1]
    # print
    assert bwall.Name == data.dt[wallkey][0][1]

    # set aliases
    bwall.__aliases = {'Constr':'Construction_Name'}

    # print "wall.Construction_Name = %s" % (bwall.Construction_Name, )
    # print "wall.Constr = %s" % (bwall.Constr, )
    # print
    assert bwall.Construction_Name == bwall.Constr
    # print "change wall.Constr"
    bwall.Constr = 'AnewConstr'
    # print "wall.Constr = %s" % (bwall.Constr, )
    # print "wall.Constr = %s" % (data.dt[wallkey][0][3], )
    # print
    assert bwall.Constr == data.dt[wallkey][0][3]

    # add functions
    bwall.__functions = {'svalues':bunch_subclass.somevalues}
    assert 'svalues' in bwall.__functions

    # print bwall.svalues
    assert bwall.svalues == (
        'Gumby', 'AnewConstr',
        [
            'BuildingSurface:Detailed', 'Gumby', 'Wall', 'AnewConstr',
            'West Zone', 'Outdoors', '', 'SunExposed', 'WindExposed',
            '0.5000000', '4', '0', '0', '3.048000', '0', '0', '0', '6.096000',
            '0', '0', '6.096000', '0', '3.048000'])

    # print bwall.__functions

    # test __getitem__
    assert bwall["Name"] == data.dt[wallkey][0][1]
    # test __setitem__
    newname = "loofah"
    bwall["Name"] = newname
    assert bwall.Name == newname
    assert bwall["Name"] == newname
    assert data.dt[wallkey][0][1] == newname
    # test functions and alias again
    assert bwall.Constr == data.dt[wallkey][0][3]
    assert bwall.svalues == (
        newname, 'AnewConstr',
        [
            'BuildingSurface:Detailed', newname, 'Wall', 'AnewConstr',
            'West Zone', 'Outdoors', '', 'SunExposed', 'WindExposed',
            '0.5000000', '4', '0', '0', '3.048000', '0', '0', '0', '6.096000',
            '0', '0', '6.096000', '0', '3.048000'])
    # test bunch_subclass.BadEPFieldError
    with pytest.raises(bunch_subclass.BadEPFieldError):
        bwall.Name_atypo = "newname"
    with pytest.raises(bunch_subclass.BadEPFieldError):
        thename = bwall.Name_atypo
    with pytest.raises(bunch_subclass.BadEPFieldError):
        bwall["Name_atypo"] = "newname"
    with pytest.raises(bunch_subclass.BadEPFieldError):
        thename = bwall["Name_atypo"]

    # test where constr["obj"] has to be extended
    # more items are added to an extendible field
    constr_i = dtls.index('Construction'.upper())
    constrkey = 'Construction'.upper()
    constridd = commdct[constr_i]
    dconstrs = ddtt[constrkey]
    dconstr = dconstrs[0]
    constrfields = [comm.get('field') for comm in commdct[constr_i]]
    constrfields[0] = ['key']
    constrfields = [field[0] for field in constrfields]
    constr_fields = [bunchhelpers.makefieldname(field) for field in constrfields]
    bconstr = EpBunch(dconstr, constr_fields, constridd)
    assert bconstr.Name == "Dbl Clr 3mm/13mm Air"
    bconstr.Layer_4 = "butter"
    assert bconstr.obj == [
        'Construction', 'Dbl Clr 3mm/13mm Air', 'CLEAR 3MM', 'AIR 13MM',
        'CLEAR 3MM', 'butter']
    bconstr.Layer_7 = "cheese"
    assert bconstr.obj == [
        'Construction', 'Dbl Clr 3mm/13mm Air', 'CLEAR 3MM', 'AIR 13MM',
        'CLEAR 3MM', 'butter', '', '', 'cheese']
    bconstr["Layer_8"] = "jam"
    assert bconstr.obj == [
        'Construction', 'Dbl Clr 3mm/13mm Air', 'CLEAR 3MM', 'AIR 13MM',
        'CLEAR 3MM', 'butter', '', '', 'cheese', 'jam']

    # retrieve a valid field that has no value
    assert bconstr.Layer_10 == ''
    assert bconstr["Layer_10"] == ''

Example 26

Project: crosscat
Source File: test_pred_prob.py
View license
def test_predictive_probability_unobserved(seed=0):
    # This function tests the predictive probability for the joint distirbution.
    # Throughout, we will check that the result is the same for the joint and
    # simple calls.
    T, M_r, M_c, X_L, X_D, engine = quick_le(seed)

    # Hypothetical column number should throw an error.
    Q = [(N_ROWS, 1, 1.5), (N_ROWS, 10, 2)]
    Y = []
    with pytest.raises(ValueError):
        vals = engine.predictive_probability(M_c, X_L, X_D, Y, Q)

    # Inconsistent row numbers should throw an error.
    Q = [(N_ROWS, 1, 1.5), (N_ROWS-1, 10, 2)]
    Y = []
    with pytest.raises(ValueError):
        vals = engine.predictive_probability(M_c, X_L, X_D, Y, Q)

    # Duplicate column numbers should throw an error,
    Q = [(N_ROWS, 1, 1.5), (N_ROWS, 1, 2)]
    Y = []
    with pytest.raises(ValueError):
        val = engine.predictive_probability(M_c, X_L, X_D, Y, Q)

    # Different row numbers should throw an error.
    Q = [(N_ROWS, 0, 1.5), (N_ROWS+1, 1, 2)]
    Y = [(N_ROWS, 1, 1.5), (N_ROWS, 2, 3)]
    with pytest.raises(Exception):
        val = engine.predictive_probability(M_c, X_L, X_D, Y, Q[0])

    # Inconsistent with constraints should be negative infinity.
    Q = [(N_ROWS, 1, 1.5), (N_ROWS, 0, 1.3)]
    Y = [(N_ROWS, 1, 1.6)]
    val = engine.predictive_probability(M_c, X_L, X_D, Y, Q)
    assert val == -float('inf')
    assert isinstance(val, float)

    # Consistent with constraints should be log(1) == 0.
    Q = [(N_ROWS, 0, 1.3)]
    Y = [(N_ROWS, 0, 1.3)]
    val = engine.predictive_probability(M_c, X_L, X_D, Y, Q)
    assert val == 0

    # Consistent with constraints should not impact other queries.
    Q = [(N_ROWS, 1, 1.5), (N_ROWS, 0, 1.3)]
    Y = [(N_ROWS, 1, 1.5), (N_ROWS, 2, 3)]
    val_0 = engine.predictive_probability(M_c, X_L, X_D, Y, Q)
    val_1 = engine.predictive_probability(M_c, X_L, X_D, Y, Q[1:])
    assert val_0 == val_1

    # Predictive and simple should be the same in univariate case (cont).
    Q = [(N_ROWS, 0, 0.5)]
    Y = [(0, 0, 1), (N_ROWS//2, 4, 5), (N_ROWS, 1, 0.5), (N_ROWS+1, 0, 1.2)]
    val_0 = engine.predictive_probability(M_c, X_L, X_D, Y, Q)
    val_1 = engine.simple_predictive_probability(M_c, X_L, X_D, Y, Q)
    assert val_0 == val_1

    # Predictive and simple should be the same in univariate case (disc).
    Q = [(N_ROWS, 2, 1)]
    Y = [(0, 0, 1), (N_ROWS//2, 4, 5), (N_ROWS, 1, 0.5), (N_ROWS+1, 0, 1.2)]
    val_0 = engine.predictive_probability(M_c, X_L, X_D, Y, Q)
    val_1 = engine.simple_predictive_probability(M_c, X_L, X_D, Y, Q)
    assert val_0 == val_1

    # Do some full joint queries, all on the same row.
    Q = [(N_ROWS, 3, 4), (N_ROWS, 4, 1.3)]
    Y = [(N_ROWS, 0, 1), (N_ROWS, 1, -0.7), (N_ROWS, 2, 3)]
    val = engine.predictive_probability(M_c, X_L, X_D, Y, Q)
    assert isinstance(val, float)

    Q = [(N_ROWS, 0, 1), (N_ROWS, 1, -0.7), (N_ROWS, 2, 3)]
    Y = [(N_ROWS, 3, 4), (N_ROWS, 4, 1.3)]
    val = engine.predictive_probability(M_c, X_L, X_D, Y, Q)
    assert isinstance(val, float)

Example 27

Project: umongo
Source File: test_fields.py
View license
    def test_embedded_inheritance(self):
        @self.instance.register
        class EmbeddedParent(EmbeddedDocument):
            a = fields.IntField(attribute='in_mongo_a_parent')
            b = fields.IntField()

        @self.instance.register
        class EmbeddedChild(EmbeddedParent):
            a = fields.IntField(attribute='in_mongo_a_child')
            c = fields.IntField()

        @self.instance.register
        class GrandChild(EmbeddedChild):
            d = fields.IntField()

        @self.instance.register
        class OtherEmbedded(EmbeddedDocument):
            pass

        @self.instance.register
        class MyDoc(Document):
            parent = fields.EmbeddedField(EmbeddedParent)
            child = fields.EmbeddedField(EmbeddedChild)

        assert 'EmbeddedChild' in EmbeddedParent.opts.children
        assert 'OtherEmbedded' not in EmbeddedParent.opts.children

        parent = EmbeddedParent(a=1)
        child = EmbeddedChild(a=1, b=2, c=3)
        grandchild = GrandChild(d=4)

        assert parent.to_mongo() == {'in_mongo_a_parent': 1}
        assert child.to_mongo() == {'in_mongo_a_child': 1, 'b': 2, 'c': 3, '_cls': 'EmbeddedChild'}
        assert grandchild.to_mongo() == {'d': 4, '_cls': 'GrandChild'}

        with pytest.raises(ValidationError):
            ret = MyDoc(parent=OtherEmbedded())
        with pytest.raises(ValidationError):
            ret = MyDoc(child=parent)
        doc = MyDoc(parent=child, child=child)
        assert doc.child == doc.parent

        doc = MyDoc(child={'a': 1, 'cls': 'GrandChild'},
                    parent={'cls': 'EmbeddedChild', 'a': 1})
        assert doc.child.to_mongo() == {'in_mongo_a_child': 1, '_cls': 'GrandChild'}
        assert doc.parent.to_mongo() == {'in_mongo_a_child': 1, '_cls': 'EmbeddedChild'}

        with pytest.raises(ValidationError) as exc:
            MyDoc(child={'a': 1, '_cls': 'GrandChild'})
        assert exc.value.messages == {'child': {'_schema': ['Unknown field name _cls.']}}

        # Try to build a non-child document
        with pytest.raises(ValidationError) as exc:
            MyDoc(child={'cls': 'OtherEmbedded'})
        assert exc.value.messages == {'child': ['Unknown document `OtherEmbedded`.']}

        # Test embedded child deserialization from mongo
        child = EmbeddedChild(c=69)
        doc = MyDoc(parent=child)
        mongo_data = doc.to_mongo()
        doc2 = MyDoc.build_from_mongo(mongo_data)
        assert isinstance(doc2.parent, EmbeddedChild)
        assert doc._data == doc2._data

Example 28

View license
def test_conda_create_and_install_and_remove(monkeypatch):
    monkeypatch_conda_not_to_use_links(monkeypatch)

    spec = EnvSpec(name='myenv', conda_packages=['ipython'], pip_packages=['flake8'], channels=[])
    assert spec.conda_packages == ('ipython', )
    assert spec.pip_packages == ('flake8', )

    spec_with_phony_pip_package = EnvSpec(name='myenv',
                                          conda_packages=['ipython'],
                                          pip_packages=['flake8', 'nope_not_a_thing'],
                                          channels=[])
    assert spec_with_phony_pip_package.conda_packages == ('ipython', )
    assert spec_with_phony_pip_package.pip_packages == ('flake8', 'nope_not_a_thing')

    def do_test(dirname):
        envdir = os.path.join(dirname, spec.name)

        manager = DefaultCondaManager()

        assert not os.path.isdir(envdir)
        assert not os.path.exists(os.path.join(envdir, IPYTHON_BINARY))
        assert not os.path.exists(os.path.join(envdir, FLAKE8_BINARY))

        deviations = manager.find_environment_deviations(envdir, spec)

        assert deviations.missing_packages == ('ipython', )
        assert deviations.missing_pip_packages == ('flake8', )

        manager.fix_environment_deviations(envdir, spec, deviations)

        assert os.path.isdir(envdir)
        assert os.path.isdir(os.path.join(envdir, "conda-meta"))
        assert os.path.exists(os.path.join(envdir, IPYTHON_BINARY))
        assert os.path.exists(os.path.join(envdir, FLAKE8_BINARY))

        # test bad pip package throws error
        deviations = manager.find_environment_deviations(envdir, spec_with_phony_pip_package)

        assert deviations.missing_packages == ()
        assert deviations.missing_pip_packages == ('nope_not_a_thing', )

        with pytest.raises(CondaManagerError) as excinfo:
            manager.fix_environment_deviations(envdir, spec, deviations)
        assert 'Failed to install missing pip packages' in str(excinfo.value)

        # test that we can remove a package
        manager.remove_packages(prefix=envdir, packages=['ipython'])
        assert not os.path.exists(os.path.join(envdir, IPYTHON_BINARY))

        # test for error removing
        with pytest.raises(CondaManagerError) as excinfo:
            manager.remove_packages(prefix=envdir, packages=['ipython'])
        assert 'no packages found to remove' in str(excinfo.value)

        # test failure to exec pip
        def mock_call_pip(*args, **kwargs):
            raise pip_api.PipError("pip fail")

        monkeypatch.setattr('conda_kapsel.internal.pip_api._call_pip', mock_call_pip)

        with pytest.raises(CondaManagerError) as excinfo:
            deviations = manager.find_environment_deviations(envdir, spec)
        assert 'pip failed while listing' in str(excinfo.value)

    with_directory_contents(dict(), do_test)

Example 29

Project: piecash
Source File: test_transaction.py
View license
    def test_create_cdtytransaction(self, book_basic):
        EUR = book_basic.commodities(namespace="CURRENCY")
        racc = book_basic.root_account
        a = book_basic.accounts(name="asset")
        s = book_basic.accounts(name="broker")

        tr = Transaction(currency=EUR, description="buy stock", notes=u"on St-Eugène day",
                         post_date=datetime(2014, 1, 2),
                         enter_date=datetime(2014, 1, 3),
                         splits=[
                             Split(account=a, value=100, memo=u"mémo asset"),
                             Split(account=s, value=-90, memo=u"mémo brok"),
                         ])

        # check issue with quantity for broker split not defined
        with pytest.raises(GncValidationError):
            book_basic.validate()

        sb = tr.splits(account=s)
        sb.quantity = 15

        # check issue with quantity not same sign as value
        with pytest.raises(GncValidationError):
            book_basic.validate()

        sb.quantity = -15

        # verify imbalance issue
        with pytest.raises(GncImbalanceError):
            book_basic.validate()

        # adjust balance
        Split(account=a, value=-10, memo="missing asset corr", transaction=tr)
        book_basic.save()
        assert str(sb)
        assert str(sb)

        # changing currency of an existing transaction is not allowed
        tr.currency = book_basic.currencies(mnemonic="USD")
        with pytest.raises(GncValidationError):
            book_basic.validate()
        book_basic.cancel()

        # check sum of quantities are not balanced per commodity but values are
        d = defaultdict(lambda: Decimal(0))
        for sp in tr.splits:
            assert sp.quantity == sp.value or sp.account != a
            d[sp.account.commodity] += sp.quantity
            d["cur"] += sp.value
        assert d["cur"] == 0
        assert all([v != 0 for k, v in d.items() if k != "cur"])

Example 30

Project: kapsel
Source File: test_pip_api.py
View license
def test_pip_errors(monkeypatch):
    monkeypatch_conda_not_to_use_links(monkeypatch)

    def do_test(dirname):
        envdir = os.path.join(dirname, "myenv")

        conda_api.create(prefix=envdir, pkgs=['python'])

        # no packages to install
        with pytest.raises(TypeError) as excinfo:
            pip_api.install(prefix=envdir, pkgs=[])
        assert 'must specify a list' in repr(excinfo.value)

        # no packages to remove
        with pytest.raises(TypeError) as excinfo:
            pip_api.remove(prefix=envdir, pkgs=[])
        assert 'must specify a list' in repr(excinfo.value)

        # pip command not installed
        from os.path import exists as real_exists

        def mock_exists(path):
            if path.endswith("pip") or path.endswith("pip.exe"):
                return False
            else:
                return real_exists(path)

        monkeypatch.setattr('os.path.exists', mock_exists)
        with pytest.raises(pip_api.PipNotInstalledError) as excinfo:
            pip_api.install(prefix=envdir, pkgs=['foo'])
        assert 'command is not installed in the environment' in repr(excinfo.value)

        installed = pip_api.installed(prefix=envdir)
        assert dict() == installed  # with pip not installed, no packages are listed.

        # pip command exits nonzero
        error_script = """from __future__ import print_function
import sys
print("TEST_ERROR", file=sys.stderr)
sys.exit(1)
"""

        def get_failed_command(prefix, extra_args):
            return tmp_script_commandline(error_script)

        monkeypatch.setattr('conda_kapsel.internal.pip_api._get_pip_command', get_failed_command)
        with pytest.raises(pip_api.PipError) as excinfo:
            pip_api.install(prefix=envdir, pkgs=['flake8'])
        assert 'TEST_ERROR' in repr(excinfo.value)

        # pip command exits zero printing stuff on stderr
        error_message_but_success_script = """from __future__ import print_function
import sys
print("TEST_ERROR", file=sys.stderr)
sys.exit(0)
"""

        def get_failed_command(prefix, extra_args):
            return tmp_script_commandline(error_message_but_success_script)

        monkeypatch.setattr('conda_kapsel.internal.pip_api._get_pip_command', get_failed_command)
        pip_api.install(prefix=envdir, pkgs=['flake8'])

        # cannot exec pip
        def mock_popen(args, stdout=None, stderr=None):
            raise OSError("failed to exec")

        monkeypatch.setattr('subprocess.Popen', mock_popen)
        with pytest.raises(pip_api.PipError) as excinfo:
            pip_api.install(prefix=envdir, pkgs=['flake8'])
        assert 'failed to exec' in repr(excinfo.value)

    with_directory_contents(dict(), do_test)

Example 31

Project: python-consul
Source File: test_std.py
View license
    def test_acl_implicit_token_use(self, acl_consul):
        # configure client to use the master token by default
        c = consul.Consul(port=acl_consul.port, token=acl_consul.token)
        master_token = acl_consul.token

        acls = c.acl.list()
        assert set([x['ID'] for x in acls]) == \
            set(['anonymous', master_token])

        assert c.acl.info('foo') is None
        compare = [c.acl.info(master_token), c.acl.info('anonymous')]
        compare.sort(key=operator.itemgetter('ID'))
        assert acls == compare

        rules = """
            key "" {
                policy = "read"
            }
            key "private/" {
                policy = "deny"
            }
        """
        token = c.acl.create(rules=rules)
        assert c.acl.info(token)['Rules'] == rules

        token2 = c.acl.clone(token)
        assert c.acl.info(token2)['Rules'] == rules

        assert c.acl.update(token2, name='Foo') == token2
        assert c.acl.info(token2)['Name'] == 'Foo'

        assert c.acl.destroy(token2) is True
        assert c.acl.info(token2) is None

        c.kv.put('foo', 'bar')
        c.kv.put('private/foo', 'bar')

        c_limited = consul.Consul(port=acl_consul.port, token=token)
        assert c_limited.kv.get('foo')[1]['Value'] == six.b('bar')
        pytest.raises(
            consul.ACLPermissionDenied, c_limited.kv.put, 'foo', 'bar2')
        pytest.raises(
            consul.ACLPermissionDenied, c_limited.kv.delete, 'foo')

        assert c.kv.get('private/foo')[1]['Value'] == six.b('bar')
        assert c_limited.kv.get('private/foo')[1] is None
        pytest.raises(
            consul.ACLPermissionDenied,
            c_limited.kv.put, 'private/foo', 'bar2')
        pytest.raises(
            consul.ACLPermissionDenied,
            c_limited.kv.delete, 'private/foo')

        # check we can override the client's default token
        assert c.kv.get('private/foo', token=token)[1] is None
        pytest.raises(
            consul.ACLPermissionDenied,
            c.kv.put, 'private/foo', 'bar2', token=token)
        pytest.raises(
            consul.ACLPermissionDenied,
            c.kv.delete, 'private/foo', token=token)

        # clean up
        c.acl.destroy(token)
        acls = c.acl.list()
        assert set([x['ID'] for x in acls]) == \
            set(['anonymous', master_token])

Example 32

Project: giraffez
Source File: test_load.py
View license
    def test_load_from_file_invalid_header(self, mocker, tmpfiles):
        mock_connect = mocker.patch("giraffez.Cmd._connect")
        mock_execute = mocker.patch("giraffez.Cmd._execute")

        columns = Columns([
            ("col1", VARCHAR_NN, 50, 0, 0),
            ("col2", VARCHAR_N, 50, 0, 0),
            ("col3", VARCHAR_N, 50, 0, 0),
        ])

        mock_columns = mocker.patch("giraffez.Cmd.get_columns")

        mock_columns.return_value = columns

        # Invalid column (blank string)
        with open(tmpfiles.load_file, 'w') as f:
            f.write("|".join(["col1", "col2", "col3", "", ""]))
            f.write("\n")
            f.write("|".join(["value1", "value2", "value3"]))
            f.write("\n")

        with giraffez.Load() as load:
            load.panic = True
            with pytest.raises(GiraffeError):
                result = load.from_file("db1.test", tmpfiles.load_file, delimiter="|")
                print(result)

        # Invalid column (wrong name)
        with open(tmpfiles.load_file, 'w') as f:
            f.write("|".join(["col1", "col2", "col4"]))
            f.write("\n")
            f.write("|".join(["value1", "value2", "value3"]))
            f.write("\n")

        with giraffez.Load() as load:
            load.panic = True
            with pytest.raises(GiraffeError):
                result = load.from_file("db1.test", tmpfiles.load_file, delimiter="|")
                print(result)

        # Too many columns (duplicate name)
        with open(tmpfiles.load_file, 'w') as f:
            f.write("|".join(["col1", "col2", "col3", "col3"]))
            f.write("\n")
            f.write("|".join(["value1", "value2", "value3"]))
            f.write("\n")

        with giraffez.Load() as load:
            load.panic = True
            with pytest.raises(GiraffeEncodeError):
                result = load.from_file("db1.test", tmpfiles.load_file, delimiter="|")
                print(result)

Example 33

Project: stringphone
Source File: test_topic.py
View license
@given(binary())
def test_discovery(bytestring):
    master = Topic(topic_key=generate_topic_key())
    slave = Topic()

    # Construct the introduction on the slave.
    intro = slave.construct_intro()

    # Attempt to read the introduction on the master.
    with pytest.raises(IntroductionError):
        master.decode(intro)

    # Trust the slave.
    public_key = Message(intro).sender_key
    master.add_participant(public_key)

    # If the intro contains a public key that didn't sign
    # the encryption key, assert that we raise an error.
    bad_intro = bytearray(intro[0:1]) + bytearray(master.public_key) + \
        intro[33:]
    with pytest.raises(BadSignatureError):
        master.construct_reply(bad_intro)

    # Reply to the slave with the encrypted topic key.
    reply = master.construct_reply(intro)

    # Assert that decoding the reply returns None (because it's not addressed
    # to us).

    # Assert that the reply raises IntroductionReplyError (because it's a reply,
    # not a simple message).
    with pytest.raises(IntroductionReplyError):
        slave.decode(reply)

    # Trust the master on the slave.
    public_key = Message(reply).sender_key
    slave.add_participant(public_key)

    # Decode the introduction reply, getting the topic key.
    slave.parse_reply(reply)

    # Now we can decrypt all messages.
    assert slave.decode(master.encode(bytestring)) == bytestring
    assert master.decode(slave.encode(bytestring)) == bytestring

Example 34

Project: pymtl
Source File: SimulationTool_mix_test.py
View license
def test_SliceWriteCheck( setup_sim ):

  model = SliceWriteCheck( 16 )
  model, sim = setup_sim( model )
  assert model.out == 0

  # Test regular write
  model.in_.n = 8
  sim.cycle()
  assert model.out == 0b1000

  # Slice then .n, should pass
  model.in_[0].n = 1
  sim.cycle()
  assert model.out == 0b1001
  model.in_[4:8].n = 0b1001
  sim.cycle()
  assert model.out == 0b10011001

  # Test regular write
  model.in_.n = 8
  sim.cycle()
  assert model.out == 0b1000

  # Only slice, should fail
  model.in_[0] = 1
  sim.cycle()
  with pytest.raises( AssertionError ):
    assert model.out == 0b1001
  model.in_[4:8] = 0b1001
  sim.cycle()
  with pytest.raises( AssertionError ):
    assert model.out == 0b10011001

  # Test regular write
  model.in_.n = 8
  sim.cycle()
  assert model.out == 0b1000

  # .n then slice, should fail
  model.in_.n[0] = 1
  sim.cycle()
  with pytest.raises( AssertionError ):
    assert model.out == 0b1001
  model.in_.n[4:8] = 0b1001
  sim.cycle()
  with pytest.raises( AssertionError ):
    assert model.out == 0b10011001

Example 35

Project: pyqtgraph
Source File: test_functions.py
View license
def test_interpolateArray():
    def interpolateArray(data, x):
        result = pg.interpolateArray(data, x)
        assert result.shape == x.shape[:-1] + data.shape[x.shape[-1]:]
        return result
    
    data = np.array([[ 1.,   2.,   4.  ],
                     [ 10.,  20.,  40. ],
                     [ 100., 200., 400.]])
    
    # test various x shapes
    interpolateArray(data, np.ones((1,)))
    interpolateArray(data, np.ones((2,)))
    interpolateArray(data, np.ones((1, 1)))
    interpolateArray(data, np.ones((1, 2)))
    interpolateArray(data, np.ones((5, 1)))
    interpolateArray(data, np.ones((5, 2)))
    interpolateArray(data, np.ones((5, 5, 1)))
    interpolateArray(data, np.ones((5, 5, 2)))
    with pytest.raises(TypeError):
        interpolateArray(data, np.ones((3,)))
    with pytest.raises(TypeError):
        interpolateArray(data, np.ones((1, 3,)))
    with pytest.raises(TypeError):
        interpolateArray(data, np.ones((5, 5, 3,)))
    
    
    x = np.array([[  0.3,   0.6],
                  [  1. ,   1. ],
                  [  0.5,   1. ],
                  [  0.5,   2.5],
                  [ 10. ,  10. ]])
    
    result = interpolateArray(data, x)
    #import scipy.ndimage
    #spresult = scipy.ndimage.map_coordinates(data, x.T, order=1)
    spresult = np.array([  5.92,  20.  ,  11.  ,   0.  ,   0.  ])  # generated with the above line
    
    assert_array_almost_equal(result, spresult)
    
    # test mapping when x.shape[-1] < data.ndim
    x = np.array([[  0.3,   0],
                  [  0.3,   1],
                  [  0.3,   2]])
    r1 = interpolateArray(data, x)
    x = np.array([0.3])  # should broadcast across axis 1
    r2 = interpolateArray(data, x)
    
    assert_array_almost_equal(r1, r2)
    
    
    # test mapping 2D array of locations
    x = np.array([[[0.5, 0.5], [0.5, 1.0], [0.5, 1.5]],
                  [[1.5, 0.5], [1.5, 1.0], [1.5, 1.5]]])
    
    r1 = interpolateArray(data, x)
    #r2 = scipy.ndimage.map_coordinates(data, x.transpose(2,0,1), order=1)
    r2 = np.array([[   8.25,   11.  ,   16.5 ],  # generated with the above line
                   [  82.5 ,  110.  ,  165.  ]])

    assert_array_almost_equal(r1, r2)
    
    
    # test interpolate where data.ndim > x.shape[1]
    
    data = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]) # 2x2x3
    x = np.array([[1, 1], [0, 0.5], [5, 5]])
    
    r1 = interpolateArray(data, x)
    assert np.all(r1[0] == data[1, 1])
    assert np.all(r1[1] == 0.5 * (data[0, 0] + data[0, 1]))
    assert np.all(r1[2] == 0)

Example 36

View license
def test_spread():
    p = 0x7d00007d
    g = 0x7d00FF00
    b = 0x7dFF0000
    data = np.array([[p, p, 0, 0, 0],
                     [p, g, 0, 0, 0],
                     [0, 0, 0, 0, 0],
                     [0, 0, 0, b, 0],
                     [0, 0, 0, 0, 0]], dtype='uint32')
    coords = [np.arange(5), np.arange(5)]
    img = tf.Image(data, coords=coords, dims=dims)

    s = tf.spread(img)
    o = np.array([[0xed00863b, 0xed00863b, 0xbc00a82a, 0x00000000, 0x00000000],
                  [0xed00863b, 0xed00863b, 0xbc00a82a, 0x00000000, 0x00000000],
                  [0xbc00a82a, 0xbc00a82a, 0xbca85600, 0x7dff0000, 0x7dff0000],
                  [0x00000000, 0x00000000, 0x7dff0000, 0x7dff0000, 0x7dff0000],
                  [0x00000000, 0x00000000, 0x7dff0000, 0x7dff0000, 0x7dff0000]])
    np.testing.assert_equal(s.data, o)
    assert (s.x_axis == img.x_axis).all()
    assert (s.y_axis == img.y_axis).all()
    assert s.dims == img.dims

    s = tf.spread(img, px=2)
    o = np.array([[0xed00863b, 0xed00863b, 0xed00863b, 0xbc00a82a, 0x00000000],
                  [0xed00863b, 0xed00863b, 0xf581411c, 0xdc904812, 0x7dff0000],
                  [0xed00863b, 0xf581411c, 0xed864419, 0xbca85600, 0x7dff0000],
                  [0xbc00a82a, 0xdc904812, 0xbca85600, 0x7dff0000, 0x7dff0000],
                  [0x00000000, 0x7dff0000, 0x7dff0000, 0x7dff0000, 0x7dff0000]])
    np.testing.assert_equal(s.data, o)

    s = tf.spread(img, shape='square')
    o = np.array([[0xed00863b, 0xed00863b, 0xbc00a82a, 0x00000000, 0x00000000],
                  [0xed00863b, 0xed00863b, 0xbc00a82a, 0x00000000, 0x00000000],
                  [0xbc00a82a, 0xbc00a82a, 0xbca85600, 0x7dff0000, 0x7dff0000],
                  [0x00000000, 0x00000000, 0x7dff0000, 0x7dff0000, 0x7dff0000],
                  [0x00000000, 0x00000000, 0x7dff0000, 0x7dff0000, 0x7dff0000]])
    np.testing.assert_equal(s.data, o)

    s = tf.spread(img, how='add')
    o = np.array([[0xff007db7, 0xff007db7, 0xfa007f3e, 0x00000000, 0x00000000],
                  [0xff007db7, 0xff007db7, 0xfa007f3e, 0x00000000, 0x00000000],
                  [0xfa007f3e, 0xfa007f3e, 0xfa7f7f00, 0x7dff0000, 0x7dff0000],
                  [0x00000000, 0x00000000, 0x7dff0000, 0x7dff0000, 0x7dff0000],
                  [0x00000000, 0x00000000, 0x7dff0000, 0x7dff0000, 0x7dff0000]])
    np.testing.assert_equal(s.data, o)

    mask = np.array([[1, 0, 1],
                     [0, 1, 0],
                     [1, 0, 1]])
    s = tf.spread(img, mask=mask)
    o = np.array([[0xbc00a82a, 0xbc00007d, 0x7d00ff00, 0x00000000, 0x00000000],
                  [0xbc00007d, 0xbc00a82a, 0x7d00007d, 0x00000000, 0x00000000],
                  [0x7d00ff00, 0x7d00007d, 0xbca85600, 0x00000000, 0x7dff0000],
                  [0x00000000, 0x00000000, 0x00000000, 0x7dff0000, 0x00000000],
                  [0x00000000, 0x00000000, 0x7dff0000, 0x00000000, 0x7dff0000]])
    np.testing.assert_equal(s.data, o)

    s = tf.spread(img, px=0)
    np.testing.assert_equal(s.data, img.data)

    pytest.raises(ValueError, lambda: tf.spread(img, px=-1))
    pytest.raises(ValueError, lambda: tf.spread(img, mask=np.ones(2)))
    pytest.raises(ValueError, lambda: tf.spread(img, mask=np.ones((2, 2))))

Example 37

Project: zerodb
Source File: test_ssl.py
View license
def _test_basic(root_cert=True, root_password=False,
                user_cert=True, user_password=False,
                ):

    if root_password:
        root_pwd, _ = kdf.hash_password(
                'root', 'root_password',
                key_file=None, cert_file=None,
                appname='zerodb.com', key=None)

    # zerodb.server took care of setting up a databasw with a root
    # user and starting a server for it.  The root user's cert is from
    # ZEO.testing.  The server is using a server cert from ZEO.tests.
    addr, stop = zerodb.server(
        init=dict(
            cert=ZEO.tests.testssl.client_cert if root_cert else None,
            password='root_password' if root_password else None,
            ),
        )

    # Create an admin client.  Admin data aren't encrypted, so we use
    # a regular ZEO client.
    # XXX this should be in zerodb.db
    # XXX along with kdf
    def admin_db_factory():
        return ZEO.DB(
            addr,
            ssl=ZEO.tests.testssl.client_ssl() if root_cert else nobody_ssl(),
            credentials=dict(name='root', password=root_pwd)
            if root_password else None,
            wait_timeout=19999,
            )

    admin_db = admin_db_factory()
    with admin_db.transaction() as conn:

        # The get_admin function gets us an admin object with CRUD methods.
        admin = zerodb.permissions.base.get_admin(conn)
        [root] = admin.users.values()
        if root_cert:
            [root_der] = root.certs

            assert (set(pem.strip()
                        for pem in admin.certs.data.strip().split('\n\n')) ==
                    set(pem.strip()
                        for pem in (nobody_pem, root.certs[root_der]))
                    )
            assert admin.uids[root_der] == root.id
        else:
            assert admin.certs.data.strip() == nobody_pem.strip()
        assert len(admin.uids) == 2 if root_cert else 1
        assert len(admin.users_by_name) == 1
        assert admin.users_by_name[root.name] is root

        # Let's add a user:
        admin.add_user('user0',
                       pem_data=(pem_data('cert0') if user_cert else None),
                       password=('password0' if user_password else None),
                       )

        [uid0] = [uid for uid in admin.users if uid != root.id]

    admin_db.close()

    # Now, let's try connecting
    def user_db_factory(n='0'):
        return zerodb.DB(
            addr, username='user0', key=user_key,
            cert_file=pem_path('cert' + n) if user_cert else None,
            key_file=pem_path('key' + n) if user_cert else None,
            server_cert=ZEO.tests.testssl.server_cert,
            password='password' + n if user_password else None,
            wait_timeout=1
            )

    db = user_db_factory()

    # we can access the root object.
    assert db._root._p_oid == uid0

    # It's empty now:
    assert len(db._root) == 0

    # Let's put something it:
    db._root['x'] = 1
    db._root['s'] = db._root.__class__()
    db._root['s']['x'] = 2

    db._connection.transaction_manager.commit()

    # Close the db and reopen:
    db._db.close()

    # Reopen, and make sure the data are there:
    db = user_db_factory()

    assert db._root._p_oid == uid0
    assert len(db._root) == 2
    assert db._root['x'] == 1
    assert db._root['s']['x'] == 2
    db._db.close()

    # The admin user can no longer access the user's folder:
    admin_db = admin_db_factory()
    with admin_db.transaction() as conn:
        admin = zerodb.permissions.base.get_admin(conn)
        user_root = admin.users[uid0].root
        with pytest.raises(ZODB.POSException.StorageError) as exc_info:
            len(user_root)

        assert ('Attempt to access encrypted data of others'
                in str(exc_info.value))

    # Note that we had to close and reopen the admin connection
    # because invalidations aren't sent accross users. (Even clearing
    # the cache doesn't work (maybe a misfeature))

    # The user's data are encrypted:
    server_server = zerodb.forker.last_server
    storage = server_server.server.storages['1']
    assert storage.loadBefore(uid0, maxtid)[0].startswith(b'.e')

    # Let's change the user's credentials:

    with admin_db.transaction() as conn:
        admin = zerodb.permissions.base.get_admin(conn)
        admin.change_cert(
            'user0',
            pem_data('cert1') if user_cert else None,
            'password1' if user_password else None,
            )

    # Now login with the old cert will fail:
    with pytest.raises(ZEO.Exceptions.ClientDisconnected):
        user_db_factory()

    # But login with the new one will work:
    db = user_db_factory('1')
    assert len(db._root) == 2
    db._db.close()

    # Finally, let's remove the user:
    with admin_db.transaction() as conn:
        admin = zerodb.permissions.base.get_admin(conn)
        admin.del_user('user0')

    # Now, they can't log in at all:
    for i in '01':
        with pytest.raises(ZEO.Exceptions.ClientDisconnected):
            user_db_factory(i)

    admin_db.close()

    # The admin user can login as an ordinary ZeroDB user:
    db = zerodb.DB(
        addr, username='root', key=root_key,
        cert_file=ZEO.tests.testssl.client_cert if root_cert else None,
        key_file=ZEO.tests.testssl.client_key if root_cert else None,
        server_cert=ZEO.tests.testssl.server_cert,
        password='root_password' if root_password else None,
        wait_timeout=1
        )
    # They have an empty root
    assert len(db._root) == 0

    stop()

Example 38

Project: python-consul
Source File: test_std.py
View license
    def test_catalog(self, consul_port):
        c = consul.Consul(port=consul_port)

        # grab the node our server created, so we can ignore it
        _, nodes = c.catalog.nodes()
        assert len(nodes) == 1
        current = nodes[0]

        # test catalog.datacenters
        assert c.catalog.datacenters() == ['dc1']

        # test catalog.register
        pytest.raises(
            consul.ConsulException,
            c.catalog.register, 'foo', '10.1.10.11', dc='dc2')

        assert c.catalog.register(
            'n1',
            '10.1.10.11',
            service={'service': 's1'},
            check={'name': 'c1'}) is True
        assert c.catalog.register(
            'n1', '10.1.10.11', service={'service': 's2'}) is True
        assert c.catalog.register(
            'n2', '10.1.10.12',
            service={'service': 's1', 'tags': ['master']}) is True

        # test catalog.nodes
        pytest.raises(consul.ConsulException, c.catalog.nodes, dc='dc2')
        _, nodes = c.catalog.nodes()
        nodes.remove(current)
        assert [x['Node'] for x in nodes] == ['n1', 'n2']

        # test catalog.services
        pytest.raises(consul.ConsulException, c.catalog.services, dc='dc2')
        _, services = c.catalog.services()
        assert services == {'s1': [u'master'], 's2': [], 'consul': []}

        # test catalog.node
        pytest.raises(consul.ConsulException, c.catalog.node, 'n1', dc='dc2')
        _, node = c.catalog.node('n1')
        assert set(node['Services'].keys()) == set(['s1', 's2'])
        _, node = c.catalog.node('n3')
        assert node is None

        # test catalog.service
        pytest.raises(
            consul.ConsulException, c.catalog.service, 's1', dc='dc2')
        _, nodes = c.catalog.service('s1')
        assert set([x['Node'] for x in nodes]) == set(['n1', 'n2'])
        _, nodes = c.catalog.service('s1', tag='master')
        assert set([x['Node'] for x in nodes]) == set(['n2'])

        # test catalog.deregister
        pytest.raises(
            consul.ConsulException, c.catalog.deregister, 'n2', dc='dc2')
        assert c.catalog.deregister('n1', check_id='c1') is True
        assert c.catalog.deregister('n2', service_id='s1') is True
        # check the nodes weren't removed
        _, nodes = c.catalog.nodes()
        nodes.remove(current)
        assert [x['Node'] for x in nodes] == ['n1', 'n2']
        # check n2's s1 service was removed though
        _, nodes = c.catalog.service('s1')
        assert set([x['Node'] for x in nodes]) == set(['n1'])

        # cleanup
        assert c.catalog.deregister('n1') is True
        assert c.catalog.deregister('n2') is True
        _, nodes = c.catalog.nodes()
        nodes.remove(current)
        assert [x['Node'] for x in nodes] == []

Example 39

Project: raiden
Source File: test_channel_manager.py
View license
def test_channelmanager(tester_state, tester_token, tester_events,
                        tester_channelmanager_library_address, settle_timeout,
                        netting_channel_abi):
    # pylint: disable=too-many-locals,too-many-statements

    address0 = tester.DEFAULT_ACCOUNT
    address1 = tester.a1
    address2 = tester.a2
    inexisting_address = sha3('this_does_not_exist')[:20]

    channelmanager_path = get_contract_path('ChannelManagerContract.sol')
    channel_manager = tester_state.abi_contract(
        None,
        path=channelmanager_path,
        language='solidity',
        constructor_parameters=[tester_token.address],
        contract_name='ChannelManagerContract',
        log_listener=tester_events.append,
        libraries={
            'ChannelManagerLibrary': tester_channelmanager_library_address.encode('hex'),
        }
    )

    assert len(channel_manager.getChannelsParticipants()) == 0, 'newly deployed contract must be empty'

    netting_channel_translator = ContractTranslator(netting_channel_abi)

    previous_events = list(tester_events)
    netting_channel_address1_hex = channel_manager.newChannel(
        address1,
        settle_timeout,
    )
    assert len(previous_events) + 1 == len(tester_events), 'ChannelNew event must be fired.'

    channelnew_event = tester_events[-1]
    assert channelnew_event == {
        '_event_type': 'ChannelNew',
        'participant1': address0.encode('hex'),
        'participant2': address1.encode('hex'),
        'netting_channel': netting_channel_address1_hex,
        'settle_timeout': settle_timeout,
    }

    # should fail if settleTimeout is too low
    with pytest.raises(TransactionFailed):
        channel_manager.newChannel(address1, 5)

    # cannot have two channels at the same time
    with pytest.raises(TransactionFailed):
        channel_manager.newChannel(address1, settle_timeout)

    # should trow if there is no channel for the given address
    with pytest.raises(TransactionFailed):
        channel_manager.getChannelWith(inexisting_address)

    assert len(channel_manager.getChannelsParticipants()) == 2

    netting_contract_proxy1 = ABIContract(
        tester_state,
        netting_channel_translator,
        netting_channel_address1_hex,
    )

    assert netting_contract_proxy1.settleTimeout() == settle_timeout

    previous_events = list(tester_events)
    netting_channel_address2_hex = channel_manager.newChannel(
        address2,
        settle_timeout,
    )
    assert len(previous_events) + 1 == len(tester_events), 'ChannelNew event must be fired.'

    assert channel_manager.getChannelWith(address1) == netting_channel_address1_hex
    assert channel_manager.getChannelWith(address2) == netting_channel_address2_hex

    msg_sender_channels = channel_manager.nettingContractsByAddress(tester.DEFAULT_ACCOUNT)
    address1_channels = channel_manager.nettingContractsByAddress(address1)
    inexisting_channels = channel_manager.nettingContractsByAddress(inexisting_address)

    assert len(msg_sender_channels) == 2
    assert len(address1_channels) == 1
    assert len(inexisting_channels) == 0

    assert len(channel_manager.getChannelsParticipants()) == 4

    channelnew_event = tester_events[-1]
    assert channelnew_event == {
        '_event_type': 'ChannelNew',
        'participant1': address0.encode('hex'),
        'participant2': address2.encode('hex'),
        'netting_channel': netting_channel_address2_hex,
        'settle_timeout': settle_timeout,
    }

Example 40

Project: overloading.py
Source File: test_overloading.py
View license
def test_errors():

    # Invalid signature
    with pytest.raises(OverloadingError):
        @overloaded
        def f(foo: 1):
            pass

    # Recurring signature
    with pytest.raises(OverloadingError):
        @overloaded
        def f(foo):
            pass
        @overloads(f)
        def f(foox):
            pass

    # Recurring signature
    with pytest.raises(OverloadingError):
        @overloaded
        def f(foo:int, bar, baz=None):
            pass
        @overloads(f)
        def f(foo:int, bar):
            pass

    # Recurring signature based on names
    with pytest.raises(OverloadingError):
        @overloaded
        def f(foo:int, bar:str):
            pass
        @overloads(f)
        def f(bar:str, foo:int):
            pass

    # Recurring signature: ambiguous for f(1, foo='a', bar=2)
    with pytest.raises(OverloadingError):
        @overloaded
        def f(x:int, foo:str, bar:int):
            pass
        @overloads(f)
        def f(y:int, bar:int, foo:str):
            pass

    # Recurring signature with `*args`
    with pytest.raises(OverloadingError):
        @overloaded
        def f(foo, *args):
            pass
        @overloads(f)
        def f(foo, bar=None, *args):
            pass

    # `overloads` without `overloaded`
    with pytest.raises(OverloadingError):
        def f(*args):
            pass
        @overloads(f)
        def f(foo):
            pass

    # Invalid object
    with pytest.raises(OverloadingError):
        @overloaded
        class Foo:
            pass
    with pytest.raises(OverloadingError):
        @overloaded
        def f(*args):
            pass
        @overloads(f)
        class Foo:
            pass

Example 41

Project: botogram
Source File: test_api.py
View license
def test_unavailable_chats(api, mock_req):
    # A bunch of mocked requests for the API
    mock_req({
        "sendMessage": {"ok": True, "result": {}},
        "forwardMessage": {
            "ok": False, "error_code": 123,
            "description": "This is a message!",
        },
        "sendPhoto": {
            "ok": False, "error_code": 403,
            "description": "This is not the message you want!",
        },
        "sendAudio": {
            "ok": False, "error_code": 123,
            "description": "Bot was blocked by the user",
        },
        "sendDocument": {
            "ok": False, "error_code": 403,
            "description": "Bot was blocked by the user",
        },
        "sendSticker": {
            "ok": False, "error_code": 400,
            "description": "Bad request: chat not found",
        },
        "sendVideo": {
            "ok": False, "error_code": 403,
            "description": "Forbidden: bot was kicked from the group chat",
        },
        "sendLocation": {
            "ok": False, "error_code": 400,
            "description": "Bad request: PEER_ID_INVALID",
        },
        "sendVoice": {
            "ok": False, "error_code": 403,
            "description": "Forbidden: user is deleted",
        },
        "sendChatAction": {
            "ok": False, "error_code": 400,
            "description":
                "Bad Request: group chat is migrated to a supergroup chat",
        },
        "getMe": {
            "ok": False, "error_code": 403,
            "description": "Bot was blocked by the user",
        },
    })

    # Test a successiful request
    api.call("sendMessage", {"chat_id": 123})

    # Test a failed request with wrong error code and description
    with pytest.raises(botogram.api.APIError) as e:
        api.call("forwardMessage", {"chat_id": 123})
    assert e.type != botogram.api.ChatUnavailableError

    # Test a failed request with matching error code and wrong description
    with pytest.raises(botogram.api.APIError) as e:
        api.call("sendPhoto", {"chat_id": 123})
    assert e.type != botogram.api.ChatUnavailableError

    # Test a failed request with wrong error code and matching description
    with pytest.raises(botogram.api.APIError) as e:
        api.call("sendAudio", {"chat_id": 123})
    assert e.type != botogram.api.ChatUnavailableError

    # Test a failed request with matching error code and description for
    # blocked users
    with pytest.raises(botogram.api.ChatUnavailableError) as e:
        api.call("sendDocument", {"chat_id": 123})
    assert e.value.chat_id == 123
    assert e.value.reason == "blocked"

    # Test a failed request with matching error code and description for chats
    # not found
    with pytest.raises(botogram.api.ChatUnavailableError) as e:
        api.call("sendSticker", {"chat_id": 123})
    assert e.value.chat_id == 123
    assert e.value.reason == "not_found"

    # Test a failed request with matching error code and description for a bot
    # kicked from the group
    with pytest.raises(botogram.api.ChatUnavailableError) as e:
        api.call("sendVideo", {"chat_id": 123})
    assert e.value.chat_id == 123
    assert e.value.reason == "kicked"

    # Test a failed request with matching error code and description, and in
    # which Telegram failed to determine the reason why the user can't be
    # contacted
    with pytest.raises(botogram.api.ChatUnavailableError) as e:
        api.call("sendLocation", {"chat_id": 123})
    assert e.value.chat_id == 123
    assert e.value.reason == "not_found"

    # Test a failed request with matching error code and description to an user
    # which deleted its account
    with pytest.raises(botogram.api.ChatUnavailableError) as e:
        api.call("sendVoice", {"chat_id": 123})
    assert e.value.chat_id == 123
    assert e.value.reason == "account_deleted"

    # Test a failed request with right error code and descriptio to the wrong
    # method (not a method which sends things to users)
    with pytest.raises(botogram.api.APIError) as e:
        api.call("getMe", {"chat_id": 123})
    assert e.type != botogram.api.ChatUnavailableError

Example 42

Project: picoCTF-web
Source File: user_test.py
View license
    @ensure_empty_collections("users", "teams")
    @clear_collections("users", "teams")
    def test_create_simple_user_request_existing_team(self):
        """
        Tests the registration of users on existing teams.

        Covers:
            partially: user.create_simple_user_request
            team.get_team_uids
            team.create_team
        """

        team = base_team.copy()
        tid = api.team.create_team(team)
        assert tid, "Team was not created."

        # create a new user and join and existing team
        uid = api.user.create_simple_user_request(base_user.copy())
        assert uid == api.user.get_user(name=base_user["username"])["uid"], "Good user created unsuccessfully."

        assert api.team.join_team(team["team_name"],team["password"],uid), "User unable to joining an existing team"

        with pytest.raises(InternalException):
            api.team.join_team(team["team_name"],team["password"],uid)
            assert False, "Was able to register and join the team twice."

        # attempt to join a non existent team
        with pytest.raises(InternalException):
            invalid_team_user = base_user.copy()
            invalid_team_user["username"] = "asdf"
            invalid_uid = api.user.create_simple_user_request(invalid_team_user)
            api.team.join_team("Totally Invalid",team["password"],uid) 
            assert False, "Was able to join a team that doesn't exist."

        # attempt to join an existing team with an invalid password
        with pytest.raises(WebException):
            invalid_team_user = base_user.copy()
            invalid_team_user["username"] = "asdf"
            invalid_uid  = api.user.create_simple_user_request(invalid_team_user)
            api.team.join_team(team["team_name"],"bad-password",uid) 
            assert False, "Was able to join a team with an invalid password."

        team_uids = api.team.get_team_uids(tid)

        assert len(team_uids) == 1, "Invalid teams were created though the tests passed."
        assert uid in team_uids, "User was not successfully placed into the existing team."

Example 43

Project: schematics
Source File: test_datastructures.py
View license
def test_context():

    class FooContext(Context):
        _fields = ('x', 'y', 'z')

    assert bool(FooContext()) is True

    c = FooContext(x=1, y=2)
    assert c.__dict__ == dict(x=1, y=2)

    with pytest.raises(ValueError):
        FooContext(a=1)

    with pytest.raises(Exception):
        c.x = 0

    c.z = 3
    assert c.__dict__ == dict(x=1, y=2, z=3)

    c = FooContext._new(1, 2, 3)
    assert c.__dict__ == dict(x=1, y=2, z=3)

    with pytest.raises(TypeError):
        FooContext._new(1, 2, 3, 4)

    d = c._branch()
    assert d is c

    d = c._branch(x=None)
    assert d is c

    d = c._branch(x=0)
    assert d is not c
    assert d.__dict__ == dict(x=0, y=2, z=3)

    e = d._branch(x=0)
    assert e is d

    c = FooContext(x=1, y=2)
    c._setdefaults(dict(x=9, z=9))
    assert c.__dict__ == dict(x=1, y=2, z=9)

    c = FooContext(x=1, y=2)
    c._setdefaults(FooContext(x=9, z=9))
    assert c.__dict__ == dict(x=1, y=2, z=9)

Example 44

Project: Uranium
Source File: TestDecorators.py
View license
def test_interface():
    def declare_interface():
        @interface
        class TestInterface:
            def test(self):
                pass

            def test2(self):
                pass

        return TestInterface

    cls = declare_interface()
    assert cls is not None

    def declare_subclass(cls):
        class TestSubclass(cls):
            def __init__(self):
                super().__init__()

            def test(self):
                print("test")

            def test2(self):
                print("test2")

        return TestSubclass

    cls = declare_subclass(cls)
    assert cls is not None

    sub = cls()
    assert sub is not None

    def declare_bad_interface():
        @interface
        class TestBadInterface:
            def test(self):
                raise NotImplementedError()

            test_property = "Test"

        return TestBadInterface

    with pytest.raises(TypeError):
        declare_bad_interface()

    def declare_bad_subclass():
        @interface
        class TestInterface:
            def test(self):
                pass

        class TestSubclass(TestInterface):
            pass

        return TestSubclass()

    with pytest.raises(NotImplementedError):
        declare_bad_subclass()

    def declare_good_signature():
        @interface
        class TestInterface:
            def test(self, one, two, three = None):
                pass

        class TestSubclass(TestInterface):
            def test(self, one, two, three = None):
                pass

        return TestSubclass()

    sub = declare_good_signature()
    assert sub is not None

    def declare_bad_signature():
        @interface
        class TestInterface:
            def test(self, one, two, three = None):
                pass

        class TestSubclass(TestInterface):
            def test(self, one):
                pass

        return TestSubclass()

    with pytest.raises(NotImplementedError):
        declare_bad_signature()

Example 45

Project: raiden
Source File: test_netting_channel.py
View license
def test_update_direct_transfer(settle_timeout, tester_state, tester_channels, tester_events):
    privatekey0_raw, privatekey1_raw, nettingchannel, channel0, channel1 = tester_channels[0]
    privatekey0 = PrivateKey(privatekey0_raw, ctx=GLOBAL_CTX, raw=True)
    privatekey1 = PrivateKey(privatekey1_raw, ctx=GLOBAL_CTX, raw=True)
    address0 = privatekey_to_address(privatekey0_raw)
    address1 = privatekey_to_address(privatekey1_raw)

    transfer_amount = 3
    first_direct_transfer0 = channel0.create_directtransfer(
        transfer_amount,
        1  # TODO: fill in identifier
    )
    first_direct_transfer0.sign(privatekey0, address0)
    first_direct_transfer0_data = str(first_direct_transfer0.packed().data)

    channel0.register_transfer(first_direct_transfer0)
    channel1.register_transfer(first_direct_transfer0)

    transfer_amount = 5
    second_direct_transfer0 = channel0.create_directtransfer(
        transfer_amount,
        1  # TODO: fill in identifier
    )
    second_direct_transfer0.sign(privatekey0, address0)
    second_direct_transfer0_data = str(second_direct_transfer0.packed().data)

    channel0.register_transfer(second_direct_transfer0)
    channel1.register_transfer(second_direct_transfer0)

    transfer_amount = 7
    third_direct_transfer0 = channel0.create_directtransfer(
        transfer_amount,
        1  # TODO: fill in identifier
    )
    third_direct_transfer0.sign(privatekey0, address0)
    third_direct_transfer0_data = str(third_direct_transfer0.packed().data)

    channel0.register_transfer(third_direct_transfer0)
    channel1.register_transfer(third_direct_transfer0)

    transfer_amount = 11
    fourth_direct_transfer0 = channel0.create_directtransfer(
        transfer_amount,
        1  # TODO: fill in identifier
    )
    fourth_direct_transfer0.sign(privatekey0, address0)
    fourth_direct_transfer0_data = str(fourth_direct_transfer0.packed().data)

    channel0.register_transfer(fourth_direct_transfer0)
    channel1.register_transfer(fourth_direct_transfer0)

    transfer_amount = 13
    direct_transfer1 = channel1.create_directtransfer(
        transfer_amount,
        1  # TODO: fill in identifier
    )
    direct_transfer1.sign(privatekey1, address1)
    direct_transfer1_data = str(direct_transfer1.packed().data)

    channel0.register_transfer(direct_transfer1)
    channel1.register_transfer(direct_transfer1)

    # not yet closed
    with pytest.raises(TransactionFailed):
        nettingchannel.updateTransfer(
            second_direct_transfer0_data,
            sender=privatekey0_raw,
        )

    nettingchannel.close(
        second_direct_transfer0_data,
        direct_transfer1_data,
        sender=privatekey0_raw,
    )

    # who closes the channel cannot call updateTransfer
    with pytest.raises(TransactionFailed):
        nettingchannel.updateTransfer(
            third_direct_transfer0_data,
            sender=privatekey0_raw,
        )

    # nonce too low
    with pytest.raises(TransactionFailed):
        nettingchannel.updateTransfer(
            first_direct_transfer0_data,
            sender=privatekey1_raw,
        )

    nettingchannel.updateTransfer(
        third_direct_transfer0_data,
        sender=privatekey1_raw,
    )

    tester_state.mine(number_of_blocks=settle_timeout + 1)

    # settle time passed
    with pytest.raises(TransactionFailed):
        nettingchannel.updateTransfer(
            fourth_direct_transfer0_data,
            sender=privatekey1_raw,
        )

Example 46

Project: audiolazy
Source File: test_core.py
View license
  @p("is_delitem", [True, False])
  def test_delitem_delattr(self, is_delitem):
    sd = StrategyDict()
    sd.strategy("sum")(lambda *args: reduce(operator.add, args))
    sd.strategy("prod")(lambda *args: reduce(operator.mul, args))

    # They work...
    assert sd.sum(7, 2, 3) == 12 == sd(7, 2, 3) == sd.default(7, 2, 3)
    assert sd.prod(7, 2, 3) == 42
    assert sd["sum"](2, 3) == 5 == sd(2, 3) == sd.default(2, 3)
    assert sd["prod"](2, 3) == 6
    with pytest.raises(KeyError): # Default isn't an item
      sd["default"](5, 4)

    # Their names are there
    assert set(sd.keys()) == {("sum",), ("prod",)}
    assert "sum" in dir(sd)
    assert "prod" in dir(sd)
    assert "sum" in vars(sd)
    assert "prod" in vars(sd)
    assert "default" in dir(sd)
    assert "default" in vars(sd)

    # Not anymore!
    if is_delitem:
      del sd["sum"]
    else:
      del sd.sum
    assert "sum" not in dir(sd)
    assert "sum" not in vars(sd)
    assert "default" in dir(sd)
    assert "default" not in vars(sd)
    with pytest.raises(AttributeError):
      sd.sum(-1, 2, 3)
    with pytest.raises(KeyError):
      sd["sum"](5, 4)
    with pytest.raises(KeyError): # About this one, nothing changed
      sd["default"](5, 4)

    # But prod is still there
    assert list(sd.keys()) == [("prod",)]
    assert len(sd) == 1
    assert "prod" in dir(sd)
    assert "prod" in vars(sd)
    assert sd.prod(-1, 2, 3) == -6
    assert sd["prod"](5, 4) == 20

    # And now there's no default strategy
    assert sd(3, 2) == NotImplemented == sd.default(3, 2)

Example 47

Project: datasciencebox
Source File: test_conda.py
View license
@utils.remotetest
def test_conda_install():
    env = 'test_conda_install'
    project = utils.get_test_project()
    home_dir = '/home/%s' % project.settings['USERNAME']
    out = project.salt('cmd.run', args=['"rm -rf {}/anaconda/envs/{}"'.format(home_dir, env)])

    out = project.salt('conda.create', args=[env])

    kwargs = {'env': env, '--out': 'json', '--out-indent': '-1'}
    out = project.salt('conda.list', kwargs=kwargs)
    with pytest.raises(AssertionError):
        check_pkg(out, 'numpy')
    with pytest.raises(AssertionError):
        check_pkg(out, 'scipy')
    with pytest.raises(AssertionError):
        check_pkg(out, 'pandas')

    out = project.salt('conda.install', args=['numpy==1.7.1'], kwargs={'env': env})
    out = project.salt('conda.list', kwargs=kwargs)
    check_pkg(out, 'numpy', version='1.7.1')
    with pytest.raises(AssertionError):
        check_pkg(out, 'scipy')
    with pytest.raises(AssertionError):
        check_pkg(out, 'pandas')

    out = project.salt('conda.install', args=['scipy'], kwargs={'env': env}, target='head')
    out = project.salt('conda.list', kwargs=kwargs)
    check_pkg(out, 'numpy')
    check_pkg(out, 'scipy', minion='head')
    with pytest.raises(AssertionError):
        check_pkg(out, 'scipy', minion='compute-1')
    with pytest.raises(AssertionError):
        check_pkg(out, 'pandas')

    out = project.salt('conda.install', args=['scipy'], kwargs={'env': env})
    out = project.salt('conda.list', kwargs=kwargs)
    check_pkg(out, 'numpy')
    check_pkg(out, 'scipy', minion='head')
    check_pkg(out, 'scipy', minion='compute-1')
    with pytest.raises(AssertionError):
        check_pkg(out, 'pandas')

    out = project.salt('conda.install', args=['pandas'], kwargs=kwargs, target='*')
    out = project.salt('conda.list', kwargs=kwargs)
    check_pkg(out, 'numpy')
    check_pkg(out, 'scipy')
    check_pkg(out, 'pandas')

Example 48

Project: umongo
Source File: test_data_proxy.py
View license
    def test_partial(self):

        class MySchema(EmbeddedSchema):
            with_default = fields.StrField(default='default_value')
            with_missing = fields.StrField(missing='missing_value')
            normal = fields.StrField()
            loaded = fields.StrField()
            loaded_but_empty = fields.StrField()
            normal_with_attribute = fields.StrField(attribute='in_mongo_field')

        MyDataProxy = data_proxy_factory('My', MySchema())
        d = MyDataProxy()
        d.from_mongo({'loaded': "foo", 'loaded_but_empty': missing}, partial=True)
        assert d.partial is True
        for field in ('with_default', 'with_missing', 'normal'):
            with pytest.raises(exceptions.FieldNotLoadedError):
                d.get(field)
            with pytest.raises(exceptions.FieldNotLoadedError):
                d.set(field, "test")
            with pytest.raises(exceptions.FieldNotLoadedError):
                d.delete(field)
        assert d.get('loaded') == "foo"
        assert d.get('loaded_but_empty') is missing
        d.set('loaded_but_empty', "bar")
        assert d.get('loaded_but_empty') == "bar"
        d.delete('loaded')
        # Can still access the deleted field
        assert d.get('loaded') is missing

        # Same test, but using `load`
        d = MyDataProxy()
        d.load({'loaded': "foo", 'loaded_but_empty': missing}, partial=True)
        assert d.partial is True
        for field in ('with_default', 'with_missing', 'normal'):
            with pytest.raises(exceptions.FieldNotLoadedError):
                d.get(field)
            with pytest.raises(exceptions.FieldNotLoadedError):
                d.set(field, "test")
            with pytest.raises(exceptions.FieldNotLoadedError):
                d.delete(field)
        assert d.get('loaded') == "foo"
        assert d.get('loaded_but_empty') is missing
        d.set('loaded_but_empty', "bar")
        assert d.get('loaded_but_empty') == "bar"
        d.delete('loaded')
        # Can still access the deleted field
        assert d.get('loaded') is missing

        # Not partial
        d = MyDataProxy()
        d.from_mongo({'loaded': "foo", 'loaded_but_empty': missing})
        assert d.partial is False
        assert d.get('with_default') == 'default_value'
        assert d.get('with_missing') == 'missing_value'
        assert d.get('normal') is missing
        assert d.get('loaded') == "foo"
        assert d.get('loaded_but_empty') == missing
        # Same test with load
        d = MyDataProxy()
        d.load({'loaded': "foo", 'loaded_but_empty': missing})
        assert d.partial is False
        assert d.partial is False
        assert d.get('with_default') == 'default_value'
        assert d.get('with_missing') == 'missing_value'
        assert d.get('normal') is missing
        assert d.get('loaded') == "foo"
        assert d.get('loaded_but_empty') == missing

        # Partial, then not partial
        d = MyDataProxy()
        d.from_mongo({'loaded': "foo", 'loaded_but_empty': missing}, partial=True)
        assert d.partial is True
        d.from_mongo({'loaded': "foo", 'loaded_but_empty': missing})
        assert d.partial is False
        # Same test with load
        d = MyDataProxy()
        d.load({'loaded': "foo", 'loaded_but_empty': missing}, partial=True)
        assert d.partial is True
        d.load({'loaded': "foo", 'loaded_but_empty': missing})
        assert d.partial is False

        # Partial, then update turns it into not partial
        d = MyDataProxy()
        d.from_mongo({'loaded': "foo", 'loaded_but_empty': missing}, partial=True)
        assert len(d.not_loaded_fields) == 4
        d.update({'with_default': 'test', 'with_missing': 'test', 'normal_with_attribute': 'foo'})
        assert len(d.not_loaded_fields) == 1
        assert d.partial is True
        d.update({'normal': 'test'})
        assert d.partial is False
        assert not d.not_loaded_fields

Example 49

Project: bayeslite
Source File: test_read_csv.py
View license
def test_read_csv():
    with bayeslite.bayesdb_open(builtin_metamodels=False) as bdb:

        f = StringIO.StringIO(csv_data)
        with pytest.raises(ValueError):
            # Table must already exist for create=False.
            bayeslite.bayesdb_read_csv(bdb, 't', f, header=False, create=False,
                ifnotexists=False)

        f = StringIO.StringIO(csv_data)
        with pytest.raises(ValueError):
            # Must pass create=True for ifnotexists=True.
            bayeslite.bayesdb_read_csv(bdb, 't', f, header=False, create=False,
                ifnotexists=True)

        f = StringIO.StringIO(csv_data)
        with pytest.raises(ValueError):
            # Must pass create=False for header=False.
            bayeslite.bayesdb_read_csv(bdb, 't', f, header=False, create=True,
                ifnotexists=False)

        f = StringIO.StringIO(csv_data)
        with pytest.raises(ValueError):
            # Must pass create=False for header=False.
            bayeslite.bayesdb_read_csv(bdb, 't', f, header=False, create=True,
                ifnotexists=True)

        f = StringIO.StringIO(csv_hdrdata)
        with pytest.raises(ValueError):
            # Table must already exist for create=False.
            bayeslite.bayesdb_read_csv(bdb, 't', f, header=True, create=False,
                ifnotexists=False)

        f = StringIO.StringIO(csv_hdrdata)
        with pytest.raises(ValueError):
            # Must pass create=True for ifnotexists=True.
            bayeslite.bayesdb_read_csv(bdb, 't', f, header=True, create=False,
                ifnotexists=True)

        f = StringIO.StringIO(csv_hdrdata)
        with pytest.raises(ValueError):
            with bdb.savepoint():
                # Table must not exist if ifnotexists=False.
                bdb.sql_execute('CREATE TABLE t(x)')
                bayeslite.bayesdb_read_csv(bdb, 't', f, header=True,
                    create=True, ifnotexists=False)
        with pytest.raises(IOError):
            # Table must have no empty values in header.
            csv_hdrdata_prime = csv_hdrdata[1:]
            f = StringIO.StringIO(csv_hdrdata_prime)
            with bdb.savepoint():
                bayeslite.bayesdb_read_csv(bdb, 't', f, header=True,
                    create=True, ifnotexists=False)

        f = StringIO.StringIO(csv_hdrdata)
        bayeslite.bayesdb_read_csv(bdb, 't', f, header=True, create=True,
            ifnotexists=False)
        data = bdb.sql_execute('SELECT * FROM t').fetchall()
        assert data == [
            # XXX Would be nice if the NaN could actually be that, or
            # at least None/NULL.
            (1,2,3,'foo','bar',u'nan',u'',u'quagga'),
            (4,5,6,'baz','quux',42.0,u'',u'eland'),
            (7,8,6,'zot','mumble',87.0,u'zoot',u'caribou'),
        ]

        f = StringIO.StringIO(csv_hdr)
        bayeslite.bayesdb_read_csv(bdb, 't', f, header=True, create=True,
            ifnotexists=True)
        assert bdb.sql_execute('SELECT * FROM t').fetchall() == data
        assert cursor_value(bdb.sql_execute('SELECT sql FROM sqlite_master'
                    ' WHERE name = ?', ('t',))) == \
            'CREATE TABLE "t"' \
            '("a" NUMERIC,"b" NUMERIC,"c" NUMERIC,"name" NUMERIC,' \
            '"nick" NUMERIC,"age" NUMERIC,"muppet" NUMERIC,"animal" NUMERIC)'

        f = StringIO.StringIO(csv_data)
        bayeslite.bayesdb_read_csv(bdb, 't', f, header=False, create=False,
            ifnotexists=False)
        assert bdb.sql_execute('SELECT * FROM t').fetchall() == data + data

        f = StringIO.StringIO(csv_hdrdata)
        bayeslite.bayesdb_read_csv(bdb, 't', f, header=True, create=False,
            ifnotexists=False)
        assert bdb.sql_execute('SELECT * FROM t').fetchall() == \
            data + data + data
        with tempfile.NamedTemporaryFile(prefix='bayeslite') as temp:
            with open(temp.name, 'w') as f:
                f.write(csv_hdrdata)
            bayeslite.bayesdb_read_csv_file(bdb, 't', temp.name, header=True,
                create=False, ifnotexists=False)
        assert bdb.sql_execute('SELECT * FROM t').fetchall() == \
            data + data + data + data

        # Test the BQL CREATE TABLE FROM <csv-file> syntax.
        f = StringIO.StringIO(csv_hdrdata)
        with tempfile.NamedTemporaryFile(prefix='bayeslite') as temp:
            with open(temp.name, 'w') as f:
                f.write(csv_hdrdata)
            bdb.execute('CREATE TABLE t2 FROM \'%s\'' % (temp.name,))
            assert bdb.sql_execute('SELECT * FROM t2').fetchall() == data

        # Trying to read a csv with an empty column name should fail.
        csv_header_corrupt = csv_hdr.replace('a,b',',')
        csv_hdrdata_corrupt = csv_header_corrupt + csv_data
        with tempfile.NamedTemporaryFile(prefix='bayeslite') as temp:
            with open(temp.name, 'w') as f:
                f.write(csv_hdrdata_corrupt)
            with pytest.raises(IOError):
                bayeslite.bayesdb_read_csv_file(
                    bdb, 't3', temp.name, header=True, create=True)

Example 50

Project: mongokat
Source File: test_api.py
View license
def test_document_common_methods(Sample):

  from bson import ObjectId
  import collections

  assert Sample.collection.find().count() == 0

  # Instanciate
  new_object = Sample({"name": "XXX", "url": "http://example.com"})

  # Should not save to DB yet.
  assert Sample.collection.find().count() == 0

  # Now save()
  new_object.save()

  # Once the object is in DB, we can't do it anymore.
  with pytest.raises(Exception):
    new_object.save()

  assert type(new_object["_id"]) == ObjectId

  assert Sample.collection.find().count() == 1
  db_object = Sample.collection.find_one()
  assert type(db_object) == dict
  assert db_object["name"] == "XXX"

  # test insert()
  inserted_object = Sample.insert({"name": "ZZZ", "url": "http://example2.com", "stats": {"nb_of_products": 2}})
  assert type(inserted_object) == ObjectId

  assert Sample.collection.find().count() == 2

  # Find back with different methods
  orm_object = Sample.find_by_id(db_object["_id"])
  assert orm_object["name"] == "XXX"
  orm_object = Sample.find_by_id(str(db_object["_id"]))
  assert orm_object["name"] == "XXX"
  orm_object = Sample.find_by_id({"_id": db_object["_id"]})
  assert orm_object["name"] == "XXX"
  orm_object = Sample.find_by_id({"_id": str(db_object["_id"])})
  assert orm_object["name"] == "XXX"
  assert isinstance(orm_object, sample_models.SampleDocument)

  # exists()
  assert Sample.exists({"name": "XXX"})

  # Other find styles
  cursor = Sample.find({"name": "XXX"})
  assert "cursor" in str(type(cursor)).lower()
  orm_objects = list(cursor)
  assert len(orm_objects) == 1
  assert isinstance(orm_objects[0], sample_models.SampleDocument)
  assert orm_objects[0]["name"] == "XXX"

  orm_object = Sample.find_one({"_id": db_object["_id"]})
  assert orm_object["name"] == "XXX"
  assert isinstance(orm_object, sample_models.SampleDocument)

  # TODO - should that not work?
  orm_object = Sample.find_one({"_id": str(db_object["_id"])})
  assert orm_object is None

  col_cursor = Sample.iter_column({"name": "XXX"})
  assert isinstance(col_cursor, collections.Iterable)
  assert list(col_cursor) == [new_object["_id"]]

  col = Sample.list_column({"name": "XXX"}, field="name")
  assert col == ["XXX"]
  col = Sample.list_column({"name": "ZZZ"}, field="stats.nb_of_products")
  assert col == [2]

  with pytest.raises(KeyError):
    Sample.list_column({"name": "ZZZ"}, field="inexistent_field")

  # We should be able to fetch & save partial objects.
  orm_object = Sample.find_by_id(db_object["_id"], fields=["url"])
  assert list(dict(orm_object).keys()) == ["url"]
  assert dict(orm_object)["url"] == "http://example.com"

  # If we save() that, it will create a new object because we lack an _id :(
  with pytest.raises(Exception):
    orm_object.save()

  assert Sample.collection.find().count() == 2

  # FIXME not anymore as we are requesting _id for each query
  # orm_object.save(force=True)

  # assert Sample.collection.find().count() == 3

  orm_object = Sample.find_by_id(db_object["_id"], fields=["url", "_id"])
  assert dict(orm_object) == {"url": "http://example.com", "_id": db_object["_id"]}

  # Change the data a bit and save.
  # This would remove "name" from the doc.
  orm_object["url"] = "http://other.example.com"

  # Not authorized!
  with pytest.raises(Exception):
    orm_object.save()

  assert Sample.collection.find().count() == 2
  db_object = Sample.collection.find_one({"_id": db_object["_id"]})
  assert "name" in db_object

  orm_object.save(force=True)

  # Should not add anything new
  assert Sample.collection.find().count() == 2

  db_object = Sample.collection.find_one({"_id": db_object["_id"]})
  assert "name" not in db_object
  assert db_object["url"] == "http://other.example.com"

  orm_object = Sample.find_by_id(db_object["_id"], fields=["_id"])
  orm_object["name"] = "YYY"

  # This one should not overwrite unset fields.
  orm_object.save_partial()

  db_object = Sample.collection.find_one({"_id": db_object["_id"]})
  assert db_object["name"] == "YYY"
  assert db_object["url"] == "http://other.example.com"

  # Test the reload() method by changing the data from somewhere else
  Sample.collection.update({"_id": db_object["_id"]}, {"$set": {"name": "AAA"}})

  assert orm_object["name"] == "YYY"

  orm_object.reload()

  assert orm_object["name"] == "AAA"

  # Test .update() - local dict update()
  orm_object.update({"name": "BBB"})

  assert orm_object["name"] == "BBB"

  # Should not have changed the DB
  db_object = Sample.collection.find_one({"_id": db_object["_id"]})
  assert db_object["name"] == "AAA"