Esempio n. 1
0
class TestConcentration:
    @pytest.mark.randomize(impurities=list_of(float, items=100),
                           matrix=list_of(float, items=100))
    def test_calculate(self, impurities, matrix):
        ia = random.random()
        rsf = random.uniform(1e15, 1e25)
        assert concentration.calculate(impurities, ia, matrix, rsf) == [
            i / ia / 100 / m * rsf for i, m in zip(impurities, matrix)
        ]

    @pytest.mark.randomize(
        impurities=list_of(float, items=random.randint(1, 100)),
        matrix=list_of(float, items=random.randint(101, 200)),
    )
    def test_list_len(self, impurities, matrix):
        ia = random.random()
        rsf = random.uniform(1e15, 1e25)
        with pytest.raises(AssertionError):
            concentration.calculate(impurities, ia, matrix, rsf)
Esempio n. 2
0
class TestPSubstrings(object):
    def test_triv(self):
        assert (list(psubstrings('abc', 'abc', 3, 20)) == [('abc', 'abc')])

    def test_null(self):
        assert (list(psubstrings('abc', 'abc', 4, 20)) == [])
        assert (list(psubstrings('abc', 'abcd', 4, 20)) == [])

    def test_equal(self):
        assert (set(list(psubstrings('abcd', 'abcd', 3, 20))) ==
                set([('abcd', 'abcd'), ('abc', 'abc'), ('bcd', 'bcd')]))
        assert (set(list(psubstrings('abcde', 'abcde', 3, 20))) ==
                set([('abcde', 'abcde'), ('abcd', 'abcd'), ('abc', 'abc'),
                     ('bcd', 'bcd'), ('bcde', 'bcde'), ('cde', 'cde')]))

    def test_inequal(self):
        assert (set(list(psubstrings('abc', 'abcd', 3, 20))) ==
                set([('abc', 'abc'), ('abc', 'bcd')]))
        assert (set(list(psubstrings('abcd', 'abcde', 3, 20))) ==
                set([('abcd', 'abcd'), ('abc', 'abc'), ('bcd', 'bcd'),
                     ('abcd', 'bcde'), ('abc', 'bcd'), ('bcd', 'cde')]))
        assert (set(list(psubstrings('abcd', 'abcdef', 3, 20))) ==
                set([('abcd', 'abcd'), ('abc', 'abc'), ('bcd', 'bcd'),
                     ('abcd', 'bcde'), ('abc', 'bcd'), ('bcd', 'cde'),
                     ('abcd', 'cdef'), ('abc', 'cde'), ('bcd', 'def')]))

    def test_reverse(self):
        assert (set(list(psubstrings('abcde', 'abcd', 3, 20))) ==
                set([(b, a) for a, b in psubstrings('abcd', 'abcde', 3, 20)]))

    @pytest.mark.randomize(l1=list_of(int, min_items=10, max_items=100),
                           l2=list_of(int, min_items=10, max_items=100),
                           choices=[0,1])
    def test_length(self, l1, l2):
        for a, b in psubstrings(l1, l2, 3, 40):
            assert (3 <= len(a) <= 40)
            assert (3 <= len(b) <= 40)
Esempio n. 3
0
def test_encode_keys_random(delimiter, highest_character, key_prefix: list_of(str)):
    kp = tuple(k.replace(delimiter, "").replace(highest_character, "").encode("ascii") for k in key_prefix)
    d = delimiter.encode("ascii")
    h = highest_character.encode("ascii")
    keys = _encode_keys(d, h, kp)
    assert set(keys) == {"key_from", "key_to"}
    assert isinstance(keys, dict)
    if len(key_prefix) == 0:
        for name in ["key_from", "key_to"]:
            assert keys[name] == None
    else:
        assert keys["key_to"].endswith(h)
        for name in ["key_from", "key_to"]:
            assert keys[name].count(d) == len(key_prefix) - 1

        assert len(keys["key_from"]) + 1 == len(keys["key_to"])
Esempio n. 4
0
def test_encode_keys_random(delimiter, highest_character,
                            key_prefix: list_of(str)):
    kp = tuple(
        k.replace(delimiter, '').replace(highest_character, '').encode('ascii')
        for k in key_prefix)
    d = delimiter.encode('ascii')
    h = highest_character.encode('ascii')
    keys = _encode_keys(d, h, kp)
    assert set(keys) == {'key_from', 'key_to'}
    assert isinstance(keys, dict)
    if len(key_prefix) == 0:
        for name in ['key_from', 'key_to']:
            assert keys[name] == None
    else:
        assert keys['key_to'].endswith(h)
        for name in ['key_from', 'key_to']:
            assert keys[name].count(d) == len(key_prefix) - 1

        assert len(keys['key_from']) + 1 == len(keys['key_to'])
Esempio n. 5
0
"""
Test suite for the `mini_aes` module.
"""

import pytest
from pytest import list_of

import mini_aes

@pytest.mark.randomize(
    ns=list_of(int),
    min_num=0,
    max_num=15
)
def test_nibble_sub(ns):
    # Ensure that any list of nibbles, when passed through `nibble_sub` and
    # `inv_nibble_sub`, returns the original list.
    assert ns == mini_aes.inv_nibble_sub(mini_aes.nibble_sub(ns))

@pytest.mark.randomize(
    n0=int,
    n1=int,
    n2=int,
    n3=int,
    min_num=0,
    max_num=15
)
def test_shift_row(n0, n1, n2, n3):
    # Ensure that `shift_row` interchanges the second and fourth nibble.
    assert mini_aes.shift_row([n0, n1, n2, n3]) == [n0, n3, n2, n1]
Esempio n. 6
0
    assert(allcommonsubstrings(l1, same=True) == [])

def test_single_nonempty():
    l1 = 'abcdeabc'
    expected = [(slice(0, 3, None), slice(5, 8, None)),
                (slice(5, 8, None), slice(0, 3, None))]
    assert(allcommonsubstrings(l1, minlength=3, same=True) == expected)

def test_simple():
    l1 = 'abcde'
    l2 = 'fghijabc'
    m1, m2 = allcommonsubstrings(l1, l2, minlength=3)[0]
    assert(l1[m1] == l2[m2])


@pytest.mark.randomize(l1=list_of(int, min_items=10, max_items=100),
                       l2=list_of(int, min_items=10, max_items=100),
                       choices=[0,1])
def test_length(l1, l2):
    n = 4
    for slice1, slice2 in allcommonsubstrings(l1, l2, minlength=n):
        assert(slice1.stop - slice1.start >= n)
        assert(slice2.stop - slice2.start >= n)


@pytest.mark.randomize(l1=list_of(int, min_items=10, max_items=100),
                       l2=list_of(int, min_items=10, max_items=100),
                       choices=[0,1])
def test_equality(l1, l2):
    for slice1, slice2 in allcommonsubstrings(l1, l2, minlength=4):
        assert(l1[slice1] == l2[slice2])
def test_list_of_illogical_size():
    with pytest.raises(AssertionError):
        list_of(str, min_items=2, max_items=1).generate()
Esempio n. 8
0
# -*- coding: utf-8 -*-
import pytest
from pytest import list_of

# https://pypi.python.org/pypi/pytest-quickcheck


@pytest.mark.randomize(l=list_of(int), ncalls=10)
def test_sorting(l):
    sorted_l = sorted(l)
    assert all(sorted_l[i] <= sorted_l[i + 1]
               for i in range(len(sorted_l) - 1))


@pytest.mark.randomize(xs=list_of(int), ncalls=10)
def test_sorting(xs):
    ys = list(xs)
    ys.reverse()
    ys.reverse()
    assert xs == ys
    def _create(self, items):
        subset = set(items)
        for item in items:
            self._item_to_subset[item] = subset
        self._subsets.append(subset)

    @staticmethod
    def _arbitrary(s):
        """Returns an arbitrary item from set s. Consistently returns
        the same item as long as s remains the same.

        """
        return next(iter(s))

@pytest.mark.randomize(equivalence=nonempty_list_of(int),
                       unrelateds=nonempty_list_of(list_of(int)),
                       min_num=-10, max_num=100)
def test_canonify(equivalence, unrelateds, n_calls=1000):
    e = Equivalence()
    e.disconnect(equivalence)
    canon = e.canonify(equivalence[0])

    equivalence = set(equivalence)
    assert canon in equivalence
    for unrelated in unrelateds:
        unrelated = list(set(unrelated).difference(equivalence))
        e.disconnect(unrelated)
        for item in equivalence:
            assert e.canonify(item) == canon

@pytest.mark.randomize(equivalences=list_of(list_of(int)))
Esempio n. 10
0
import pytest

from src.lib.math import depth

TIME = [0.3 * i for i in range(101)]


@pytest.mark.randomize(time=pytest.list_of(float), speed=float, positive=True)
def test_homostructure(time, speed):
    assert depth._homostructure(time, speed) == [i * speed for i in time]


@pytest.mark.parametrize(
    "speed, indexes, expected",
    [
        ([1.0, 2.0], [3], 59.4000000000001),
        ([1.0, 2.0], [4], 59.100000000000094),
        ([1.0, 2.0, 3.0], [2, 5], 88.50000000000009),
    ],
)
def test_heterostructure(speed, indexes, expected):
    assert depth._heterostructure(TIME, speed, indexes)[-1] == expected


@pytest.mark.parametrize(
    "speed, indexes, expected", [(2.0, None, 60.0), ([1.0, 2.0], [3], 59.4000000000001)]
)
def test_calculate(speed, indexes, expected):
    assert depth.calculate(TIME, speed, indexes)[-1] == expected

Esempio n. 11
0
    assert (sl.index_lt((10, 'e')) == 1)
    assert (sl.index_le((10, 'e')) == 1)
    assert (sl.index_lt((5, 'b')) == 0)

    with pytest.raises(ValueError):
        sl.index((10, 'b'))

    with pytest.raises(ValueError):
        sl.index((3, 'b'))


from pytest import list_of


@pytest.mark.randomize(l=list_of(int), min_num=-10000, max_num=10000)
def test_intlist1(l):
    sl = SortedList(l)
    assert (sorted(l) == sl._v)
    assert (sorted(l) == sl._k)


@pytest.mark.randomize(l=list_of(int, min_items=1),
                       min_num=-10000,
                       max_num=10000)
def test_intlist2(l):
    el = l[:-1]
    e = l[-1]
    sl = SortedList(el)
    assert (sorted(el) == sl._v)
    assert (sorted(el) == sl._k)
Esempio n. 12
0
class TestCiderCore(object):
    @pytest.mark.parametrize("bool_values",
                             ["yes", "no", "y", "n", "true", "false"])
    @pytest.mark.randomize(domain=str,
                           key=str,
                           values=[str, int, float],
                           force=bool)
    def test_set_default(self, tmpdir, debug, verbose, domain, key, values,
                         bool_values, force):
        cider = Cider(False, debug, verbose, cider_dir=str(tmpdir))
        cider.defaults = MagicMock()

        for value in values + map(random_case, bool_values):
            json_value = cider.json_value(value)
            cider.set_default(domain, key, value, force=force)
            cider.defaults.write.assert_called_with(domain, key, json_value,
                                                    force)

            assert cider.read_defaults()[domain][key] == json_value

            # Verify str(value) => defaults.write(value)
            cider.set_default(domain, key, str(value), force=force)
            cider.defaults.write.assert_called_with(
                domain, key, cider.json_value(str(value)), force)

    @pytest.mark.randomize(domain=str, key=str)
    def test_remove_default(self, tmpdir, debug, verbose, domain, key):
        cider = Cider(False, debug, verbose, cider_dir=str(tmpdir))
        cider.defaults = MagicMock()
        cider.remove_default(domain, key)
        cider.defaults.delete.assert_called_with(domain, key)
        assert key not in cider.read_defaults().get(domain, [])

    @pytest.mark.randomize(tap=str)
    def test_tap(self, tmpdir, debug, verbose, tap):
        cider = Cider(False, debug, verbose, cider_dir=str(tmpdir))
        cider.brew = MagicMock()
        cider.tap(tap)
        cider.brew.tap.assert_called_with(tap)
        assert tap in cider.read_bootstrap().get("taps", [])

    @pytest.mark.randomize(tap=str)
    def test_untap(self, tmpdir, debug, verbose, tap):
        cider = Cider(False, debug, verbose, cider_dir=str(tmpdir))
        cider.brew = MagicMock()
        cider.untap(tap)
        cider.brew.untap.assert_called_with(tap)
        assert tap not in cider.read_bootstrap().get("taps", [])

    @pytest.mark.randomize(data=dict_of(str, str))
    def test_read_defaults(self, tmpdir, debug, verbose, data):
        with patch("cider.core.read_config") as mock:
            cider = Cider(False, debug, verbose, cider_dir=str(tmpdir))
            mock.return_value = data

            assert cider.read_defaults() == data
            mock.assert_called_with(cider.defaults_file, {})

    @pytest.mark.randomize(force=bool)
    def test_relink(self, tmpdir, debug, verbose, force):
        """
        Tests that:
        1. Target directories are created.
        2. For each source in glob(key), mklink(src, expandtarget(src, target))
           is called.
        3. Previously-cached targets are removed.
        4. Cache is updated with new targets.
        """
        def generate_symlinks():
            srcdir = tmpdir.join(random_str(min_length=1))

            def symkey(directory, key):
                return str(directory.join(key).relto(srcdir))

            def symvalue(directory, value):
                return str(directory.join(value)) + ("/" if value.endswith("/")
                                                     else "")

            outerdir = srcdir.join(random_str(min_length=1))
            innerdir = outerdir.join(random_str(min_length=1))
            targetdir = tmpdir.join(random_str(min_length=1))

            ext = random_str(min_length=1, max_length=8)
            os.makedirs(str(innerdir))

            for _ in range(random.randint(0, 10)):
                touch(str(innerdir.join("{0}.{1}".format(random_str(), ext))))

            path = str(outerdir.join(random_str(min_length=1)))
            touch(path)

            return {
                symkey(outerdir, "*/*." + ext): symvalue(targetdir, "a/b/c/"),
                symkey(outerdir, "*/*." + ext): symvalue(targetdir, "a/b/c"),
                symkey(outerdir, path): symvalue(targetdir, "a/b/d"),
            }

        cider = Cider(False,
                      debug,
                      verbose,
                      cider_dir=str(tmpdir),
                      support_dir=str(tmpdir.join(".cache")))
        cider.mklink = MagicMock(return_value=True)

        for srcglob, target in generate_symlinks().items():
            invalid = not isdirname(target) and ("*" in srcglob
                                                 or "?" in srcglob)
            old_targets = cider._cached_targets()  # pylint:disable=W0212
            cider.read_bootstrap = MagicMock(
                return_value={"symlinks": {
                    srcglob: target
                }})

            with pytest.raises(SymlinkError) if invalid else empty():
                new_targets = set(cider.relink(force))
                for src in iglob(srcglob):
                    cider.mklink.assert_called_with(
                        src, cider.expandtarget(src, target))

                assert os.path.isdir(os.path.dirname(target))
                for dead_target in set(old_targets) - new_targets:
                    assert not os.path.exists(dead_target)

                new_cache = cider._cached_targets()  # pylint:disable=W0212
                assert new_targets == set(new_cache) & new_targets

    def test_mklink(self, tmpdir, debug, verbose):
        cider = Cider(False,
                      debug,
                      verbose,
                      cider_dir=str(tmpdir),
                      support_dir=str(tmpdir.join(".cache")))
        source = str(tmpdir.join(random_str(min_length=1)))
        target = str(tmpdir.join(random_str(min_length=1)))

        # SymlinkError should be raised if source does not exist.
        with pytest.raises(SymlinkError):
            assert not cider.mklink(source, target)

        # Should succeed for valid source/target.
        touch(source)
        for _ in range(2):
            assert cider.mklink(source, target)
            assert os.path.islink(target)

        # Should fail for existing target.
        os.remove(target)
        touch(target)
        assert not cider.mklink(source, target)
        assert not os.path.islink(target)

        # Should allow removing existing target with --force.
        with patch("cider._osx.move_to_trash", side_effect=os.remove):
            assert cider.mklink(source, target, force=True)

    @pytest.mark.randomize(name=str, min_length=1)
    def test_addlink(self, tmpdir, debug, verbose, name):
        """
        Tests that:
        1. Symlink directory is created & file is moved there.
        2. Symlink is created.
        3. Symlink is added to bootstrap.
        4. Cache is updated with new target.

        Expected errors:
        - StowError is raised if target does not exist.
        - StowError is raised if target already exists.
        """
        cider = Cider(False,
                      debug,
                      verbose,
                      cider_dir=str(tmpdir),
                      support_dir=str(tmpdir.join(".cache")))
        cider.add_symlink = MagicMock()

        source = os.path.abspath(str(tmpdir.join(random_str(min_length=1))))
        basename = os.path.basename(source)

        stow_dir = os.path.abspath(os.path.join(cider.symlink_dir, name))
        stow = os.path.join(stow_dir, basename)

        # StowError should be raised if source does not exist.
        with pytest.raises(StowError):
            cider.addlink(name, source)

        touch(source)
        cider.addlink(name, source)
        assert os.path.isdir(stow_dir)
        assert os.path.isfile(stow)
        assert os.path.islink(source)
        assert os.path.samefile(os.path.realpath(stow),
                                os.path.realpath(source))

        cider.add_symlink.assert_called_with(name, source)
        new_cache = cider._cached_targets()  # pylint:disable=W0212
        assert source in new_cache

        # StowError should be raised if source already exists.
        os.remove(source)
        touch(source)
        with pytest.raises(StowError):
            cider.addlink(source, name)

    @pytest.mark.randomize(name=str, links=nonempty_list_of(str), min_length=1)
    def test_unlink(self, tmpdir, debug, verbose, name, links):
        """
        Tests that:
        1. Each symlink is moved back to its original location.
        2. Symlinks are removed from bootstrap.
        3. Cache is updated with targets removed.
        4. Symlink directory is removed if empty.

        Expected errors:
        - StowError is raised if no symlink was found.
        - SymlinkError is raised if target already exists.
        """
        cider = Cider(False,
                      debug,
                      verbose,
                      cider_dir=str(tmpdir.join("cider")),
                      support_dir=str(tmpdir.join("cider", ".cache")))
        cider.remove_symlink = MagicMock()

        stow_dir = os.path.abspath(os.path.join(cider.symlink_dir, name))
        os.makedirs(stow_dir)
        for link in links:
            source = os.path.join(stow_dir, link)
            target = str(tmpdir.join(link))
            touch(source)
            os.symlink(source, target)
            cider.add_symlink(name, target)

        cider.unlink(name)

        new_cache = cider._cached_targets()  # pylint:disable=W0212
        for link in links:
            source = os.path.join(stow_dir, link)
            target = str(tmpdir.join(link))
            assert os.path.exists(target)
            assert not os.path.islink(target)
            assert not os.path.exists(source)
            assert target not in new_cache

        cider.remove_symlink.assert_called_with(name)
        assert not os.path.exists(stow_dir)

    @pytest.mark.randomize(defaults=dict_of(str, dict_of(str, str)))
    def test_apply_defaults(self, tmpdir, debug, verbose, defaults):
        cider = Cider(False, debug, verbose, cider_dir=str(tmpdir))
        cider.defaults = MagicMock()
        cider.read_defaults = MagicMock(return_value=defaults)
        cider.apply_defaults()

        for domain, options in defaults.items():
            for key, value in options.items():
                cider.defaults.write.assert_any_call(domain, key, value)

    @pytest.mark.randomize(before=bool,
                           after=bool,
                           bootstrap={
                               "before-scripts": list_of(str),
                               "after-scripts": list_of(str)
                           },
                           min_length=1)
    def test_run_scripts(self, tmpdir, debug, verbose, before, after,
                         bootstrap):
        cider = Cider(False, debug, verbose, cider_dir=str(tmpdir))
        cider.read_bootstrap = MagicMock(return_value=bootstrap)
        scripts = []
        scripts += bootstrap.get("before-scripts", []) if before else []
        scripts += bootstrap.get("after-scripts", []) if after else []

        # TODO: Assert ordering
        with patch("cider.core.spawn", autospec=True, return_value=0) as spawn:
            cider.run_scripts(before, after)
            for script in scripts:
                spawn.assert_any_call([script],
                                      shell=True,
                                      debug=debug,
                                      cwd=cider.cider_dir,
                                      env=cider.env)

    @pytest.mark.randomize(installed=list_of(str),
                           brewed=list_of(str),
                           min_length=1)
    def test_missing_taps(self, tmpdir, debug, verbose, installed, brewed):
        cider = Cider(False, debug, verbose, cider_dir=str(tmpdir))
        cider.brew = MagicMock()
        cider.brew.tap = MagicMock(return_value="\n".join(brewed))

        missing = set(brewed) - set(installed)
        assert cider.missing_taps() == sorted(missing)
Esempio n. 13
0
    sl = SortedList(data, key=lambda x: x[1])
    assert(sl._k == ['a', 'b', 'v', 'z'])
    assert(sl._v == [(3, 'a'), (5, 'b'), (4, 'v'), (1, 'z')])

    assert(sl.index_lt((10, 'e')) == 1)
    assert(sl.index_le((10, 'e')) == 1)
    assert(sl.index_lt((5, 'b')) == 0)

    with pytest.raises(ValueError):
        sl.index((10, 'b'))

    with pytest.raises(ValueError):
        sl.index((3, 'b'))

from pytest import list_of
@pytest.mark.randomize(l=list_of(int), min_num=-10000, max_num=10000)
def test_intlist1(l):
    sl = SortedList(l)
    assert(sorted(l) == sl._v)
    assert(sorted(l) == sl._k)

@pytest.mark.randomize(l=list_of(int, min_items=1),
                                 min_num=-10000, max_num=10000)
def test_intlist2(l):
    el = l[:-1]
    e = l[-1]
    sl = SortedList(el)
    assert(sorted(el) == sl._v)
    assert(sorted(el) == sl._k)

    sl.insert(e)
import pytest
from pytest import list_of, nonempty_list_of, dict_of, Generator


@pytest.mark.randomize(l=list_of(int))
def test_list_of(l):
    assert isinstance(l, list)
    assert all(isinstance(i, int) for i in l), l


@pytest.mark.randomize(l=nonempty_list_of(int), ncalls=50)
def test_nonempty_list_of(l):
    assert isinstance(l, list), l
    assert len(l) >= 1


@pytest.mark.randomize(l=list_of(str, min_items=10, max_items=12),
                       fixed_length=5)
def test_list_of_options(l):
    assert isinstance(l, list)
    assert 10 <= len(l) <= 12
    assert all(isinstance(s, str) and len(s) == 5 for s in l), l


@pytest.mark.randomize(l=list_of(str, items=15))
def test_list_of_num_items(l):
    assert len(l) == 15


@pytest.mark.randomize(l=list_of(str, items=15, min_items=1000))
def test_list_of_items_precedes_over_min_items(l):
Esempio n. 15
0
def test_buyCard(x,c):
	g=d.initializeGame(x, [d.adventurer, d.ambassador, d.baron, d.council_room, d.cutpurse,
                            d.embargo, d.feast, d.gardens, d.great_hall,d.mine], 2)
		
	if g.numBuys<1 or g.supplyCount[c]==0 or g.coins<d.getCost(c):
		assert d.buyCard(c, g)==-1
	else:
		assert d.buyCard(c, g)==0

		
		
		

@pytest.mark.parametrize("x",[2,3,4])
@pytest.mark.parametrize("s",[2,3,4,5,6,7,8])
@pytest.mark.randomize(l=list_of(int, items=10),min_num=7, max_num=16)	
def test_initialzeGame(x,l,s):
	g=d.initializeGame(x,l,s)
	if len(l)==len(set(l)):
		assert g==-1


@pytest.mark.parametrize("x",[2,3,4])
@pytest.mark.randomize(s=int,min_num=1, max_num=9)
def test_initialzeGame_2(s,x):
	g=d.initializeGame(x, [d.adventurer, d.ambassador, d.baron, d.council_room, d.cutpurse,
                            d.embargo, d.feast, d.gardens, d.great_hall,d.mine], s)
	assert isinstance(g,d.gameState)
	if x==2:
		supply={d.curse:10,d.estate:8,d.duchy:8,d.province:8,d.copper:46,d.silver:40,d.gold:30,d.adventurer:10,d.ambassador:10,d.baron:10,d.council_room:10, d.cutpurse:10,d.embargo:10, d.feast:10, d.gardens:8, d.great_hall:8, d.mine:10}
		assert supply==g.supplyCount
Esempio n. 16
0
import pytest

from tde.util.functions import unique, intersection, fname2speaker

@pytest.mark.randomize(it=pytest.list_of(str))
def test_unique(it):
    assert (sorted(list(unique(it))) == sorted(list(set(it))))

def test_intersection():
    it1 = range(20)
    it2 = range(10, 30)
    assert (sorted(list(intersection(it1, it2))) ==
            sorted(list(set(it1) & set(it2))))

def test_fname2speaker():
    t = 'buckeye'
    assert (fname2speaker(t)('s2801a_1923810923') == 's28')
    with pytest.raises(NotImplementedError):
        fname2speaker('somethingelse')
Esempio n. 17
0
class TestBrewCore(object):
    @pytest.mark.randomize(formulas=nonempty_list_of(str),
                           force=bool,
                           min_length=1)
    def test_install(self, tmpdir, cask, debug, verbose, formulas, force):
        cider = Cider(cask, debug, verbose, cider_dir=str(tmpdir))
        cider.brew = MagicMock()

        cider.install(*formulas, force=force)
        cider.brew.install.assert_called_once_with(*formulas, force=force)
        key = "casks" if cask else "formulas"
        for formula in formulas:
            assert formula in cider.read_bootstrap().get(key, [])

    @pytest.mark.randomize(formulas=nonempty_list_of(str), min_length=1)
    def test_rm(self, tmpdir, cask, debug, verbose, formulas):
        cider = Cider(cask, debug, verbose, cider_dir=str(tmpdir))
        cider.brew = MagicMock()

        cider.rm(*formulas)
        cider.brew.rm.assert_called_once_with(*formulas)
        key = "casks" if cask else "formulas"
        for formula in formulas:
            assert formula not in cider.read_bootstrap().get(key, [])

    @pytest.mark.randomize(data=dict_of(str, str))
    def test_read_bootstrap(self, tmpdir, cask, debug, verbose, data):
        with patch("cider.core.read_config") as mock:
            cider = Cider(cask, debug, verbose, cider_dir=str(tmpdir))
            mock.return_value = data
            assert cider.read_bootstrap() == data
            mock.assert_called_with(cider.bootstrap_file, {})

    @pytest.mark.randomize(random_prefix=str,
                           bootstrap={
                               "formulas": list_of(str),
                               "casks": list_of(str)
                           },
                           min_length=1)
    def test_installed(self, tmpdir, cask, debug, verbose, random_prefix,
                       bootstrap):
        cider = Cider(cask, debug, verbose, cider_dir=str(tmpdir))
        cider.read_bootstrap = MagicMock(return_value=bootstrap)

        key = "casks" if cask else "formulas"
        installed = bootstrap.get(key, [])
        random_choice = random.choice(installed) if installed else None
        for prefix in [None, random_choice, random_prefix]:
            assert cider.installed(prefix) == [
                x for x in installed if not prefix or x.startswith(prefix)
            ]

    @pytest.mark.randomize(installed=list_of(str),
                           brewed=list_of(str),
                           min_length=1)
    def test_missing(self, tmpdir, cask, debug, verbose, installed, brewed):
        orphans = []

        def generate_uses():
            uses = {}
            for formula in brewed:
                subset = [x for x in installed if x != formula]
                if subset and random.choice([True, False]):
                    uses[formula] = random.sample(
                        subset, random.randint(1, len(subset)))
                else:
                    orphans.append(formula)

            return lambda x: uses.get(x, [])

        cider = Cider(cask, debug, verbose, cider_dir=str(tmpdir))
        cider.brew = MagicMock()
        cider.brew.ls = MagicMock(return_value=brewed)
        cider.brew.uses = MagicMock(side_effect=generate_uses())
        cider.installed = MagicMock(return_value=installed)

        assert cider.missing() == sorted(orphans)
def test_list_of_negative_size():
    with pytest.raises(AssertionError):
        list_of(str, min_items=-1, max_items=-1).generate()
Esempio n. 19
0
def stdLibPerms(l):
  return [list(i) for i in permutations(l)] #permutations returns a list of tuples so I'm converting it to a list of lists

def comparePerms(p1, p2):
  found = False

  for i in p1:
    for j in p2:
      if sorted(i) == sorted(j):
        found = True
        break

    if found == False:
      return False
    else: 
      found == False

  return True

t = TestCase("__str__") #assertTrue is a method of TestCase, so to get to it I'm gonna just create a throw away instance of TestCase

@pytest.mark.randomize(l=list_of(int, min_items=0, max_items=6), ncalls=10)
def test_heaps(l):
  t.assertTrue(comparePerms(heaps(l), stdLibPerms(l)))

@pytest.mark.randomize(l=list_of(int, min_items=0, max_items=6), ncalls=10)
def test_sjt(l):
  t.assertTrue(comparePerms(sjt(sorted(l)), stdLibPerms(l)))

Esempio n. 20
0
def list_of(thetype, min_items=0, max_items=20):
    return pytest.list_of(thetype, min_items=min_items, max_items=max_items)
def test_list_of_unsupported_options():
    with pytest.raises(NotImplementedError):
        list_of(str, choices="something").generate()