pytest.mark.parametrize

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

178 Examples 7

Example 101

Project: html5lib-python Source File: test_stream.py
@pytest.mark.parametrize("inp,num",
                         [("\u0000", 0),
                          ("\u0001", 1),
                          ("\u0008", 1),
                          ("\u0009", 0),
                          ("\u000A", 0),
                          ("\u000B", 1),
                          ("\u000C", 0),
                          ("\u000D", 0),
                          ("\u000E", 1),
                          ("\u001F", 1),
                          ("\u0020", 0),
                          ("\u007E", 0),
                          ("\u007F", 1),
                          ("\u009F", 1),
                          ("\u00A0", 0),
                          ("\uFDCF", 0),
                          ("\uFDD0", 1),
                          ("\uFDEF", 1),
                          ("\uFDF0", 0),
                          ("\uFFFD", 0),
                          ("\uFFFE", 1),
                          ("\uFFFF", 1),
                          ("\U0001FFFD", 0),
                          ("\U0001FFFE", 1),
                          ("\U0001FFFF", 1),
                          ("\U0002FFFD", 0),
                          ("\U0002FFFE", 1),
                          ("\U0002FFFF", 1),
                          ("\U0003FFFD", 0),
                          ("\U0003FFFE", 1),
                          ("\U0003FFFF", 1),
                          ("\U0004FFFD", 0),
                          ("\U0004FFFE", 1),
                          ("\U0004FFFF", 1),
                          ("\U0005FFFD", 0),
                          ("\U0005FFFE", 1),
                          ("\U0005FFFF", 1),
                          ("\U0006FFFD", 0),
                          ("\U0006FFFE", 1),
                          ("\U0006FFFF", 1),
                          ("\U0007FFFD", 0),
                          ("\U0007FFFE", 1),
                          ("\U0007FFFF", 1),
                          ("\U0008FFFD", 0),
                          ("\U0008FFFE", 1),
                          ("\U0008FFFF", 1),
                          ("\U0009FFFD", 0),
                          ("\U0009FFFE", 1),
                          ("\U0009FFFF", 1),
                          ("\U000AFFFD", 0),
                          ("\U000AFFFE", 1),
                          ("\U000AFFFF", 1),
                          ("\U000BFFFD", 0),
                          ("\U000BFFFE", 1),
                          ("\U000BFFFF", 1),
                          ("\U000CFFFD", 0),
                          ("\U000CFFFE", 1),
                          ("\U000CFFFF", 1),
                          ("\U000DFFFD", 0),
                          ("\U000DFFFE", 1),
                          ("\U000DFFFF", 1),
                          ("\U000EFFFD", 0),
                          ("\U000EFFFE", 1),
                          ("\U000EFFFF", 1),
                          ("\U000FFFFD", 0),
                          ("\U000FFFFE", 1),
                          ("\U000FFFFF", 1),
                          ("\U0010FFFD", 0),
                          ("\U0010FFFE", 1),
                          ("\U0010FFFF", 1),
                          ("\x01\x01\x01", 3),
                          ("a\x01a\x01a\x01a", 3)])
def test_invalid_codepoints(inp, num):
    stream = HTMLUnicodeInputStream(StringIO(inp))
    for _i in range(len(inp)):
        stream.char()
    assert len(stream.errors) == num

Example 102

Project: instaseis Source File: test_server_finite_source.py
@pytest.mark.parametrize("usgs_param", [USGS_PARAM_FILE_1, USGS_PARAM_FILE_2])
def test_various_failure_conditions(reciprocal_clients_all_callbacks,
                                    usgs_param):
    """
    Tests some failure conditions.
    """
    client = reciprocal_clients_all_callbacks

    basic_parameters = {
        "receiverlongitude": 11,
        "receiverlatitude": 22,
        "components": "Z",
        "format": "miniseed"}

    with io.open(usgs_param, "rb") as fh:
        body = fh.read()

    # Starttime too large.
    params = copy.deepcopy(basic_parameters)
    params["starttime"] = 200000
    request = client.fetch(_assemble_url('finite_source', **params),
                           method="POST", body=body)
    assert request.code == 400
    assert request.reason == ("The `starttime` must be before the seismogram "
                              "ends.")

    # Starttime too early.
    params = copy.deepcopy(basic_parameters)
    params["starttime"] = -10000
    request = client.fetch(_assemble_url('finite_source', **params),
                           method="POST", body=body)
    assert request.code == 400
    assert request.reason == ("The seismogram can start at the maximum one "
                              "hour before the origin time.")

    # Endtime too small.
    params = copy.deepcopy(basic_parameters)
    params["endtime"] = -200000
    request = client.fetch(_assemble_url('finite_source', **params),
                           method="POST", body=body)
    assert request.code == 400
    assert request.reason == ("The end time of the seismograms lies outside "
                              "the allowed range.")

    # Useless phase relative times. pdiff does not exist at the epicentral
    # range of the example files.
    params = copy.deepcopy(basic_parameters)
    params["starttime"] = "Pdiff%2D5"
    request = client.fetch(_assemble_url('finite_source', **params),
                           method="POST", body=body)
    assert request.code == 400
    assert request.reason == ("No seismograms found for the given phase "
                              "relative offsets. This could either be due to "
                              "the chosen phase not existing for the specific "
                              "source-receiver geometry or arriving too "
                              "late/with too large offsets if the database is "
                              "not long enough.")

    # Scale of zero.
    params = copy.deepcopy(basic_parameters)
    params["scale"] = 0.0
    request = client.fetch(_assemble_url('finite_source', **params),
                           method="POST", body=body)
    assert request.code == 400
    assert request.reason.startswith("A scale of zero means")

    # Invalid receiver coordinates.
    params = copy.deepcopy(basic_parameters)
    params["receiverlatitude"] = 1E9
    request = client.fetch(_assemble_url('finite_source', **params),
                           method="POST", body=body)
    assert request.code == 400
    assert request.reason == ("Could not construct receiver with passed "
                              "parameters. Check parameters for sanity.")

    # Invalid receiver coordinates based on a station coordinates query.
    params = copy.deepcopy(basic_parameters)
    del params["receiverlatitude"]
    del params["receiverlongitude"]
    params["network"] = "XX"
    params["station"] = "DUMMY"
    request = client.fetch(_assemble_url('finite_source', **params),
                           method="POST", body=body)
    assert request.code == 400
    assert request.reason == ("Station coordinate query returned invalid "
                              "coordinates.")

    # Coordinates not found
    params = copy.deepcopy(basic_parameters)
    del params["receiverlatitude"]
    del params["receiverlongitude"]
    params["network"] = "UN"
    params["station"] = "KNOWN"
    request = client.fetch(_assemble_url('finite_source', **params),
                           method="POST", body=body)
    assert request.code == 404
    assert request.reason == "No coordinates found satisfying the query."

Example 103

Project: django-money Source File: test_tags.py
@pytest.mark.parametrize(
    'string, result, context',
    (
        (
            '{% load djmoney %}{% money_localize "2.5" "PLN" as NEW_M %}{{NEW_M}}',
            '2,50 zł',
            {}
        ),
        (
            '{% load djmoney %}{% money_localize "2.5" "PLN" %}',
            '2,50 zł',
            {}
        ),
        (
            '{% load djmoney %}{% money_localize amount currency %}',
            '2,60 zł',
            {'amount': 2.6, 'currency': 'PLN'}
        ),
        (
            '{% load djmoney %}{% money_localize money as NEW_M %}{{NEW_M}}',
            '2,30 zł',
            {'money': Money(2.3, 'PLN')}
        ),
        (
            '{% load djmoney %}{% money_localize money off as NEW_M %}{{NEW_M}}',
            '2.30 zł',
            {'money': Money(2.3, 'PLN')}
        ),
        (
            '{% load djmoney %}{% money_localize money off as NEW_M %}{{NEW_M}}',
            '0.00 zł',
            {'money': Money(0, 'PLN')}
        ),
        (
            # with a tag template "money_localize"
            '{% load djmoney %}{% money_localize money %}',
            '2,30 zł',
            {'money': Money(2.3, 'PLN')}
        ),
        (
            # without a tag template "money_localize"
            '{{ money }}',
            '2,30 zł',
            {'money': MoneyPatched(2.3, 'PLN')}
        ),
        (
            '{% load djmoney %}{% money_localize money off %}',
            '2.30 zł',
            {'money': Money(2.3, 'PLN')}
        ),
        (
            '{% load djmoney %}{% money_localize money on %}',
            '2,30 zł',
            {'money': Money(2.3, 'PLN')}
        )
    )
)
def test_tag(string, result, context):
    assert_template(string, result, context)

Example 104

Project: reikna Source File: test_basics.py
@pytest.mark.parametrize(
    'tempalloc_cls',
    [tempalloc.TrivialManager, tempalloc.ZeroOffsetManager],
    ids=['trivial', 'zero_offset'])
@pytest.mark.parametrize('pack', [False, True], ids=['no_pack', 'pack'])
def test_tempalloc(cluda_api, tempalloc_cls, pack):

    shape = (10000,)
    dtype = numpy.int32
    thr = cluda_api.Thread.create(temp_alloc=dict(
        cls=tempalloc_cls, pack_on_alloc=False))

    # Dependency graph for the test
    dependencies = dict(
        _temp0=[],
        _temp1=['_temp9', '_temp8', '_temp3', '_temp5', '_temp4', '_temp7', '_temp6', 'input'],
        _temp10=['output', '_temp7'],
        _temp11=['_temp7'],
        _temp2=['input'],
        _temp3=['_temp1', 'input'],
        _temp4=['_temp9', '_temp8', '_temp1', '_temp7', '_temp6'],
        _temp5=['_temp1'],
        _temp6=['_temp1', '_temp4'],
        _temp7=['_temp9', '_temp1', '_temp4', 'output', '_temp11', '_temp10'],
        _temp8=['_temp1', '_temp4'],
        _temp9=['_temp1', '_temp4', '_temp7'],
        input=['_temp1', '_temp3', '_temp2'],
        output=['_temp10', '_temp7'])

    program = thr.compile(
    """
    KERNEL void fill(GLOBAL_MEM ${ctype} *dest, ${ctype} val)
    {
      const SIZE_T i = get_global_id(0);
      dest[i] = val;
    }

    KERNEL void transfer(GLOBAL_MEM ${ctype} *dest, GLOBAL_MEM ${ctype} *src)
    {
      const SIZE_T i = get_global_id(0);
      dest[i] = src[i];
    }
    """, render_kwds=dict(ctype=dtypes.ctype(dtype)))
    fill = program.fill
    transfer = program.transfer

    arrays = {}
    transfer_dest = thr.array(shape, dtype)

    # Allocate temporary arrays with dependencies
    for name in sorted(dependencies.keys()):
        deps = dependencies[name]
        arr_deps = [arrays[d] for d in deps if d in arrays]
        arrays[name] = thr.temp_array(shape, dtype, dependencies=arr_deps)
        fill(arrays[name], dtype(0), global_size=shape)

    if pack:
        thr.temp_alloc.pack()

    # Fill arrays with zeros
    for name in sorted(dependencies.keys()):
        deps = dependencies[name]
        arr_deps = [arrays[d] for d in deps if d in arrays]
        arrays[name] = thr.temp_array(shape, dtype, dependencies=arr_deps)
        fill(arrays[name], dtype(0), global_size=shape)

    for i, name in enumerate(sorted(dependencies.keys())):
        val = dtype(i + 1)
        fill(arrays[name], val, global_size=shape)
        for dep in dependencies[name]:
            # CUDA does not support get() for GPUArray with custom buffers,
            # So we need to transfer the data to a normal array first.
            transfer(transfer_dest, arrays[dep], global_size=shape)
            assert (transfer_dest.get() != val).all()

Example 105

Project: OpenTAXII Source File: test_subscription_management.py
@pytest.mark.parametrize("https", [True, False])
def test_subscribe_pause_resume(server, https):

    version = 11

    service = server.get_service('collection-management-A')

    headers = prepare_headers(version, https)

    params = dict(
        response_type=RT_FULL,
        content_bindings=[CB_STIX_XML_111, CUSTOM_CONTENT_BINDING]
    )

    # Subscribing
    request = prepare_request(
        collection=COLLECTION_OPEN, action=ACT_SUBSCRIBE,
        version=version, params=params)

    response = service.process(headers, request)

    assert isinstance(
        response,
        as_tm(version).ManageCollectionSubscriptionResponse)
    assert response.collection_name == COLLECTION_OPEN

    assert len(response.subscription_instances) == 1

    subs = response.subscription_instances[0]

    assert subs.status == SS_ACTIVE
    assert (
        server.persistence.get_subscription(subs.subscription_id).status ==
        SS_ACTIVE)

    # Pausing
    request = prepare_request(
        collection=COLLECTION_OPEN, action=ACT_PAUSE,
        subscription_id=subs.subscription_id, version=version)

    response = service.process(headers, request)

    assert isinstance(
        response,
        as_tm(version).ManageCollectionSubscriptionResponse)
    assert response.collection_name == COLLECTION_OPEN

    assert len(response.subscription_instances) == 1

    subs = response.subscription_instances[0]

    assert subs.subscription_id
    assert subs.status == SS_PAUSED
    assert (
        server.persistence.get_subscription(subs.subscription_id).status ==
        SS_PAUSED)

    # Resume
    request = prepare_request(
        collection=COLLECTION_OPEN, action=ACT_RESUME,
        subscription_id=subs.subscription_id, version=version)

    response = service.process(headers, request)

    assert isinstance(
        response,
        as_tm(version).ManageCollectionSubscriptionResponse)
    assert response.collection_name == COLLECTION_OPEN

    assert len(response.subscription_instances) == 1

    subs = response.subscription_instances[0]

    assert subs.subscription_id
    assert subs.status == SS_ACTIVE
    assert (
        server.persistence.get_subscription(subs.subscription_id).status ==
        SS_ACTIVE)

Example 106

Project: two1-python Source File: test_ecdsa.py
@pytest.mark.parametrize("curve", [
    ecdsa_python.secp256k1(),
    ecdsa_openssl.secp256k1()
    ])
def test_secp256k1(curve):
    # Don't test point operations for OpenSSL
    if isinstance(curve, ecdsa_python.secp256k1):
        private_key, pub_key_aff = curve.gen_key_pair()

        pub_key_jac = ecdsa_python.ECPointJacobian.from_affine(pub_key_aff)
        pub_key_jac_2 = pub_key_jac * 2
        pub_key_aff_2 = pub_key_aff * 2

        assert pub_key_jac_2.to_affine() == pub_key_aff_2

        pub_key_aff_3 = pub_key_aff_2 + pub_key_aff
        pub_key_jac_3 = pub_key_jac_2 + pub_key_jac

        assert pub_key_jac_3.to_affine() == pub_key_aff_3

        k = 0xAA5E28D6A97A2479A65527F7290311A3624D4CC0FA1578598EE3C2613BF99522
        kG = (curve.base_point * k).to_affine()
        assert kG.x == 0x34F9460F0E4F08393D192B3C5133A6BA099AA0AD9FD54EBCCFACDFA239FF49C6
        assert kG.y == 0x0B71EA9BD730FD8923F6D25A7A91E7DD7728A960686CB5A901BB419E0F2CA232

        k = 0x7E2B897B8CEBC6361663AD410835639826D590F393D90A9538881735256DFAE3
        kG = (curve.base_point * k).to_affine()
        assert kG.x == 0xD74BF844B0862475103D96A611CF2D898447E288D34B360BC885CB8CE7C00575
        assert kG.y == 0x131C670D414C4546B88AC3FF664611B1C38CEB1C21D76369D7A7A0969D61D97D

        k = 0x6461E6DF0FE7DFD05329F41BF771B86578143D4DD1F7866FB4CA7E97C5FA945D
        kG = (curve.base_point * k).to_affine()
        assert kG.x == 0xE8AECC370AEDD953483719A116711963CE201AC3EB21D3F3257BB48668C6A72F
        assert kG.y == 0xC25CAF2F0EBA1DDB2F0F3F47866299EF907867B7D27E95B3873BF98397B24EE1

        k = 0x376A3A2CDCD12581EFFF13EE4AD44C4044B8A0524C42422A7E1E181E4DEECCEC
        kG = (curve.base_point * k).to_affine()
        assert kG.x == 0x14890E61FCD4B0BD92E5B36C81372CA6FED471EF3AA60A3E415EE4FE987DABA1
        assert kG.y == 0x297B858D9F752AB42D3BCA67EE0EB6DCD1C2B7B0DBE23397E66ADC272263F982

        k = 0x1B22644A7BE026548810C378D0B2994EEFA6D2B9881803CB02CEFF865287D1B9
        kG = (curve.base_point * k).to_affine()
        assert kG.x == 0xF73C65EAD01C5126F28F442D087689BFA08E12763E0CEC1D35B01751FD735ED3
        assert kG.y == 0xF449A8376906482A84ED01479BD18882B919C140D638307F0C0934BA12590BDE

    # test getting y from x
    x = 0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798
    y1, y2 = curve.y_from_x(x)

    assert y1 == 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8

    # test the nonce generation, these test-vectors are taken from:
    # https://bitcointalk.org/index.php?topic=285142.25
    private_key = 0x1
    message = b"Satoshi Nakamoto"
    k = curve._nonce_rfc6979(private_key, hashlib.sha256(message).digest())

    assert k == 0x8F8A276C19F4149656B280621E358CCE24F5F52542772691EE69063B74F15D15

    sig_pt, rec_id = curve.sign(message, private_key)
    sig_pt, _ = make_low_s(curve, sig_pt, rec_id)
    sig_full = (sig_pt.x << curve.nlen) + sig_pt.y

    assert sig_full == 0x934b1ea10a4b3c1757e2b0c017d0b6143ce3c9a7e6a4a49860d7a6ab210ee3d82442ce9d2b916064108014783e923ec36b49743e2ffa1c4496f01a512aafd9e5  # nopep8

    private_key = 0x1
    message = b"All those moments will be lost in time, like tears in rain. Time to die..."
    k = curve._nonce_rfc6979(private_key, hashlib.sha256(message).digest())

    assert k == 0x38AA22D72376B4DBC472E06C3BA403EE0A394DA63FC58D88686C611ABA98D6B3

    sig_pt, rec_id = curve.sign(message, private_key)
    sig_pt, _ = make_low_s(curve, sig_pt, rec_id)
    sig_full = (sig_pt.x << curve.nlen) + sig_pt.y

    assert sig_full == 0x8600dbd41e348fe5c9465ab92d23e3db8b98b873beecd930736488696438cb6b547fe64427496db33bf66019dacbf0039c04199abb0122918601db38a72cfc21  # nopep8

    private_key = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364140
    message = b"Satoshi Nakamoto"
    k = curve._nonce_rfc6979(private_key, hashlib.sha256(message).digest())

    assert k == 0x33A19B60E25FB6F4435AF53A3D42D493644827367E6453928554F43E49AA6F90

    sig_pt, _ = curve.sign(message, private_key)
    sig_pt, rec_id = make_low_s(curve, sig_pt, rec_id)
    sig_full = (sig_pt.x << curve.nlen) + sig_pt.y

    assert sig_full == 0xfd567d121db66e382991534ada77a6bd3106f0a1098c231e47993447cd6af2d06b39cd0eb1bc8603e159ef5c20a5c8ad685a45b06ce9bebed3f153d10d93bed5  # nopep8

    private_key = 0xf8b8af8ce3c7cca5e300d33939540c10d45ce001b8f252bfbc57ba0342904181
    message = b"Alan Turing"
    k = curve._nonce_rfc6979(private_key, hashlib.sha256(message).digest())

    assert k == 0x525A82B70E67874398067543FD84C83D30C175FDC45FDEEE082FE13B1D7CFDF1

    sig_pt, rec_id = curve.sign(message, private_key)
    sig_pt, _ = make_low_s(curve, sig_pt, rec_id)
    sig_full = (sig_pt.x << curve.nlen) + sig_pt.y

    assert sig_full == 0x7063ae83e7f62bbb171798131b4a0564b956930092b33b07b395615d9ec7e15c58dfcc1e00a35e1572f366ffe34ba0fc47db1e7189759b9fb233c5b05ab388ea  # nopep8

    private_key = 0xe91671c46231f833a6406ccbea0e3e392c76c167bac1cb013f6f1013980455c2
    message = b"There is a computer disease that anybody who works with computers knows about. It's a very serious disease and it interferes completely with the work. The trouble with computers is that you 'play' with them!"  # nopep8
    k = curve._nonce_rfc6979(private_key, hashlib.sha256(message).digest())

    assert k == 0x1F4B84C23A86A221D233F2521BE018D9318639D5B8BBD6374A8A59232D16AD3D

    sig_pt, rec_id = curve.sign(message, private_key)
    sig_pt, _ = make_low_s(curve, sig_pt, rec_id)
    sig_full = (sig_pt.x << curve.nlen) + sig_pt.y

    assert sig_full == 0xb552edd27580141f3b2a5463048cb7cd3e047b97c9f98076c32dbdf85a68718b279fa72dd19bfae05577e06c7c0c1900c371fcd5893f7e1d56a37d30174671f6  # nopep8

Example 107

Project: vcrpy Source File: test_matchers.py
@pytest.mark.parametrize("r1, r2", [
    (
        request.Request('POST', 'http://host.com/', '123', {}),
        request.Request('POST', 'http://another-host.com/',
                        '123', {'Some-Header': 'value'})
    ),
    (
        request.Request('POST', 'http://host.com/', 'a=1&b=2',
                        {'Content-Type': 'application/x-www-form-urlencoded'}),
        request.Request('POST', 'http://host.com/', 'b=2&a=1',
                        {'Content-Type': 'application/x-www-form-urlencoded'})
    ),
    (
        request.Request('POST', 'http://host.com/', '123', {}),
        request.Request('POST', 'http://another-host.com/', '123', {'Some-Header': 'value'})
    ),
    (
        request.Request(
            'POST', 'http://host.com/', 'a=1&b=2',
            {'Content-Type': 'application/x-www-form-urlencoded'}
        ),
        request.Request(
            'POST', 'http://host.com/', 'b=2&a=1',
            {'Content-Type': 'application/x-www-form-urlencoded'}
        )
    ),
    (
        request.Request(
            'POST', 'http://host.com/', '{"a": 1, "b": 2}',
            {'Content-Type': 'application/json'}
        ),
        request.Request(
            'POST', 'http://host.com/', '{"b": 2, "a": 1}',
            {'content-type': 'application/json'}
        )
    ),
    (
        request.Request(
            'POST', 'http://host.com/', req1_body,
            {'User-Agent': 'xmlrpclib', 'Content-Type': 'text/xml'}
        ),
        request.Request(
            'POST', 'http://host.com/', req2_body,
            {'user-agent': 'somexmlrpc', 'content-type': 'text/xml'}
        )
    ),
    (
        request.Request(
            'POST', 'http://host.com/',
            '{"a": 1, "b": 2}', {'Content-Type': 'application/json'}
        ),
        request.Request(
            'POST', 'http://host.com/',
            '{"b": 2, "a": 1}', {'content-type': 'application/json'}
        )
    )
])
def test_body_matcher_does_match(r1, r2):
    assert matchers.body(r1, r2)

Example 108

Project: aerospike-client-python Source File: test_operate.py
Function: test_pos_operate_with_correct_paramters
    @pytest.mark.parametrize("key, llist, expected", [
        (('test', 'demo', 1),
            [{"op": aerospike.OPERATOR_PREPEND,
              "bin": "name",
              "val": u"ram"},
             {"op": aerospike.OPERATOR_INCR,
              "bin": "age",
              "val": 3}, {"op": aerospike.OPERATOR_READ,
                          "bin": "name"}],
            {'name': 'ramname1'}),
        (('test', 'demo', 1),                           # with_write_float_value
            [{"op": aerospike.OPERATOR_WRITE,
                "bin": "write_bin",
                "val": {"no": 89.8}},
             {"op": aerospike.OPERATOR_READ,
                "bin": "write_bin"}],
         {'write_bin': {u'no': 89.8}}),
        (('test', 'demo', 1),                            # write positive
            [{"op": aerospike.OPERATOR_WRITE,
                "bin": "write_bin",
                "val": {"no": 89}},
                {"op": aerospike.OPERATOR_READ, "bin": "write_bin"}],
            {'write_bin': {u'no': 89}}),
        (('test', 'demo', 1),                               # write_tuple_positive
            [{"op": aerospike.OPERATOR_WRITE,
                "bin": "write_bin",
                "val": tuple('abc')},
                {"op": aerospike.OPERATOR_READ, "bin": "write_bin"}],
            {'write_bin': ('a', 'b', 'c')}),
        (('test', 'demo', 1),                               # with_bin_bytearray
            [{"op": aerospike.OPERATOR_PREPEND,
              "bin": bytearray("asd[;asjk", "utf-8"),
              "val": u"ram"},
             {"op": aerospike.OPERATOR_READ,
                "bin": bytearray("asd[;asjk", "utf-8")}],
            {'asd[;asjk': 'ram'}),
        (('test', 'demo', 'bytearray_key'),                  # with_operator append_val bytearray
            [{"op": aerospike.OPERATOR_APPEND,
              "bin": "bytearray_bin",
              "val": bytearray("abc", "utf-8")},
             {"op": aerospike.OPERATOR_READ,
              "bin": "bytearray_bin"}],
         {'bytearray_bin': bytearray("asd;as[d'as;dabc", "utf-8")}),
        (('test', 'demo', 'bytearray_new'),                   # with_operator append_val bytearray_newrecord
            [{"op": aerospike.OPERATOR_APPEND,
              "bin": "bytearray_bin",
              "val": bytearray("asd;as[d'as;d", "utf-8")},
             {"op": aerospike.OPERATOR_READ,
              "bin": "bytearray_bin"}],
            {'bytearray_bin': bytearray("asd;as[d'as;d", "utf-8")}),
        (('test', 'demo', 'bytearray_key'),  # with_operatorprepend_valbytearray
            [{"op": aerospike.OPERATOR_PREPEND,
              "bin": "bytearray_bin",
              "val": bytearray("abc", "utf-8")},
             {"op": aerospike.OPERATOR_READ,
              "bin": "bytearray_bin"}],
            {'bytearray_bin': bytearray("abcasd;as[d'as;d", "utf-8")}),
        (('test', 'demo', 'bytearray_new'),                 # with_operatorprepend_valbytearray_newrecord
            [{"op": aerospike.OPERATOR_PREPEND,
              "bin": "bytearray_bin",
              "val": bytearray("asd;as[d'as;d", "utf-8")},
             {"op": aerospike.OPERATOR_READ,
              "bin": "bytearray_bin"}],
            {'bytearray_bin': bytearray("asd;as[d'as;d", "utf-8")}),

    ])
    def test_pos_operate_with_correct_paramters(self, key, llist, expected):
        """
        Invoke operate() with correct parameters
        """

        key, _, bins = self.as_connection.operate(key, llist)

        assert bins == expected
        self.as_connection.remove(key)

Example 109

Project: vint Source File: test_scope_detector.py
@pytest.mark.parametrize(
    'context_scope_visibility, id_node, expected_scope_visibility, expected_implicity', [
        # Declarative variable test
        (Vis.SCRIPT_LOCAL, create_id('g:explicit_global'), Vis.GLOBAL_LIKE, False),
        (Vis.SCRIPT_LOCAL, create_id('implicit_global'), Vis.GLOBAL_LIKE, True),
        (Vis.FUNCTION_LOCAL, create_id('g:explicit_global'), Vis.GLOBAL_LIKE, False),

        (Vis.SCRIPT_LOCAL, create_id('b:buffer_local'), Vis.GLOBAL_LIKE, False),
        (Vis.FUNCTION_LOCAL, create_id('b:buffer_local'), Vis.GLOBAL_LIKE, False),

        (Vis.SCRIPT_LOCAL, create_id('w:window_local'), Vis.GLOBAL_LIKE, False),
        (Vis.FUNCTION_LOCAL, create_id('w:window_local'), Vis.GLOBAL_LIKE, False),

        (Vis.SCRIPT_LOCAL, create_id('s:script_local'), Vis.SCRIPT_LOCAL, False),
        (Vis.FUNCTION_LOCAL, create_id('s:script_local'), Vis.SCRIPT_LOCAL, False),

        (Vis.FUNCTION_LOCAL, create_id('l:explicit_function_local'), Vis.FUNCTION_LOCAL, False),
        (Vis.FUNCTION_LOCAL, create_id('implicit_function_local'), Vis.FUNCTION_LOCAL, True),

        (Vis.FUNCTION_LOCAL, create_id('param', is_declarative=True, is_declarative_parameter=True), Vis.FUNCTION_LOCAL, False),

        (Vis.SCRIPT_LOCAL, create_id('v:count'), Vis.BUILTIN, False),
        (Vis.FUNCTION_LOCAL, create_id('v:count'), Vis.BUILTIN, False),
        (Vis.FUNCTION_LOCAL, create_id('count'), Vis.BUILTIN, True),

        (Vis.SCRIPT_LOCAL, create_curlyname(), Vis.UNANALYZABLE, False),
        (Vis.FUNCTION_LOCAL, create_curlyname(), Vis.UNANALYZABLE, False),

        (Vis.SCRIPT_LOCAL, create_subscript_member(), Vis.UNANALYZABLE, False),
        (Vis.FUNCTION_LOCAL, create_subscript_member(), Vis.UNANALYZABLE, False),

        (Vis.SCRIPT_LOCAL, create_id('g:ExplicitGlobalFunc', is_function=True), Vis.GLOBAL_LIKE, False),
        (Vis.SCRIPT_LOCAL, create_id('ImplicitGlobalFunc', is_function=True), Vis.GLOBAL_LIKE, True),

        (Vis.SCRIPT_LOCAL, create_id('g:file#explicit_global_func', is_function=True, is_autoload=True), Vis.GLOBAL_LIKE, False),
        (Vis.SCRIPT_LOCAL, create_id('file#implicit_global_func', is_function=True, is_autoload=True), Vis.GLOBAL_LIKE, True),

        (Vis.FUNCTION_LOCAL, create_id('g:ExplicitGlobalFunc', is_function=True), Vis.GLOBAL_LIKE, False),
        (Vis.FUNCTION_LOCAL, create_id('ImplicitGlobalFunc', is_function=True), Vis.GLOBAL_LIKE, True),

        (Vis.FUNCTION_LOCAL, create_id('g:file#explicit_global_func', is_function=True, is_autoload=True), Vis.GLOBAL_LIKE, False),
        (Vis.FUNCTION_LOCAL, create_id('file#implicit_global_func', is_function=True, is_autoload=True), Vis.GLOBAL_LIKE, True),

        (Vis.SCRIPT_LOCAL, create_id('s:ScriptLocalFunc', is_function=True), Vis.SCRIPT_LOCAL, False),
        (Vis.FUNCTION_LOCAL, create_id('s:ScriptLocalFunc', is_function=True), Vis.SCRIPT_LOCAL, False),

        (Vis.SCRIPT_LOCAL, create_id('t:InvalidScopeFunc', is_function=True), Vis.INVALID, False),

        # Referencing variable test
        (Vis.SCRIPT_LOCAL, create_id('g:explicit_global', is_declarative=False), Vis.GLOBAL_LIKE, False),
        (Vis.SCRIPT_LOCAL, create_id('implicit_global', is_declarative=False), Vis.GLOBAL_LIKE, True),
        (Vis.FUNCTION_LOCAL, create_id('g:explicit_global', is_declarative=False), Vis.GLOBAL_LIKE, False),

        (Vis.SCRIPT_LOCAL, create_id('b:buffer_local', is_declarative=False), Vis.GLOBAL_LIKE, False),
        (Vis.FUNCTION_LOCAL, create_id('b:buffer_local', is_declarative=False), Vis.GLOBAL_LIKE, False),

        (Vis.SCRIPT_LOCAL, create_id('w:window_local', is_declarative=False), Vis.GLOBAL_LIKE, False),
        (Vis.FUNCTION_LOCAL, create_id('w:window_local', is_declarative=False), Vis.GLOBAL_LIKE, False),

        (Vis.SCRIPT_LOCAL, create_id('s:script_local', is_declarative=False), Vis.SCRIPT_LOCAL, False),
        (Vis.FUNCTION_LOCAL, create_id('s:script_local', is_declarative=False), Vis.SCRIPT_LOCAL, False),

        (Vis.FUNCTION_LOCAL, create_id('l:explicit_function_local', is_declarative=False), Vis.FUNCTION_LOCAL, False),
        (Vis.FUNCTION_LOCAL, create_id('implicit_function_local', is_declarative=False), Vis.FUNCTION_LOCAL, True),

        (Vis.FUNCTION_LOCAL, create_id('a:param', is_declarative=False), Vis.FUNCTION_LOCAL, False),
        (Vis.FUNCTION_LOCAL, create_id('a:000', is_declarative=False), Vis.FUNCTION_LOCAL, False),
        (Vis.FUNCTION_LOCAL, create_id('a:1', is_declarative=False), Vis.FUNCTION_LOCAL, False),

        (Vis.SCRIPT_LOCAL, create_id('v:count', is_declarative=False), Vis.BUILTIN, False),
        (Vis.FUNCTION_LOCAL, create_id('v:count', is_declarative=False), Vis.BUILTIN, False),
        (Vis.FUNCTION_LOCAL, create_id('count', is_declarative=False), Vis.BUILTIN, True),
        (Vis.SCRIPT_LOCAL, create_id('localtime', is_declarative=False, is_function=True), Vis.BUILTIN, False),

        (Vis.SCRIPT_LOCAL, create_curlyname(is_declarative=False), Vis.UNANALYZABLE, False),
        (Vis.FUNCTION_LOCAL, create_curlyname(is_declarative=False), Vis.UNANALYZABLE, False),

        (Vis.SCRIPT_LOCAL, create_subscript_member(is_declarative=False), Vis.UNANALYZABLE, False),
        (Vis.FUNCTION_LOCAL, create_subscript_member(is_declarative=False), Vis.UNANALYZABLE, False),

        (Vis.SCRIPT_LOCAL, create_id('g:ExplicitGlobalFunc', is_declarative=False, is_function=True), Vis.GLOBAL_LIKE, False),
        (Vis.SCRIPT_LOCAL, create_id('ImplicitGlobalFunc', is_declarative=False, is_function=True), Vis.GLOBAL_LIKE, True),

        (Vis.SCRIPT_LOCAL, create_id('g:file#explicit_global_func', is_declarative=False, is_function=True, is_autoload=True), Vis.GLOBAL_LIKE, False),
        (Vis.SCRIPT_LOCAL, create_id('file#implicit_global_func', is_declarative=False, is_function=False, is_autoload=True), Vis.GLOBAL_LIKE, True),

        (Vis.FUNCTION_LOCAL, create_id('g:ExplicitGlobalFunc', is_declarative=False, is_function=True), Vis.GLOBAL_LIKE, False),
        (Vis.FUNCTION_LOCAL, create_id('ImplicitGlobalFunc', is_declarative=False, is_function=True), Vis.GLOBAL_LIKE, True),

        (Vis.FUNCTION_LOCAL, create_id('g:file#explicit_global_func', is_declarative=False, is_function=True, is_autoload=True), Vis.GLOBAL_LIKE, False),
        (Vis.FUNCTION_LOCAL, create_id('file#implicit_global_func', is_declarative=False, is_function=True, is_autoload=True), Vis.GLOBAL_LIKE, True),

        (Vis.SCRIPT_LOCAL, create_id('s:ScriptLocalFunc', is_declarative=False, is_function=True), Vis.SCRIPT_LOCAL, False),
        (Vis.FUNCTION_LOCAL, create_id('s:ScriptLocalFunc', is_declarative=False, is_function=True), Vis.SCRIPT_LOCAL, False),

        (Vis.SCRIPT_LOCAL, create_id('t:TabLocalFuncRef', is_declarative=False, is_function=True), Vis.GLOBAL_LIKE, False),
    ]
)
def test_detect_scope_visibility(context_scope_visibility, id_node, expected_scope_visibility, expected_implicity):
    scope = create_scope(context_scope_visibility)
    scope_visibility_hint = detect_scope_visibility(id_node, scope)

    expected_scope_visibility_hint = create_scope_visibility_hint(expected_scope_visibility,
                                                                  is_implicit=expected_implicity)
    assert expected_scope_visibility_hint == scope_visibility_hint

Example 110

Project: sqlalchemy-imageattach Source File: s3_test.py
@mark.parametrize(('underlying_prefix', 'overriding_prefix'), [
    ('under', 'over'),
    ('', '')
])
@mark.slow
def test_s3_sandbox_store(underlying_prefix, overriding_prefix,
                          s3_sandbox_store_getter):
    s3 = s3_sandbox_store_getter(underlying_prefix=underlying_prefix,
                                 overriding_prefix=overriding_prefix)
    under = s3.underlying
    over = s3.overriding
    id_offset = uuid.uuid1().int
    if id_offset % 2:  # id_offset is always even
        id_offset -= 1
    if not underlying_prefix:
        id_offset *= -1
    # Store a fixture image for underlying store
    under_id = id_offset + 1
    under_image = TestingImage(thing_id=under_id, width=405, height=640,
                               mimetype='image/jpeg', original=True,
                               created_at=utcnow())
    image_path = os.path.join(sample_images_dir, 'iu.jpg')
    with open(image_path, 'rb') as image_file:
        expected_data = image_file.read()
        image_file.seek(0)
        under.store(under_image, image_file)
    # Underlying images have to be logically shown through sandbox
    with s3.open(under_image) as actual:
        actual_data = actual.read()
    assert expected_data == actual_data
    expected_url = under.get_url('testing', under_id, 405, 640, 'image/jpeg')
    actual_url = s3.locate(under_image)
    assert remove_query(expected_url) == remove_query(actual_url)
    # Store an image to sandbox store
    over_id = id_offset + 2
    image = TestingImage(thing_id=over_id, width=405, height=640,
                         mimetype='image/jpeg', original=True,
                         created_at=utcnow())
    image_path = os.path.join(sample_images_dir, 'iu.jpg')
    with open(image_path, 'rb') as image_file:
        s3.store(image, image_file)
    # Image has to be logically stored
    with s3.open(image) as actual:
        actual_data = actual.read()
    assert expected_data == actual_data
    expected_url = over.get_url('testing', over_id, 405, 640, 'image/jpeg')
    actual_url = s3.locate(image)
    assert remove_query(expected_url) == remove_query(actual_url)
    # Image has to be physically stored into the overriding store
    with over.open(image) as actual:
        actual_data = actual.read()
    assert expected_data == actual_data
    expected_url = over.get_url('testing', over_id, 405, 640, 'image/jpeg')
    actual_url = s3.locate(image)
    assert remove_query(expected_url) == remove_query(actual_url)
    # Images must not be physically stored into the underlying store
    with raises(IOError):
        under.open(image)
    # Deletion must not touch underlying
    s3.delete(under_image)
    with raises(IOError):
        s3.open(under_image)
    with under.open(under_image) as actual:
        actual_data = actual.read()
    assert expected_data == actual_data
    expected_url = over.get_url('testing', under_id, 405, 640, 'image/jpeg')
    actual_url = s3.locate(under_image)
    assert remove_query(expected_url) == remove_query(actual_url)
    # Clean up fixtures
    if underlying_prefix and overriding_prefix:
        no_prefix = s3_sandbox_store_getter()
        with raises(IOError):
            no_prefix.open(image)
    under.delete(under_image)

Example 111

Project: CSScheme Source File: test_tokenizer.py
Function: test_tokens
@pytest.mark.parametrize(('tokenize', 'css_source', 'expected_tokens'), [
  (tokenize,) + test_data
  for tokenize in (python_tokenize_flat, cython_tokenize_flat)
  for test_data in [
    ('', []),
    ('red -->',
        [('IDENT', 'red'), ('S', ' '), ('CDC', '-->')]),
    # Longest match rule: no CDC
    ('red-->',
        [('IDENT', 'red--'), ('DELIM', '>')]),

    (r'''p[example="\
foo(int x) {\
    this.x = x;\
}\
"]''', [
        ('IDENT', 'p'),
        ('[', '['),
        ('IDENT', 'example'),
        ('DELIM', '='),
        ('STRING', 'foo(int x) {    this.x = x;}'),
        (']', ']')]),

    #### Numbers are parsed
    ('42 .5 -4pX 1.25em 30%',
        [('INTEGER', 42), ('S', ' '),
         ('NUMBER', .5), ('S', ' '),
         # units are normalized to lower-case:
         ('DIMENSION', -4, 'px'), ('S', ' '),
         ('DIMENSION', 1.25, 'em'), ('S', ' '),
         ('PERCENTAGE', 30, '%')]),

    #### URLs are extracted
    ('url(foo.png)', [('URI', 'foo.png')]),
    ('url("foo.png")', [('URI', 'foo.png')]),

    #### Escaping

    (r'/* Comment with a \ backslash */',
        [('COMMENT', '/* Comment with a \ backslash */')]),  # Unchanged

    # backslash followed by a newline in a string: ignored
    ('"Lorem\\\nIpsum"', [('STRING', 'LoremIpsum')]),

    # backslash followed by a newline outside a string: stands for itself
    ('Lorem\\\nIpsum', [
        ('IDENT', 'Lorem'), ('DELIM', '\\'),
        ('S', '\n'), ('IDENT', 'Ipsum')]),

    # Cancel the meaning of special characters
    (r'"Lore\m Ipsum"', [('STRING', 'Lorem Ipsum')]),  # or not specal
    (r'"Lorem \49psum"', [('STRING', 'Lorem Ipsum')]),
    (r'"Lorem \49 psum"', [('STRING', 'Lorem Ipsum')]),
    (r'"Lorem\"Ipsum"', [('STRING', 'Lorem"Ipsum')]),
    (r'"Lorem\\Ipsum"', [('STRING', r'Lorem\Ipsum')]),
    (r'"Lorem\5c Ipsum"', [('STRING', r'Lorem\Ipsum')]),
    (r'Lorem\+Ipsum', [('IDENT', 'Lorem+Ipsum')]),
    (r'Lorem+Ipsum', [('IDENT', 'Lorem'), ('DELIM', '+'), ('IDENT', 'Ipsum')]),
    (r'url(foo\).png)', [('URI', 'foo).png')]),

    # Unicode and backslash escaping
    ('\\26 B', [('IDENT', '&B')]),
    ('\\&B', [('IDENT', '&B')]),
    ('@\\26\tB', [('ATKEYWORD', '@&B')]),
    ('@\\&B', [('ATKEYWORD', '@&B')]),
    ('#\\26\nB', [('HASH', '#&B')]),
    ('#\\&B', [('HASH', '#&B')]),
    ('\\26\r\nB(', [('FUNCTION', '&B(')]),
    ('\\&B(', [('FUNCTION', '&B(')]),
    (r'12.5\000026B', [('DIMENSION', 12.5, '&b')]),
    (r'12.5\0000263B', [('DIMENSION', 12.5, '&3b')]),  # max 6 digits
    (r'12.5\&B', [('DIMENSION', 12.5, '&b')]),
    (r'"\26 B"', [('STRING', '&B')]),
    (r"'\000026B'", [('STRING', '&B')]),
    (r'"\&B"', [('STRING', '&B')]),
    (r'url("\26 B")', [('URI', '&B')]),
    (r'url(\26 B)', [('URI', '&B')]),
    (r'url("\&B")', [('URI', '&B')]),
    (r'url(\&B)', [('URI', '&B')]),
    (r'Lorem\110000Ipsum', [('IDENT', 'Lorem\uFFFDIpsum')]),

    #### Bad strings

    # String ends at EOF without closing: no error, parsed
    ('"Lorem\\26Ipsum', [('STRING', 'Lorem&Ipsum')]),
    # Unescaped newline: ends the string, error, unparsed
    ('"Lorem\\26Ipsum\n', [
        ('BAD_STRING', r'"Lorem\26Ipsum'), ('S', '\n')]),
    # Tokenization restarts after the newline, so the second " starts
    # a new string (which ends at EOF without errors, as above.)
    ('"Lorem\\26Ipsum\ndolor" sit', [
        ('BAD_STRING', r'"Lorem\26Ipsum'), ('S', '\n'),
        ('IDENT', 'dolor'), ('STRING', ' sit')]),

]])
def test_tokens(tokenize, css_source, expected_tokens):
    if tokenize is None:  # pragma: no cover
        pytest.skip('Speedups not available')
    sources = [css_source]
    if sys.version_info[0] < 3:
        # On Python 2.x, ASCII-only bytestrings can be used
        # where Unicode is expected.
        sources.append(css_source.encode('ascii'))
    for css_source in sources:
        tokens = tokenize(css_source, ignore_comments=False)
        result = [
            (token.type, token.value) + (
                () if token.unit is None else (token.unit,))
            for token in tokens
        ]
        assert result == expected_tokens

Example 112

Project: calvin-base Source File: test_calvincontrol.py
@pytest.mark.parametrize("url,match,handler", [
    ("GET /actor_doc HTTP/1", None, "handle_get_actor_doc"),
    ("POST /log HTTP/1", None, "handle_post_log"),
    ("DELETE /log/TRACE_" + uuid + " HTTP/1", "TRACE_" + uuid, "handle_delete_log"),
    ("GET /log/TRACE_" + uuid + " HTTP/1", "TRACE_" + uuid, "handle_get_log"),
    ("GET /id HTTP/1", None, "handle_get_node_id"),
    ("GET /nodes HTTP/1", None, "handle_get_nodes"),
    ("GET /node/NODE_" + uuid + " HTTP/1", "NODE_" + uuid, "handle_get_node"),
    ("POST /peer_setup HTTP/1", None, "handle_peer_setup"),
    ("GET /applications HTTP/1", None, "handle_get_applications"),
    ("GET /application/APP_" + uuid + " HTTP/1", "APP_" + uuid, "handle_get_application"),
    ("DELETE /application/APP_" + uuid + " HTTP/1", "APP_" + uuid, "handle_del_application"),
    ("POST /actor HTTP/1", None, "handle_new_actor"),
    ("GET /actors HTTP/1", None, "handle_get_actors"),
    ("GET /actor/" + uuid + " HTTP/1", uuid, "handle_get_actor"),
    ("DELETE /actor/" + uuid + " HTTP/1", uuid, "handle_del_actor"),
    ("GET /actor/" + uuid + "/report HTTP/1", uuid, "handle_get_actor_report"),
    ("POST /actor/" + uuid + "/migrate HTTP/1", uuid, "handle_actor_migrate"),
    ("POST /actor/" + uuid + "/disable HTTP/1", uuid, "handle_actor_disable"),
    ("GET /actor/" + uuid + "/port/PORT_" + uuid + " HTTP/1", uuid, "handle_get_port"),
    ("GET /actor/" + uuid + "/port/PORT_" + uuid + "/state HTTP/1", uuid, "handle_get_port_state"),
    ("POST /connect HTTP/1", None, "handle_connect"),
    ("POST /set_port_property HTTP/1", None, "handle_set_port_property"),
    ("POST /deploy HTTP/1", None, "handle_deploy"),
    ("POST /application/APP_" + uuid + "/migrate HTTP/1", "APP_" + uuid, "handle_post_application_migrate"),
    ("POST /disconnect HTTP/1", None, "handle_disconnect"),
    ("DELETE /node HTTP/1", None, "handle_quit"),
    ("POST /meter HTTP/1", None, "handle_post_meter"),
    ("DELETE /meter/METERING_" + uuid + " HTTP/1", "METERING_" + uuid, "handle_delete_meter"),
    ("GET /meter/METERING_" + uuid + "/timed HTTP/1", "METERING_" + uuid, "handle_get_timed_meter"),
    ("GET /meter/METERING_" + uuid + "/aggregated HTTP/1", "METERING_" + uuid, "handle_get_aggregated_meter"),
    ("GET /meter/METERING_" + uuid + "/metainfo HTTP/1", "METERING_" + uuid, "handle_get_metainfo_meter"),
    ("POST /index/abc123 HTTP/1", "abc123", "handle_post_index"),
    ("DELETE /index/abc123 HTTP/1", "abc123", "handle_delete_index"),
    ("GET /index/abc123 HTTP/1", "abc123", "handle_get_index"),
    ("GET /storage/abc123 HTTP/1", "abc123", "handle_get_storage"),
    ("POST /storage/abc123 HTTP/1", "abc123", "handle_post_storage"),
    ("OPTIONS /abc123 HTTP/1.1", None, "handle_options")
])
def test_routes_correctly(url, match, handler):
    with patch.object(CalvinControl, handler) as func:
        control = calvincontrol()

        control.route_request(1, 2, url, 3, {})
        assert func.called
        args, kwargs = func.call_args
        assert args[0] == 1
        assert args[1] == 2
        if match:
            assert args[2].group(1) == match
        assert args[3] == {}
        assert args[4] == 3

Example 113

Project: pandas-qt Source File: test_CustomDelegates.py
    @pytest.mark.parametrize(
        "value, singleStep", [
            (numpy.int8(1), 1),
            (numpy.int16(1), 1),
            (numpy.int32(1), 1),
            (numpy.int64(1), 1),
            (numpy.uint8(1), 1),
            (numpy.uint16(1), 1),
            (numpy.uint32(1), 1),
            (numpy.uint64(1), 1),
            (numpy.float16(1.11111), 0.1),
            (numpy.float32(1.11111111), 0.1),
            (numpy.float64(1.1111111111111111), 0.1),
            #(numpy.float128(1.11111111111111111111), 0.1),
        ]
    )
    def test_setDelegates(self, qtbot, tableView, index, value, singleStep):
        dlg = createDelegate(numpy.dtype(value), 0, tableView)
        assert dlg is not None

        data = pandas.DataFrame([value], columns=['A'])
        data['A'] = data['A'].astype(value.dtype)
        model = tableView.model()
        model.setDataFrame(data)
        for i, delegate in enumerate([dlg]):
            assert tableView.itemDelegateForColumn(i) == delegate

            option = QtGui.QStyleOptionViewItem()
            option.rect = QtCore.QRect(0, 0, 100, 100)
            editor = delegate.createEditor(tableView, option, index)
            delegate.setEditorData(editor, index)
            assert editor.value() == index.data()
            delegate.setModelData(editor, model, index)

            delegate.updateEditorGeometry(editor, option, index)

            dtype = value.dtype
            if dtype in DataFrameModel._intDtypes:
                info = numpy.iinfo(dtype)
                assert isinstance(delegate, BigIntSpinboxDelegate)
            elif dtype in DataFrameModel._floatDtypes:
                info = numpy.finfo(dtype)
                assert isinstance(delegate, CustomDoubleSpinboxDelegate)
                assert delegate.decimals == DataFrameModel._float_precisions[str(value.dtype)]
            assert delegate.maximum == info.max
            assert editor.maximum() == info.max
            assert delegate.minimum == info.min
            assert editor.minimum() == info.min
            assert delegate.singleStep == singleStep
            assert editor.singleStep() == singleStep


        def clickEvent(index):
            assert index.isValid()

        tableView.clicked.connect(clickEvent)
        with qtbot.waitSignal(tableView.clicked) as blocker:
            qtbot.mouseClick(tableView.viewport(), QtCore.Qt.LeftButton, pos=QtCore.QPoint(10, 10))
        assert blocker.signal_triggered

Example 114

Project: flask-restplus-server-example Source File: test_models.py
@pytest.mark.parametrize(
    'init_static_roles,is_internal,is_admin,is_regular_user,is_active',
    [
        (_init_static_roles, _is_internal, _is_admin, _is_regular_user, _is_active) \
                for _init_static_roles in (
                    0,
                    (models.User.StaticRoles.INTERNAL.mask
                        | models.User.StaticRoles.ADMIN.mask
                        | models.User.StaticRoles.REGULAR_USER.mask
                        | models.User.StaticRoles.ACTIVE.mask
                    )
                ) \
                    for _is_internal in (False, True) \
                        for _is_admin in (False, True) \
                            for _is_regular_user in (False, True) \
                                for _is_active in (False, True)
    ]
)
def test_User_static_roles_setting(
        init_static_roles,
        is_internal,
        is_admin,
        is_regular_user,
        is_active,
        user_instance
    ):
    """
    Static User Roles are saved as bit flags into one ``static_roles``
    integer field. Ideally, it would be better implemented as a custom field,
    and the plugin would be tested separately, but for now this implementation
    is fine, so we test it as it is.
    """
    user_instance.static_roles = init_static_roles

    if is_internal:
        user_instance.set_static_role(user_instance.StaticRoles.INTERNAL)
    else:
        user_instance.unset_static_role(user_instance.StaticRoles.INTERNAL)

    if is_admin:
        user_instance.set_static_role(user_instance.StaticRoles.ADMIN)
    else:
        user_instance.unset_static_role(user_instance.StaticRoles.ADMIN)

    if is_regular_user:
        user_instance.set_static_role(user_instance.StaticRoles.REGULAR_USER)
    else:
        user_instance.unset_static_role(user_instance.StaticRoles.REGULAR_USER)

    if is_active:
        user_instance.set_static_role(user_instance.StaticRoles.ACTIVE)
    else:
        user_instance.unset_static_role(user_instance.StaticRoles.ACTIVE)

    assert user_instance.has_static_role(user_instance.StaticRoles.INTERNAL) is is_internal
    assert user_instance.has_static_role(user_instance.StaticRoles.ADMIN) is is_admin
    assert user_instance.has_static_role(user_instance.StaticRoles.REGULAR_USER) is is_regular_user
    assert user_instance.has_static_role(user_instance.StaticRoles.ACTIVE) is is_active
    assert user_instance.is_internal is is_internal
    assert user_instance.is_admin is is_admin
    assert user_instance.is_regular_user is is_regular_user
    assert user_instance.is_active is is_active

    if not is_active and not is_regular_user and not is_admin and not is_internal:
        assert user_instance.static_roles == 0

Example 115

Project: pymtl Source File: SimulationTool_transl_test.py
@pytest.mark.parametrize('num', range(8) )
def test_translation_reverse_iter( setup_sim, num ):

  class TestTranslationReverseIter( Model ):
    def __init__( s, num ):
      s.in_ = InPort ( 8 )
      s.out = OutPort( 8 )

      if num == 0:
        @s.combinational
        def logic0():
          for i in range( 8 ):
            s.out[i].value = s.in_[i]

      elif num == 1:
        @s.combinational
        def logic0():
          for i in range( 0, 8, 2 ):
            s.out[i].value = s.in_[i]
          for i in range( 1, 8, 2 ):
            s.out[i].value = s.in_[i]

      elif num == 2:
        @s.combinational
        def logic0():
          for i in xrange( 8 ):
            s.out[i].value = s.in_[i]

      elif num == 3:
        @s.combinational
        def logic0():
          for i in xrange( 0, 8, 2 ):
            s.out[i].value = s.in_[i]
          for i in xrange( 1, 8, 2 ):
            s.out[i].value = s.in_[i]

      elif num == 4:
        @s.combinational
        def logic0():
          for i in range( 7,-1,-1 ):
            s.out[i].value = s.in_[i]

      elif num == 5:
        @s.combinational
        def logic0():
          for i in range( 7, -1, -2 ):
            s.out[i].value = s.in_[i]
          for i in range( 6, -1, -2 ):
            s.out[i].value = s.in_[i]

      elif num == 6:
        step = 1
        @s.combinational
        def logic0():
          for i in range( 0,8,step ):
            s.out[i].value = s.in_[i]

      elif num == 7:
        step = -1
        @s.combinational
        def logic0():
          for i in range( 7,-1,step ):
            s.out[i].value = s.in_[i]

      else:
        raise Exception('Invalid Configuration!')

  n = 4
  m, sim = setup_sim( TestTranslationReverseIter(num) )
  for i in range(10):
    k = Bits(n,randrange(0,2**n))
    m.in_.value = k
    sim.cycle()
    assert m.out == k

Example 116

Project: memegen Source File: test_domain_template.py
def describe_template():

    def it_supports_comparison():
        t1 = Template('abc', "A Thing")
        t2 = Template('def')
        t3 = Template('def', "Do This")

        assert t1 != t2
        assert t2 == t3
        assert t1 < t3

    def describe_get_path():

        @patch('pathlib.Path.is_file', Mock(return_value=True))
        def it_returns_default_when_no_style(template):
            expect(template.get_path()) == Path("abc/default.png")

        @patch('pathlib.Path.is_file', Mock(return_value=True))
        def it_returns_alternate_when_style_provided(template):
            expect(template.get_path('Custom')) == Path("abc/custom.png")

        @patch('pathlib.Path.is_file', Mock(return_value=True))
        def it_returns_default_when_style_is_none(template):
            expect(template.get_path(None)) == Path("abc/default.png")

        @patch('pathlib.Path.is_file', Mock(return_value=False))
        def it_considers_urls_valid_styles(template):
            url = "http://example.com"
            path = temp("a9b9f04336ce0181a08e774e01113b31")
            expect(template.get_path(url)) == path

        @patch('pathlib.Path.is_file', Mock(return_value=True))
        def it_caches_file_downloads(template):
            url = "http://this/will/be/ignored"
            path = temp("d888710f0697650eb68fc9dcbb976d4c")
            expect(template.get_path(url)) == path

        def it_handles_bad_urls(template):
            expect(template.get_path("http://invalid")) == None

        def it_handles_invalid_paths(template):
            expect(template.get_path("@#$%^")) == None

    def describe_path():

        def is_returned_when_file_exists(template):
            template.root = "my_root"

            with patch('pathlib.Path.is_file', Mock(return_value=True)):
                path = template.path

            expect(path) == Path("my_root/abc/default.png")

        def is_none_when_no_file(template):
            template.root = "my_root"

            with patch('pathlib.Path.is_file', Mock(return_value=False)):
                path = template.path

            expect(path) == None

    def describe_default_path():

        def is_based_on_lines(template):
            expect(template.default_path) == "foo/bar"

        def is_underscore_when_no_lines(template):
            template.lines = []

            expect(template.default_path) == "_"

    def describe_styles():

        @patch('os.listdir', Mock(return_value=[]))
        def is_empty_when_no_alternate_images(template):
            expect(template.styles) == []

        @patch('os.listdir', Mock(return_value=['foo.jpg', 'bar.png']))
        def is_filesnames_of_alternate_images(template):
            expect(template.styles) == ['bar', 'foo']

    def describe_sample_path():

        def is_based_on_lines(template):
            expect(template.sample_path) == "foo/bar"

        def is_placeholder_when_no_lines(template):
            template.lines = []

            expect(template.sample_path) == "your-text/goes-here"

    def describe_match():

        def it_returns_none_when_no_match(template):
            expect(template.match("")) == (0, None)

        def it_returns_the_best_matching_result(template):
            template.compile_regexes([r"(\w*)/?(abc)", r"(\w*)/?(def)"])

            expect(template.match("_/def")) == (0.42, "_/def")

    def describe_validate_meta():

        def with_no_name(template):
            template.name = None

            expect(template.validate_meta()) == False

        def with_no_default_image(template):
            expect(template.validate_meta()) == False

        def with_nonalphanumberic_name(template):
            template.name = "'ABC' Meme"

            expect(template.validate_meta()) == False

    def describe_validate_link():

        def with_bad_link(template):
            mock_response = Mock()
            mock_response.status_code = 404

            with patch('requests.head', Mock(return_value=mock_response)):
                template.link = "example.com/fake"

                expect(template.validate_link()) == False

        @patch('pathlib.Path.is_file', Mock(return_value=True))
        def with_cached_valid_link(template):
            template.link = "already_cached_site.com"

            expect(template.validate_link()) == True

    def describe_validate_size():

        @pytest.mark.parametrize('dimensions,valid', [
            ((Template.MIN_WIDTH, Template.MIN_HEIGHT), True),
            ((Template.MIN_WIDTH - 1, Template.MIN_HEIGHT), False),
            ((Template.MIN_WIDTH, Template.MIN_HEIGHT - 1), False),
            ((Template.MIN_WIDTH - 1, Template.MIN_HEIGHT - 1), False),
        ])
        @patch('PIL.Image.open')
        def with_various_dimenions(mock_open, template, dimensions, valid):
            mock_img = Mock()
            mock_img.size = dimensions
            mock_open.return_value = mock_img

            expect(template.validate_size()) == valid

    def describe_validate_regexes():

        def with_missing_split(template):
            template.compile_regexes([".*"])

            expect(template.validate_regexes()) == False

    def describe_validate():

        def with_no_validators(template):
            expect(template.validate([])) == True

        def with_all_passing_validators(template):
            """Verify a template is valid if all validators pass."""
            mock_validators = [lambda: True]

            expect(template.validate(validators=mock_validators)) == True

        def with_one_failing_validator(template):
            """Verify a template is invalid if any validators fail."""
            mock_validators = [lambda: False]

            expect(template.validate(validators=mock_validators)) == False

Example 117

Project: astrodendro Source File: test_structure.py
@pytest.mark.parametrize('index', [[(0,), (1,), (2,)],
                                   [(1, 3), (2, 2), (4, 1)],
                                   [(4, 5, 9), (3, 2, 1), (6, 7, 8)]])
def test_init_branch_list_3_level(index):

    ndim = len(index[0])

    leaf_index = tuple([10 for i in range(ndim)])
    leaf = Structure(leaf_index, 20.)
    leaf_indices = leaf.indices(subtree=False)

    branch_index = tuple([9 for i in range(ndim)])
    branch = Structure(branch_index, 15., children=[leaf])
    branch_indices = branch.indices(subtree=False)

    s = Structure(index, [3.1, 4.2, 5.3], children=[branch])

    # Properties
    assert s.idx is None
    assert not s.is_leaf
    assert s.is_branch

    indices = tuple(np.atleast_1d(i) for i in zip(*index))
    indices_all = tuple(np.hstack(a) for a in
                        zip(indices, branch_indices, leaf_indices))
    assert_identical_fancyindex(s.indices(subtree=False), indices)
    assert_identical_fancyindex(s.indices(subtree=True), indices_all)

    assert np.all(s.values(subtree=False) == np.array([3.1, 4.2, 5.3]))
    assert np.all(s.values(subtree=True) == np.hstack((s.values(subtree=False), branch.values(subtree=False), leaf.values(subtree=False))))
    assert s.vmin == 3.1
    assert s.vmax == 5.3
    assert s.height == 15.
    assert s.level == 0
    assert s.ancestor is s
    assert s.parent is None
    assert s.children == [branch]
    assert s.descendants == [branch, leaf]

    # Branch properties
    assert branch.level == 1
    assert branch.ancestor is s
    assert branch.parent is s
    assert branch.children == [leaf]
    assert branch.descendants == [leaf]

    # Leaf properties
    assert leaf.level == 2
    assert leaf.ancestor is s
    assert leaf.parent is branch
    assert leaf.children == []
    assert leaf.descendants == []

    # Methods
    assert s.get_npix(subtree=False) == 3
    assert s.get_peak(subtree=False) == (index[2], 5.3)
    assert s.get_npix(subtree=True) == 5
    assert s.get_peak(subtree=True) == (leaf_index, 20.)

    # Footprint
    array = np.zeros([20 for i in range(ndim)])
    s._fill_footprint(array, level=2)
    for i in index:
        assert array[i] == 2.
    assert array[branch_index] == 3.
    assert array[leaf_index] == 4.
    assert np.sum(array) == 13.

Example 118

Project: instaseis Source File: test_server_finite_source.py
@pytest.mark.parametrize("usgs_param", [USGS_PARAM_FILE_1, USGS_PARAM_FILE_2])
def test_finite_source_retrieval(reciprocal_clients, usgs_param):
    """
    Tests if the finite sources requested from the server are identical to
    the one requested with the local instaseis client with some required
    tweaks.
    """
    client = reciprocal_clients

    db = instaseis.open_db(client.filepath)

    basic_parameters = {
        "receiverlongitude": 11,
        "receiverlatitude": 22,
        "receiverdepthinmeters": 0,
        "format": "miniseed"}

    with io.open(usgs_param, "rb") as fh:
        body = fh.read()

    # default parameters
    params = copy.deepcopy(basic_parameters)
    request = client.fetch(_assemble_url('finite_source', **params),
                           method="POST", body=body)
    assert request.code == 200
    st_server = obspy.read(request.buffer)
    for tr in st_server:
        assert tr.stats._format == "MSEED"

    # Parse the finite source.
    fs = _parse_finite_source(usgs_param)
    rec = instaseis.Receiver(latitude=22, longitude=11, network="XX",
                             station="SYN", location="SE")

    st_db = db.get_seismograms_finite_source(sources=fs, receiver=rec)
    # The origin time is the time of the first sample in the route.
    for tr in st_db:
        # Cut away the first ten samples as they have been previously added.
        tr.data = tr.data[10:]
        tr.stats.starttime = obspy.UTCDateTime(1900, 1, 1)

    for tr_db, tr_server in zip(st_db, st_server):
        # Sample spacing is very similar but not equal due to floating point
        # accuracy.
        np.testing.assert_allclose(tr_server.stats.delta, tr_db.stats.delta)
        tr_server.stats.delta = tr_db.stats.delta
        del tr_server.stats._format
        del tr_server.stats.mseed

        assert tr_db.stats == tr_server.stats
        np.testing.assert_allclose(tr_db.data, tr_server.data)

    # Once again but this time request a SAC file.
    params = copy.deepcopy(basic_parameters)
    params["format"] = "saczip"
    request = client.fetch(_assemble_url('finite_source', **params),
                           method="POST", body=body)
    assert request.code == 200
    st_server = obspy.Stream()
    zip_obj = zipfile.ZipFile(request.buffer)
    for name in zip_obj.namelist():
        st_server += obspy.read(io.BytesIO(zip_obj.read(name)))
    for tr in st_server:
        assert tr.stats._format == "SAC"

    for tr_db, tr_server in zip(st_db, st_server):
        # Sample spacing is very similar but not equal due to floating point
        # accuracy.
        np.testing.assert_allclose(tr_server.stats.delta, tr_db.stats.delta)
        tr_server.stats.delta = tr_db.stats.delta
        del tr_server.stats._format
        del tr_server.stats.sac

        assert tr_db.stats == tr_server.stats
        np.testing.assert_allclose(tr_db.data, tr_server.data)

    # One with a label.
    params = copy.deepcopy(basic_parameters)
    params["label"] = "random_things"
    request = client.fetch(_assemble_url('finite_source', **params),
                           method="POST", body=body)
    assert request.code == 200

    cd = request.headers["Content-Disposition"]
    assert cd.startswith("attachment; filename=random_things_")
    assert cd.endswith(".mseed")

    # One simulating a crash in the underlying function.
    params = copy.deepcopy(basic_parameters)

    with mock.patch("instaseis.database_interfaces.base_instaseis_db"
                    ".BaseInstaseisDB.get_seismograms_finite_source") as p:
        p.side_effect = ValueError("random crash")
        request = client.fetch(_assemble_url('finite_source', **params),
                               method="POST", body=body)

    assert request.code == 400
    assert request.reason == ("Could not extract finite source seismograms. "
                              "Make sure, the parameters are valid, and the "
                              "depth settings are correct.")

    # Simulating a logic error that should not be able to happen.
    params = copy.deepcopy(basic_parameters)
    with mock.patch("instaseis.database_interfaces.base_instaseis_db"
                    ".BaseInstaseisDB.get_seismograms_finite_source") as p:
        # Longer than the database returned stream thus the endtime is out
        # of bounds.
        st = obspy.read()

        p.return_value = st
        request = client.fetch(_assemble_url('finite_source', **params),
                               method="POST", body=body)

    assert request.code == 500
    assert request.reason.startswith("Endtime larger than the extracted "
                                     "endtime")

    # One more with resampling parameters and different units.
    params = copy.deepcopy(basic_parameters)
    # We must have a sampling rate that cleanly fits in the existing one,
    # otherwise we cannot fake the cutting.
    dt_new = 24.724845445855724 / 10
    params["dt"] = dt_new
    params["kernelwidth"] = 2
    params["units"] = "acceleration"

    st_db = db.get_seismograms_finite_source(sources=fs, receiver=rec,
                                             dt=dt_new, kernelwidth=2,
                                             kind="acceleration")
    # The origin time is the time of the first sample in the route.
    for tr in st_db:
        # Cut away the first ten samples as they have been previously added.
        tr.data = tr.data[100:]
        tr.stats.starttime = obspy.UTCDateTime(1900, 1, 1)

    request = client.fetch(_assemble_url('finite_source', **params),
                           method="POST", body=body)
    assert request.code == 200
    st_server = obspy.read(request.buffer)

    # Cut some parts in the middle to avoid any potential boundary effects.
    st_db.trim(obspy.UTCDateTime(1900, 1, 1, 0, 4),
               obspy.UTCDateTime(1900, 1, 1, 0, 14))
    st_server.trim(obspy.UTCDateTime(1900, 1, 1, 0, 4),
                   obspy.UTCDateTime(1900, 1, 1, 0, 14))

    for tr_db, tr_server in zip(st_db, st_server):
        # Sample spacing and times are very similar but not identical due to
        # floating point inaccuracies in the arithmetics.
        np.testing.assert_allclose(tr_server.stats.delta, tr_db.stats.delta)
        np.testing.assert_allclose(tr_server.stats.starttime.timestamp,
                                   tr_db.stats.starttime.timestamp)
        tr_server.stats.delta = tr_db.stats.delta
        tr_server.stats.starttime = tr_db.stats.starttime
        del tr_server.stats._format
        del tr_server.stats.mseed
        del tr_server.stats.processing
        del tr_db.stats.processing

        np.testing.assert_allclose(tr_server.stats.delta, tr_db.stats.delta)

        assert tr_db.stats == tr_server.stats
        np.testing.assert_allclose(tr_db.data, tr_server.data,
                                   rtol=1E-7, atol=tr_db.data.ptp() * 1E-7)

    # Testing network and station code parameters.
    # Default values.
    params = copy.deepcopy(basic_parameters)
    request = client.fetch(_assemble_url('finite_source', **params),
                           method="POST", body=body)
    assert request.code == 200
    st_server = obspy.read(request.buffer)
    for tr in st_server:
        assert tr.stats.network == "XX"
        assert tr.stats.station == "SYN"
        assert tr.stats.location == "SE"

    # Setting all three.
    params = copy.deepcopy(basic_parameters)
    params["networkcode"] = "AA"
    params["stationcode"] = "BB"
    params["locationcode"] = "CC"
    request = client.fetch(_assemble_url('finite_source', **params),
                           method="POST", body=body)
    assert request.code == 200
    st_server = obspy.read(request.buffer)
    for tr in st_server:
        assert tr.stats.network == "AA"
        assert tr.stats.station == "BB"
        assert tr.stats.location == "CC"

    # Setting only the location code.
    params = copy.deepcopy(basic_parameters)
    params["locationcode"] = "AA"
    request = client.fetch(_assemble_url('finite_source', **params),
                           method="POST", body=body)
    assert request.code == 200
    st_server = obspy.read(request.buffer)
    for tr in st_server:
        assert tr.stats.network == "XX"
        assert tr.stats.station == "SYN"
        assert tr.stats.location == "AA"

    # Test the scale parameter.
    params = copy.deepcopy(basic_parameters)
    params["scale"] = 33.33
    request = client.fetch(_assemble_url('finite_source', **params),
                           method="POST", body=body)
    assert request.code == 200
    st_server = obspy.read(request.buffer)
    for tr in st_server:
        assert tr.stats._format == "MSEED"

    # Parse the finite source.
    fs = _parse_finite_source(usgs_param)
    rec = instaseis.Receiver(latitude=22, longitude=11, network="XX",
                             station="SYN", location="SE")

    st_db = db.get_seismograms_finite_source(sources=fs, receiver=rec)
    # The origin time is the time of the first sample in the route.
    for tr in st_db:
        # Multiply with scale parameter.
        tr.data *= 33.33
        # Cut away the first ten samples as they have been previously added.
        tr.data = tr.data[10:]
        tr.stats.starttime = obspy.UTCDateTime(1900, 1, 1)

    for tr_db, tr_server in zip(st_db, st_server):
        # Sample spacing is very similar but not equal due to floating point
        # accuracy.
        np.testing.assert_allclose(tr_server.stats.delta, tr_db.stats.delta)
        tr_server.stats.delta = tr_db.stats.delta
        del tr_server.stats._format
        del tr_server.stats.mseed

        assert tr_db.stats == tr_server.stats
        np.testing.assert_allclose(tr_db.data, tr_server.data,
                                   atol=1E-6 * tr_db.data.ptp())

Example 119

Project: SmokeDetector Source File: test_regexes.py
Function: test_regexes
@pytest.mark.parametrize("title, body, username, site, body_is_summary, match", [
    ('18669786819 gmail customer service number 1866978-6819 gmail support number', '', '', '', False, True),
    ('18669786819 gmail customer service number 1866978-6819 gmail support number', '', '', '', True, True),
    ('Is there any http://www.hindawi.com/ template for Cloud-Oriented Data Center Networking?', '', '', '', False, True),
    ('', '', 'bagprada', '', False, True),
    ('12 Month Loans quick @ http://www.quick12monthpaydayloans.co.uk/Elimination of collateral pledging', '', '', '', False, True),
    ('support for yahoo mail 18669786819 @call for helpline number', '', '', '', False, True),
    ('yahoo email tech support 1 866 978 6819 Yahoo Customer Phone Number ,Shortest Wait', '', '', '', False, True),
    ('kkkkkkkkkkkkkkkkkkkkkkkkkkkk', '<p>bbbbbbbbbbbbbbbbbbbbbb</p>', '', 'stackoverflow.com', False, True),
    ('Yay titles!', 'bbbbbbbbbbbabcdefghijklmnop', '', 'stackoverflow.com', False, True),
    ('kkkkkkkkkkkkkkkkkkkkkkkkkkkk', 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbb', '', 'stackoverflow.com', True, True),
    ('99999999999', '', '', 'stackoverflow.com', False, True),
    ('Spam spam spam', '', 'babylisscurl', 'stackoverflow.com', False, True),
    ('Question', '111111111111111111111111111111111111', '', 'stackoverflow.com', False, True),
    ('Question', 'I have this number: 111111111111111', '', 'stackoverflow.com', False, False),
    ('Random title', '$$$$$$$$$$$$', '', 'superuser.com', False, True),
    ('Enhance SD Male Enhancement Supplements', '', '', '', False, True),
    ('Title here', '111111111111111111111111111111111111', '', 'communitybuilding.stackexchange.com', False, True),
    ('Gmail Tech Support (1-844-202-5571) Gmail tech support number[Toll Free Number]?', '', '', 'stackoverflow.com', False, True),
    ('<>1 - 866-978-6819<>gmail password reset//gmail contact number//gmail customer service//gmail help number', '', '', 'stackoverflow.com', False, True),
    ('Hotmail technical support1 - 844-780-67 62 telephone number Hotmail support helpline number', '', '', 'stackoverflow.com', False, True),
    ('Valid title', 'Hotmail technical support1 - 844-780-67 62 telephone number Hotmail support helpline number', '', 'stackoverflow.com', True, True),
    ('[[[[[1-844-202-5571]]]]]Gmail Tech support[*]Gmail tech support number', '', '', 'stackoverflow.com', False, True),
    ('@@<>1 -866-978-6819 FREE<><><::::::@Gmail password recovery telephone number', '', '', 'stackoverflow.com', False, True),
    ('1 - 844-780-6762 outlook password recovery number-outlook password recovery contact number-outlook password recovery helpline number', '', '', 'stackoverflow.com', False, True),
    ('hotmail customer <*<*<*[*[ 1 - 844-780-6762 *** support toll free number Hotmail Phone Number hotmail account recovery phone number', '', '', 'stackoverflow.com', False, True),
    ('1 - 844-780-6762 outlook phone number-outlook telephone number-outlook customer care helpline number', '', '', 'stackoverflow.com', False, True),
    ('Repeating word word word word word word word word word', '', '', 'stackoverflow.com', False, True),
    ('Visit this website: optimalstackfacts.net', '', '', 'stackoverflow.com', False, True),
    ('his email address is ([email protected])', '', '', 'money.stackexchange.com', False, True),
    ('something', 'his email address is ([email protected])', '', 'money.stackexchange.com', False, True),
    ('asdf asdf asdf asdf asdf asdf asdf asdf', '', '', 'stackoverflow.com', True, True),
    ('A title', '>>>>  http://', '', 'stackoverflow.com', False, True),
    ('', '<p>Test <a href="http://example.com/" rel="nofollow">some text</a> moo moo moo.</p><p>Another paragraph. Make it long enough to bring this comfortably over the 300-character limit. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p><p><a href="http://example.com/" rel="nofollow">http://example.com/</a></p>', '', 'stackoverflow.com', False, True),
    ('spam', '>>>> http://', '', 'stackoverflow.com', True, False),
    ('Another title', '<code>>>>>http://</code>', '', 'stackoverflow.com', False, False),
    ('This asdf should asdf not asdf be asdf matched asdf because asdf the asdf words do not asdf follow on each asdf other.', '', '', 'stackoverflow.com', False, False),
    ('What is the value of MD5 checksums if the MD5 hash itself could potentially also have been manipulated?', '', '', '', False, False),
    ('Probability: 6 Dice are rolled. Which is more likely, that you get exactly one 6, or that you get 6 different numbers?', '', '', '', False, False),
    ('The Challenge of Controlling a Powerful AI', '', 'Serban Tanasa', '', False, False),
    ('Reproducing image of a spiral using TikZ', '', 'Kristoffer Ryhl', '', False, False),
    ('What is the proper way to say "queryer"', '', 'jedwards', '', False, False),
    ('What\'s a real-world example of "overfitting"?', '', 'user3851283', '', False, False),
    ('How to avoid objects when traveling at greater than .75 light speed. or How Not to Go SPLAT?', '', 'bowlturner', '', False, False),
    ('Is it unfair to regrade prior work after detecting cheating?', '', 'Village', '', False, False),
    ('Inner workings of muscles', '', '', 'fitness.stackexchange.com', False, False),
    ('Cannot access http://stackoverflow.com/ with proxy enabled', '', '', 'superuser.com', False, False),
    ('This is a title.', 'This is a body.<pre>bbbbbbbbbbbbbb</pre>', '', 'stackoverflow.com', False, False),
    ('This is another title.', 'This is another body. <code>bbbbbbbbbbbb</code>', '', 'stackoverflow.com', False, False),
    ('Yet another title.', 'many whitespace             .', '', 'stackoverflow.com', False, False),
    ('Perfectly valid title.', 'bbbbbbbbbbbbbbbbbbbbbb', '', 'stackoverflow.com', True, False),
    ('Yay titles!', 'bbbbbbbbbbbabcdefghijklmnopqrstuvwxyz123456789a1b2c3d4e5', '', 'stackoverflow.com', False, False),
    ('Long double', 'I have this value: 9999999999999999', '', 'stackoverflow.com', False, False),
    ('Another valid title.', 'asdf asdf asdf asdf asdf asdf asdf asdf asdf', '', 'stackoverflow.com', True, False),
    ('Array question', 'I have an array with these values: 10 10 10 10 10 10 10 10 10 10 10 10', '', 'stackoverflow.com', False, False),
    ('Array question', 'I have an array with these values: 0 0 0 0 0 0 0 0 0 0 0 0', '', 'stackoverflow.com', False, False),
    ('his email address is ([email protected])', '', '', 'stackoverflow.com', False, False),
    ('something', 'his email address is ([email protected])', '', 'stackoverflow.com', False, False),
    ('something', 'URL: &[email protected]', '', 'meta.stackexchange.com', False, False),
    ('random title', 'URL: page.html#[email protected]', '', 'rpg.stackexchange.com', False, False),
    (u'Как рандомно получать числа 1 и 2?', u'Текст вопроса с кодом <code>a = b + 1</code>', u'Сашка', 'ru.stackoverflow.com', False, False),
    ('Should not be caught: http://example.com', '', '', 'drupal.stackexchange.com', False, False),
    ('Should not be caught: https://www.example.com', '', '', 'drupal.stackexchange.com', False, False),
    ('Should not be caught: [email protected]', '', '', 'drupal.stackexchange.com', False, False),
    ('Title here', '<img src="http://example.com/11111111111.jpg" alt="my image">', '', 'stackoverflow.com', False, False),
    ('Title here', '<img src="http://example.com/11111111111111.jpg" alt="my image" />', '', 'stackoverflow.com', False, False),
    ('Title here', '<a href="http://example.com/11111111111111.html">page</a>', '', 'stackoverflow.com', False, False),
    ('Error: 2147467259', '', '', 'stackoverflow.com', False, False)
])
def test_regexes(title, body, username, site, body_is_summary, match):
    # If we want to test answers separately, this should be changed
    is_answer = False
    result = FindSpam.test_post(title, body, username, site, is_answer, body_is_summary, 1, 0)[0]
    print title
    print result
    isspam = False
    if len(result) > 0:
        isspam = True
    assert match == isspam

Example 120

Project: ktbs Source File: test_rdfrest_utils_prefix_conjunctive_view.py
    @mark.parametrize("datasetname, triple_or_quad, expected", [
                ('p12', (EX.x1, EX.p, EX.x2), {(EX.x1, EX.p, EX.x2, EX['g1/'])}),
                ('p12', (EX.x2, EX.p, EX.x3), {(EX.x2, EX.p, EX.x3, EX['g1/g2'])}),
                ('p12', (EX.x3, EX.p, EX.x4), {(EX.x3, EX.p, EX.x4, EX['g1/g2'])}),
                ('p12', (EX.xa, EX.p, EX.xb), set()),
                ('p12', (EX.xb, EX.p, EX.xc), set()),
                ('p12', (EX.x0, EX.p, EX.xc), set()),

                ('pab', (EX.x1, EX.p, EX.x2), set()),
                ('pab', (EX.x2, EX.p, EX.x3), set()),
                ('pab', (EX.x3, EX.p, EX.x4), set()),
                ('pab', (EX.xa, EX.p, EX.xb), {(EX.xa, EX.p, EX.xb, EX['pab/ga'])}),
                ('pab', (EX.xb, EX.p, EX.xc), {(EX.xb, EX.p, EX.xc, EX['pab/gb'])}),
                ('pab', (EX.x0, EX.p, EX.xc), set()),

                ('p12', (EX.x1, EX.p, EX.x2, EX['g1/']), {(EX.x1, EX.p, EX.x2, EX['g1/'])}),
                ('p12', (EX.x1, EX.p, EX.x2, EX['g1/g2']), set()),
                ('p12', (EX.x2, EX.p, EX.x3, EX['g1/']), set()),
                ('p12', (EX.x2, EX.p, EX.x3, EX['g1/g2']), {(EX.x2, EX.p, EX.x3, EX['g1/g2'])}),
                ('p12', (EX.x3, EX.p, EX.x4, EX['g1/']), set()),
                ('p12', (EX.x3, EX.p, EX.x4, EX['g1/g2']), {(EX.x3, EX.p, EX.x4, EX['g1/g2'])}),
                ('p12', (EX.xa, EX.p, EX.xb, EX['pab/ga']), set()),
                ('p12', (EX.xa, EX.p, EX.xb, EX['pab/gb']), set()),
                ('p12', (EX.xb, EX.p, EX.xc, EX['pab/ga']), set()),
                ('p12', (EX.xb, EX.p, EX.xc, EX['pab/gb']), set()),

                ('pab', (EX.x1, EX.p, EX.x2, EX['g1/']), set()),
                ('pab', (EX.x1, EX.p, EX.x2, EX['g1/g2']), set()),
                ('pab', (EX.x2, EX.p, EX.x3, EX['g1/']), set()),
                ('pab', (EX.x2, EX.p, EX.x3, EX['g1/g2']), set()),
                ('pab', (EX.x3, EX.p, EX.x4, EX['g1/']), set()),
                ('pab', (EX.x3, EX.p, EX.x4, EX['g1/g2']), set()),
                ('pab', (EX.xa, EX.p, EX.xb, EX['pab/ga']), {(EX.xa, EX.p, EX.xb, EX['pab/ga'])}),
                ('pab', (EX.xa, EX.p, EX.xb, EX['pab/gb']), set()),
                ('pab', (EX.xb, EX.p, EX.xc, EX['pab/ga']), set()),
                ('pab', (EX.xb, EX.p, EX.xc, EX['pab/gb']), {(EX.xb, EX.p, EX.xc, EX['pab/gb'])}),

                ('p12', (EX.x1, None, None), {(EX.x1, EX.p, EX.x2, EX['g1/'])}),
                ('p12', (EX.x2, None, None), {(EX.x2, EX.p, EX.x3, EX['g1/g2'])}),
                ('p12', (EX.x3, None, None), {(EX.x3, EX.p, EX.x4, EX['g1/g2'])}),
                ('p12', (EX.xa, None, None), set()),
                ('p12', (EX.xb, None, None), set()),
                ('p12', (EX.x0, None, None), set()),

                ('pab', (EX.x1, None, None), set()),
                ('pab', (EX.x2, None, None), set()),
                ('pab', (EX.x3, None, None), set()),
                ('pab', (EX.xa, None, None), {(EX.xa, EX.p, EX.xb, EX['pab/ga'])}),
                ('pab', (EX.xb, None, None), {(EX.xb, EX.p, EX.xc, EX['pab/gb'])}),
                ('pab', (EX.x0, None, None), set()),

                ('p12', (EX.x1, None, None, EX['g1/']), {(EX.x1, EX.p, EX.x2, EX['g1/'])}),
                ('p12', (EX.x1, None, None, EX['g1/g2']), set()),
                ('p12', (EX.x2, None, None, EX['g1/']), set()),
                ('p12', (EX.x2, None, None, EX['g1/g2']), {(EX.x2, EX.p, EX.x3, EX['g1/g2'])}),
                ('p12', (EX.x3, None, None, EX['g1/']), set()),
                ('p12', (EX.x3, None, None, EX['g1/g2']), {(EX.x3, EX.p, EX.x4, EX['g1/g2'])}),
                ('p12', (EX.xa, None, None, EX['pab/ga']), set()),
                ('p12', (EX.xa, None, None, EX['pab/gb']), set()),
                ('p12', (EX.xb, None, None, EX['pab/ga']), set()),
                ('p12', (EX.xb, None, None, EX['pab/gb']), set()),

                ('pab', (EX.x1, None, None, EX['g1/']), set()),
                ('pab', (EX.x1, None, None, EX['g1/g2']), set()),
                ('pab', (EX.x2, None, None, EX['g1/']), set()),
                ('pab', (EX.x2, None, None, EX['g1/g2']), set()),
                ('pab', (EX.x3, None, None, EX['g1/']), set()),
                ('pab', (EX.x3, None, None, EX['g1/g2']), set()),
                ('pab', (EX.xa, None, None, EX['pab/ga']), {(EX.xa, EX.p, EX.xb, EX['pab/ga'])}),
                ('pab', (EX.xa, None, None, EX['pab/gb']), set()),
                ('pab', (EX.xb, None, None, EX['pab/ga']), set()),
                ('pab', (EX.xb, None, None, EX['pab/gb']), {(EX.xb, EX.p, EX.xc, EX['pab/gb'])}),

                ('p12', (None, None, None), {(EX.x1, EX.p, EX.x2, EX['g1/']),
                                             (EX.x2, EX.p, EX.x3, EX['g1/g2']),
                                             (EX.x3, EX.p, EX.x4, EX['g1/g2']),
                }),
                ('pab', (None, None, None), {(EX.xa, EX.p, EX.xb, EX['pab/ga']),
                                             (EX.xb, EX.p, EX.xc, EX['pab/gb']),
                }),

                ('p12', (None, None, None, EX['g1/']), {
                    (EX.x1, EX.p, EX.x2, EX['g1/']),
                }),
                ('p12', (None, None, None, EX['g1/g2']), {
                    (EX.x2, EX.p, EX.x3, EX['g1/g2']),
                    (EX.x3, EX.p, EX.x4, EX['g1/g2']),
                }),
                ('p12', (None, None, None, EX['pab/ga']), {
                }),

                ('pab', (None, None, None, EX['pab/ga']), {
                    (EX.xa, EX.p, EX.xb, EX['pab/ga']),
                }),
                ('pab', (None, None, None, EX['pab/gb']), {
                    (EX.xb, EX.p, EX.xc, EX['pab/gb']),
                }),
                ('pab', (None, None, None, EX['g1/']), {
                }),
    ])
    def test_quads(self, datasetname, triple_or_quad, expected):
        dataset = getattr(self, datasetname)
        quads = set( (s, p, o, ctx.identifier)
                     for s, p, o, ctx
                     in dataset.quads(triple_or_quad)
        )
        assert quads == set(expected)

Example 121

Project: libearth Source File: schema_test.py
@mark.parametrize(('element', 'recur_valid', 'valid'), [
    (VTDoc(), False, False),
    (VTDoc(req_attr='a'), False, False),
    (VTDoc(req_child=VTElement()), False, False),
    (VTDoc(req_text='f'), False, False),
    (VTDoc(req_child=VTElement(req_attr='a')), False, False),
    (VTDoc(req_child=VTElement(req_child=TextElement(value='a'))),
     False, False),
    (VTDoc(req_child=VTElement(req_attr='a',
                               req_child=TextElement(value='a'))),
     False, False),
    (VTDoc(req_child=VTElement(req_attr='a',
                               req_child=TextElement(value='a'),
                               req_text='e')),
     False, False),
    (VTDoc(req_attr='a', req_child=VTElement(), req_text='f'), False, True),
    (VTDoc(req_attr='a', req_child=VTElement(), multi=[], req_text='f'),
     False, True),
    (VTDoc(req_attr='a', req_child=VTElement(), multi=[
        VTElement()
    ], req_text='f'), False, True),
    (VTDoc(req_attr='a', req_child=VTElement(), multi=[
        VTElement(req_attr='a', req_child=TextElement(value='a'))
    ], req_text='f'), False, True),
    (VTDoc(req_attr='a', req_child=VTElement(req_attr='a'), req_text='f'),
     False, True),
    (VTDoc(req_attr='a', req_child=VTElement(req_attr='a'),
           multi=[], req_text='f'), False, True),
    (VTDoc(req_attr='a',
           req_child=VTElement(req_child=TextElement(value='a')),
           multi=[], req_text='f'), False, True),
    (VTDoc(req_attr='a',
           req_child=VTElement(req_attr='a',
                               req_child=TextElement(value='a'),
                               req_text='e'),
           multi=[], req_text='f'), True, True),
    (VTDoc(req_attr='a',
           req_child=VTElement(req_attr='a',
                               req_child=TextElement(value='a'),
                               req_text='e'),
           multi=[VTElement()], req_text='f'), False, True),
    (VTDoc(req_attr='a',
           req_child=VTElement(req_attr='a',
                               req_child=TextElement(value='a'),
                               req_text='e'),
           multi=[VTElement(req_attr='a',
                            req_child=TextElement(value='a'),
                            req_text='e')],
           req_text='f'), True, True)
])
def test_validate_recurse(element, recur_valid, valid):
    assert validate(element, recurse=True, raise_error=False) is recur_valid
    try:
        validate(element, recurse=True, raise_error=True)
    except IntegrityError:
        assert not recur_valid
    else:
        assert recur_valid
    assert validate(element, recurse=False, raise_error=False) is valid
    try:
        validate(element, recurse=False, raise_error=True)
    except IntegrityError:
        assert not valid
    else:
        assert valid
    try:
        for _ in write(element):
            pass
    except IntegrityError:
        assert not recur_valid
    else:
        assert recur_valid

Example 122

Project: cabby Source File: test_common.py
@pytest.mark.parametrize("version", [11, 10])
def test_jwt_auth_response(version):

    httpretty.reset()
    httpretty.enable()

    jwt_path = '/management/auth/'
    jwt_url = 'http://{}{}'.format(get_fix(version).HOST, jwt_path)

    token = 'dummy'
    username = 'dummy-username'
    password = 'dummy-password'

    def jwt_request_callback(request, uri, headers):
        body = json.loads(request.body.decode('utf-8'))

        assert body['username'] == username
        assert body['password'] == password

        return 200, headers, json.dumps({'token': token})

    httpretty.register_uri(
        httpretty.POST,
        jwt_url,
        body=jwt_request_callback,
        content_type='application/json'
    )
    discovery_uri = get_fix(version).DISCOVERY_URI_HTTP

    register_uri(
        discovery_uri,
        get_fix(version).DISCOVERY_RESPONSE,
        version)

    print(version, get_fix(version).DISCOVERY_RESPONSE)

    # client with relative JWT auth path
    client = make_client(version)
    client.set_auth(
        username=username,
        password=password,
        jwt_auth_url=jwt_path
    )
    services = client.discover_services(uri=discovery_uri)
    assert len(services) == 4

    # client with full JWT auth path
    client = make_client(version)
    client.set_auth(
        username=username,
        password=password,
        jwt_auth_url=jwt_url
    )
    services = client.discover_services(uri=discovery_uri)
    assert len(services) == 4

    httpretty.disable()
    httpretty.reset()

Example 123

Project: spherecluster Source File: test_von_mises_fisher_mixture.py
    @pytest.mark.parametrize("params_in", [
        {
            'posterior_type': 'soft',
        },
        {
            'posterior_type': 'hard',
        },
        {
            'posterior_type': 'soft',
            'n_jobs': 2,
        },
        {
            'posterior_type': 'hard',
            'n_jobs': 3,
        },
        {
            'posterior_type': 'hard',
            'force_weights': np.ones(5.)/5.,
        },
    ])
    def test_integration_sparse(self, params_in):
        n_clusters = 5
        n_examples = 20
        n_features = 100
        n_nonzero = 10
        X = sp.sparse.csr_matrix((n_examples, n_features))
        for ee in range(n_examples):
            ridx = np.random.randint(n_features, size=(n_nonzero))
            X[ee, ridx] = np.random.randn(n_nonzero)
            X[ee, :] /= sp.sparse.linalg.norm(X[ee, :])

        params_in.update({'n_clusters': n_clusters})
        movmf = VonMisesFisherMixture(**params_in)
        movmf.fit(X)

        assert movmf.cluster_centers_.shape == (n_clusters, n_features)
        assert len(movmf.concentrations_) == n_clusters
        assert len(movmf.weights_) == n_clusters
        assert len(movmf.labels_) == n_examples

        for center in movmf.cluster_centers_:
            assert_almost_equal(np.linalg.norm(center), 1.0)

        for concentration in movmf.concentrations_:
            assert concentration > 0

        for weight in movmf.weights_:
            assert not np.isnan(weight)

        plabels = movmf.predict(X)
        assert_array_equal(plabels, movmf.labels_)

        ll = movmf.log_likelihood(X)
        ll_labels = np.zeros(movmf.labels_.shape)
        for ee in range(n_examples):
            ll_labels[ee] = np.argmax(ll[:, ee])

        assert_array_equal(ll_labels, movmf.labels_)

Example 124

Project: i3pystatus Source File: test_core_modules.py
Function: test_clicks
@pytest.mark.parametrize("events, expected", [
    # Fast click
    (((0, left_click),),
     'no action'),

    # Slow click
    (((0.4, left_click),),
     'leftclick'),

    # Slow double click
    (((0.4, left_click),
      (0.4, left_click),),
     'leftclick'),

    # Fast double click
    (((0.2, left_click),
      (0, left_click),),
     'doubleleftclick'),

    # Fast double click + Slow click
    (((0.2, left_click),
      (0, left_click),
      (0.3, left_click),),
     'leftclick'),

    # Alternate double click
    (((0.2, left_click),
      (0, right_click),),
     'leftclick'),

    # Slow click, no callback
    (((0.4, right_click),),
     'no action'),

    # Fast double click
    (((0.2, right_click),
      (0, right_click),),
     'doublerightclick'),

    # Fast double click
    (((0, scroll_down),
      (0, scroll_down),),
     'downscroll'),

    # Slow click
    (((0.4, scroll_up),),
     'upscroll'),

    # Fast double click
    (((0, scroll_up),
      (0, scroll_up),),
     'doubleupscroll'),
])
def test_clicks(events, expected):
    class TestClicks(IntervalModule):
        def set_action(self, action):
            self._action = action

        on_leftclick = [set_action, "leftclick"]
        on_doubleleftclick = [set_action, "doubleleftclick"]

        # on_rightclick = [set_action, "rightclick"]
        on_doublerightclick = [set_action, "doublerightclick"]

        on_upscroll = [set_action, "upscroll"]
        on_doubleupscroll = [set_action, "doubleupscroll"]

        on_downscroll = [set_action, "downscroll"]
        # on_doubledownscroll = [set_action, "doubledownscroll"]

        _action = 'no action'

    # Divide all times by 10 to make the test run faster
    TestClicks.multi_click_timeout /= 10

    m = TestClicks()
    for sl, ev in events:
        m.on_click(ev)
        time.sleep(sl / 10)
    assert m._action == expected

Example 125

Project: dask Source File: test_arithmetics_reduction.py
@pytest.mark.parametrize('split_every', [False, 2])
def test_reductions(split_every):
    dsk = {('x', 0): pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]},
                                  index=[0, 1, 3]),
           ('x', 1): pd.DataFrame({'a': [4, 5, 6], 'b': [3, 2, 1]},
                                  index=[5, 6, 8]),
           ('x', 2): pd.DataFrame({'a': [7, 8, 9], 'b': [0, 0, 0]},
                                  index=[9, 9, 9])}
    meta = make_meta({'a': 'i8', 'b': 'i8'}, index=pd.Index([], 'i8'))
    ddf1 = dd.DataFrame(dsk, 'x', meta, [0, 4, 9, 9])
    pdf1 = ddf1.compute()

    nans1 = pd.Series([1] + [np.nan] * 4 + [2] + [np.nan] * 3)
    nands1 = dd.from_pandas(nans1, 2)
    nans2 = pd.Series([1] + [np.nan] * 8)
    nands2 = dd.from_pandas(nans2, 2)
    nans3 = pd.Series([np.nan] * 9)
    nands3 = dd.from_pandas(nans3, 2)

    bools = pd.Series([True, False, True, False, True], dtype=bool)
    boolds = dd.from_pandas(bools, 2)

    for dds, pds in [(ddf1.b, pdf1.b), (ddf1.a, pdf1.a),
                     (ddf1['a'], pdf1['a']), (ddf1['b'], pdf1['b']),
                     (nands1, nans1), (nands2, nans2), (nands3, nans3),
                     (boolds, bools)]:
        assert isinstance(dds, dd.Series)
        assert isinstance(pds, pd.Series)
        assert_eq(dds.sum(split_every=split_every), pds.sum())
        assert_eq(dds.min(split_every=split_every), pds.min())
        assert_eq(dds.max(split_every=split_every), pds.max())
        assert_eq(dds.count(split_every=split_every), pds.count())
        assert_eq(dds.std(split_every=split_every), pds.std())
        assert_eq(dds.var(split_every=split_every), pds.var())
        assert_eq(dds.std(ddof=0, split_every=split_every), pds.std(ddof=0))
        assert_eq(dds.var(ddof=0, split_every=split_every), pds.var(ddof=0))
        assert_eq(dds.mean(split_every=split_every), pds.mean())
        assert_eq(dds.nunique(split_every=split_every), pds.nunique())

        assert_eq(dds.sum(skipna=False, split_every=split_every),
                  pds.sum(skipna=False))
        assert_eq(dds.min(skipna=False, split_every=split_every),
                  pds.min(skipna=False))
        assert_eq(dds.max(skipna=False, split_every=split_every),
                  pds.max(skipna=False))
        assert_eq(dds.std(skipna=False, split_every=split_every),
                  pds.std(skipna=False))
        assert_eq(dds.var(skipna=False, split_every=split_every),
                  pds.var(skipna=False))
        assert_eq(dds.std(skipna=False, ddof=0, split_every=split_every),
                  pds.std(skipna=False, ddof=0))
        assert_eq(dds.var(skipna=False, ddof=0, split_every=split_every),
                  pds.var(skipna=False, ddof=0))
        assert_eq(dds.mean(skipna=False, split_every=split_every),
                  pds.mean(skipna=False))

    assert_dask_graph(ddf1.b.sum(split_every=split_every), 'series-sum')
    assert_dask_graph(ddf1.b.min(split_every=split_every), 'series-min')
    assert_dask_graph(ddf1.b.max(split_every=split_every), 'series-max')
    assert_dask_graph(ddf1.b.count(split_every=split_every), 'series-count')
    assert_dask_graph(ddf1.b.std(split_every=split_every), 'series-std')
    assert_dask_graph(ddf1.b.var(split_every=split_every), 'series-var')
    assert_dask_graph(ddf1.b.std(ddof=0, split_every=split_every), 'series-std')
    assert_dask_graph(ddf1.b.var(ddof=0, split_every=split_every), 'series-var')
    assert_dask_graph(ddf1.b.mean(split_every=split_every), 'series-mean')
    # nunique is performed using drop-duplicates
    assert_dask_graph(ddf1.b.nunique(split_every=split_every), 'drop-duplicates')

    assert_eq(ddf1.index.min(split_every=split_every), pdf1.index.min())
    assert_eq(ddf1.index.max(split_every=split_every), pdf1.index.max())
    assert_eq(ddf1.index.count(split_every=split_every), pd.notnull(pdf1.index).sum())

Example 126

Project: CSScheme Source File: test_color3.py
Function: test_color
@pytest.mark.parametrize(('css_source', 'expected_result'), [
    ('', None),
    (' /* hey */\n', None),
    ('4', None),
    ('top', None),
    ('/**/transparent', (0, 0, 0, 0)),
    ('transparent', (0, 0, 0, 0)),
    (' transparent\n', (0, 0, 0, 0)),
    ('TransParent', (0, 0, 0, 0)),
    ('currentColor', 'currentColor'),
    ('CURRENTcolor', 'currentColor'),
    ('current_Color', None),

    ('black', (0, 0, 0, 1)),
    ('white', (1, 1, 1, 1)),
    ('fuchsia', (1, 0, 1, 1)),
    ('cyan', (0, 1, 1, 1)),
    ('CyAn', (0, 1, 1, 1)),
    ('darkkhaki', (189 / 255., 183 / 255., 107 / 255., 1)),

    ('#', None),
    ('#f', None),
    ('#ff', None),
    ('#fff', (1, 1, 1, 1)),
    ('#ffg', None),
    ('#ffff', None),
    ('#fffff', None),
    ('#ffffff', (1, 1, 1, 1)),
    ('#fffffg', None),
    ('#fffffff', None),
    ('#ffffffff', None),
    ('#fffffffff', None),

    ('#cba987', (203 / 255., 169 / 255., 135 / 255., 1)),
    ('#CbA987', (203 / 255., 169 / 255., 135 / 255., 1)),
    ('#1122aA', (17 / 255., 34 / 255., 170 / 255., 1)),
    ('#12a', (17 / 255., 34 / 255., 170 / 255., 1)),

    ('rgb(203, 169, 135)', (203 / 255., 169 / 255., 135 / 255., 1)),
    ('RGB(255, 255, 255)', (1, 1, 1, 1)),
    ('rgB(0, 0, 0)', (0, 0, 0, 1)),
    ('rgB(0, 51, 255)', (0, .2, 1, 1)),
    ('rgb(0,51,255)', (0, .2, 1, 1)),
    ('rgb(0\t,  51 ,255)', (0, .2, 1, 1)),
    ('rgb(/* R */0, /* G */51, /* B */255)', (0, .2, 1, 1)),
    ('rgb(-51, 306, 0)', (-.2, 1.2, 0, 1)),  # out of 0..1 is allowed

    ('rgb(42%, 3%, 50%)', (.42, .03, .5, 1)),
    ('RGB(100%, 100%, 100%)', (1, 1, 1, 1)),
    ('rgB(0%, 0%, 0%)', (0, 0, 0, 1)),
    ('rgB(10%, 20%, 30%)', (.1, .2, .3, 1)),
    ('rgb(10%,20%,30%)', (.1, .2, .3, 1)),
    ('rgb(10%\t,  20% ,30%)', (.1, .2, .3, 1)),
    ('rgb(/* R */10%, /* G */20%, /* B */30%)', (.1, .2, .3, 1)),
    ('rgb(-12%, 110%, 1400%)', (-.12, 1.1, 14, 1)),  # out of 0..1 is allowed

    ('rgb(10%, 50%, 0)', None),
    ('rgb(255, 50%, 0%)', None),
    ('rgb(0, 0 0)', None),
    ('rgb(0, 0, 0deg)', None),
    ('rgb(0, 0, light)', None),
    ('rgb()', None),
    ('rgb(0)', None),
    ('rgb(0, 0)', None),
    ('rgb(0, 0, 0, 0)', None),
    ('rgb(0%)', None),
    ('rgb(0%, 0%)', None),
    ('rgb(0%, 0%, 0%, 0%)', None),
    ('rgb(0%, 0%, 0%, 0)', None),

    ('rgba(0, 0, 0, 0)', (0, 0, 0, 0)),
    ('rgba(203, 169, 135, 0.3)', (203 / 255., 169 / 255., 135 / 255., 0.3)),
    ('RGBA(255, 255, 255, 0)', (1, 1, 1, 0)),
    ('rgBA(0, 51, 255, 1)', (0, 0.2, 1, 1)),
    ('rgba(0, 51, 255, 1.1)', (0, 0.2, 1, 1)),
    ('rgba(0, 51, 255, 37)', (0, 0.2, 1, 1)),
    ('rgba(0, 51, 255, 0.42)', (0, 0.2, 1, 0.42)),
    ('rgba(0, 51, 255, 0)', (0, 0.2, 1, 0)),
    ('rgba(0, 51, 255, -0.1)', (0, 0.2, 1, 0)),
    ('rgba(0, 51, 255, -139)', (0, 0.2, 1, 0)),

    ('rgba(42%, 3%, 50%, 0.3)', (.42, .03, .5, 0.3)),
    ('RGBA(100%, 100%, 100%, 0)', (1, 1, 1, 0)),
    ('rgBA(0%, 20%, 100%, 1)', (0, 0.2, 1, 1)),
    ('rgba(0%, 20%, 100%, 1.1)', (0, 0.2, 1, 1)),
    ('rgba(0%, 20%, 100%, 37)', (0, 0.2, 1, 1)),
    ('rgba(0%, 20%, 100%, 0.42)', (0, 0.2, 1, 0.42)),
    ('rgba(0%, 20%, 100%, 0)', (0, 0.2, 1, 0)),
    ('rgba(0%, 20%, 100%, -0.1)', (0, 0.2, 1, 0)),
    ('rgba(0%, 20%, 100%, -139)', (0, 0.2, 1, 0)),

    ('rgba(255, 255, 255, 0%)', None),
    ('rgba(10%, 50%, 0, 1)', None),
    ('rgba(255, 50%, 0%, 1)', None),
    ('rgba(0, 0, 0 0)', None),
    ('rgba(0, 0, 0, 0deg)', None),
    ('rgba(0, 0, 0, light)', None),
    ('rgba()', None),
    ('rgba(0)', None),
    ('rgba(0, 0, 0)', None),
    ('rgba(0, 0, 0, 0, 0)', None),
    ('rgba(0%)', None),
    ('rgba(0%, 0%)', None),
    ('rgba(0%, 0%, 0%)', None),
    ('rgba(0%, 0%, 0%, 0%)', None),
    ('rgba(0%, 0%, 0%, 0%, 0%)', None),

    ('HSL(0, 0%, 0%)', (0, 0, 0, 1)),
    ('hsL(0, 100%, 50%)', (1, 0, 0, 1)),
    ('hsl(60, 100%, 37.5%)', (0.75, 0.75, 0, 1)),
    ('hsl(780, 100%, 37.5%)', (0.75, 0.75, 0, 1)),
    ('hsl(-300, 100%, 37.5%)', (0.75, 0.75, 0, 1)),
    ('hsl(300, 50%, 50%)', (0.75, 0.25, 0.75, 1)),

    ('hsl(10, 50%, 0)', None),
    ('hsl(50%, 50%, 0%)', None),
    ('hsl(0, 0% 0%)', None),
    ('hsl(30deg, 100%, 100%)', None),
    ('hsl(0, 0%, light)', None),
    ('hsl()', None),
    ('hsl(0)', None),
    ('hsl(0, 0%)', None),
    ('hsl(0, 0%, 0%, 0%)', None),

    ('HSLA(-300, 100%, 37.5%, 1)', (0.75, 0.75, 0, 1)),
    ('hsLA(-300, 100%, 37.5%, 12)', (0.75, 0.75, 0, 1)),
    ('hsla(-300, 100%, 37.5%, 0.2)', (0.75, 0.75, 0, .2)),
    ('hsla(-300, 100%, 37.5%, 0)', (0.75, 0.75, 0, 0)),
    ('hsla(-300, 100%, 37.5%, -3)', (0.75, 0.75, 0, 0)),

    ('hsla(10, 50%, 0, 1)', None),
    ('hsla(50%, 50%, 0%, 1)', None),
    ('hsla(0, 0% 0%, 1)', None),
    ('hsla(30deg, 100%, 100%, 1)', None),
    ('hsla(0, 0%, light, 1)', None),
    ('hsla()', None),
    ('hsla(0)', None),
    ('hsla(0, 0%)', None),
    ('hsla(0, 0%, 0%, 50%)', None),
    ('hsla(0, 0%, 0%, 1, 0%)', None),

    ('cmyk(0, 0, 0, 0)', None),
])
def test_color(css_source, expected_result):
    result = parse_color_string(css_source)
    if isinstance(result, tuple):
        for got, expected in zip(result, expected_result):
            # Compensate for floating point errors:
            assert abs(got - expected) < 1e-10
        for i, attr in enumerate(['red', 'green', 'blue', 'alpha']):
            assert getattr(result, attr) == result[i]
    else:
        assert result == expected_result

Example 127

Project: CSScheme Source File: test_parser.py
Function: test_core_parser
@pytest.mark.parametrize(('css_source', 'expected_rules', 'expected_errors'), [
    (' /* hey */\n', [], []),

    ('foo{} /* hey */\n@bar;@baz{}',
        [('foo', []), ('@bar', [], None), ('@baz', [], [])], []),

    ('@import "foo.css"/**/;', [
        ('@import', [('STRING', 'foo.css')], None)], []),

    ('@import "foo.css"/**/', [
        ('@import', [('STRING', 'foo.css')], None)], []),

    ('@import "foo.css', [
        ('@import', [('STRING', 'foo.css')], None)], []),

    ('{}', [], ['empty selector']),

    ('a{b:4}', [('a', [('b', [('INTEGER', 4)])])], []),

    ('@page {\t b: 4; @margin}', [('@page', [], [
        ('S', '\t '), ('IDENT', 'b'), (':', ':'), ('S', ' '), ('INTEGER', 4),
        (';', ';'), ('S', ' '), ('ATKEYWORD', '@margin'),
    ])], []),

    ('foo', [], ['no declaration block found']),

    ('foo @page {} bar {}', [('bar', [])],
        ['unexpected ATKEYWORD token in selector']),

    ('foo { content: "unclosed string;\n color:red; ; margin/**/\n: 2cm; }',
        [('foo', [('margin', [('DIMENSION', 2)])])],
        ['unexpected BAD_STRING token in property value']),

    ('foo { 4px; bar: 12% }',
        [('foo', [('bar', [('PERCENTAGE', 12)])])],
        ['expected a property name, got DIMENSION']),

    ('foo { bar! 3cm auto ; baz: 7px }',
        [('foo', [('baz', [('DIMENSION', 7)])])],
        ["expected ':', got DELIM"]),

    ('foo { bar ; baz: {("}"/* comment */) {0@fizz}} }',
        [('foo', [('baz', [('{', [
            ('(', [('STRING', '}')]), ('S', ' '),
            ('{', [('INTEGER', 0), ('ATKEYWORD', '@fizz')])
        ])])])],
        ["expected ':'"]),

    ('foo { bar: ; baz: not(z) }',
        [('foo', [('baz', [('FUNCTION', 'not', [('IDENT', 'z')])])])],
        ['expected a property value']),

    ('foo { bar: (]) ; baz: U+20 }',
        [('foo', [('baz', [('UNICODE-RANGE', 'U+20')])])],
        ['unmatched ] token in (']),
])
def test_core_parser(css_source, expected_rules, expected_errors):
    class CoreParser(CSSchemeParser):
        """A parser that always accepts unparsed at-rules and is reduced to
        the core functions.
        """
        def parse_at_rule(self, rule, stylesheet_rules, errors, context):
            return rule

        # parse_ruleset = CSS21Parser.parse_ruleset
        parse_declaration = CSS21Parser.parse_declaration

    stylesheet = CoreParser().parse_stylesheet(css_source)
    assert_errors(stylesheet.errors, expected_errors)
    result = [
        (rule.at_keyword, list(jsonify(rule.head)),
            list(jsonify(rule.body))
            if rule.body is not None else None)
        if rule.at_keyword else
        (rule.selector.as_css(), [
            (decl.name, list(jsonify(decl.value)))
            for decl in rule.declarations])
        for rule in stylesheet.rules
    ]
    assert result == expected_rules

Example 128

Project: dask Source File: test_multi.py
@pytest.mark.parametrize('shuffle', ['disk', 'tasks'])
@pytest.mark.parametrize('how', ['inner', 'outer', 'left', 'right'])
def test_merge_by_index_patterns(how, shuffle):

    pdf1l = pd.DataFrame({'a': [1, 2, 3, 4, 5, 6, 7],
                          'b': [7, 6, 5, 4, 3, 2, 1]})
    pdf1r = pd.DataFrame({'c': [1, 2, 3, 4, 5, 6, 7],
                          'd': [7, 6, 5, 4, 3, 2, 1]})

    pdf2l = pd.DataFrame({'a': [1, 2, 3, 4, 5, 6, 7],
                          'b': [7, 6, 5, 4, 3, 2, 1]},
                         index=list('abcdefg'))
    pdf2r = pd.DataFrame({'c': [7, 6, 5, 4, 3, 2, 1],
                          'd': [7, 6, 5, 4, 3, 2, 1]},
                         index=list('abcdefg'))

    pdf3l = pdf2l
    pdf3r = pd.DataFrame({'c': [6, 7, 8, 9],
                          'd': [5, 4, 3, 2]},
                         index=list('abdg'))

    pdf4l = pdf2l
    pdf4r = pd.DataFrame({'c': [9, 10, 11, 12],
                          'd': [5, 4, 3, 2]},
                         index=list('abdg'))

    # completely different index
    pdf5l = pd.DataFrame({'a': [1, 1, 2, 2, 3, 3, 4],
                          'b': [7, 6, 5, 4, 3, 2, 1]},
                         index=list('lmnopqr'))
    pdf5r = pd.DataFrame({'c': [1, 1, 1, 1],
                          'd': [5, 4, 3, 2]},
                         index=list('abcd'))

    pdf6l = pd.DataFrame({'a': [1, 1, 2, 2, 3, 3, 4],
                          'b': [7, 6, 5, 4, 3, 2, 1]},
                         index=list('cdefghi'))
    pdf6r = pd.DataFrame({'c': [1, 2, 1, 2],
                          'd': [5, 4, 3, 2]},
                         index=list('abcd'))

    pdf7l = pd.DataFrame({'a': [1, 1, 2, 2, 3, 3, 4],
                          'b': [7, 6, 5, 4, 3, 2, 1]},
                         index=list('abcdefg'))
    pdf7r = pd.DataFrame({'c': [5, 6, 7, 8],
                          'd': [5, 4, 3, 2]},
                         index=list('fghi'))

    for pdl, pdr in [(pdf1l, pdf1r), (pdf2l, pdf2r), (pdf3l, pdf3r),
                     (pdf4l, pdf4r), (pdf5l, pdf5r), (pdf6l, pdf6r),
                     (pdf7l, pdf7r)]:

        for lpart, rpart in [(2, 2),    # same partition
                             (3, 2),    # left npartition > right npartition
                             (2, 3)]:   # left npartition < right npartition

            ddl = dd.from_pandas(pdl, lpart)
            ddr = dd.from_pandas(pdr, rpart)

            assert_eq(dd.merge(ddl, ddr, how=how, left_index=True,
                               right_index=True, shuffle=shuffle),
                      pd.merge(pdl, pdr, how=how, left_index=True,
                               right_index=True))
            assert_eq(dd.merge(ddr, ddl, how=how, left_index=True,
                               right_index=True, shuffle=shuffle),
                      pd.merge(pdr, pdl, how=how, left_index=True,
                               right_index=True))

            assert_eq(dd.merge(ddl, ddr, how=how, left_index=True,
                               right_index=True, shuffle=shuffle,
                               indicator=True),
                      pd.merge(pdl, pdr, how=how, left_index=True,
                               right_index=True, indicator=True))
            assert_eq(dd.merge(ddr, ddl, how=how, left_index=True,
                               right_index=True, shuffle=shuffle,
                               indicator=True),
                      pd.merge(pdr, pdl, how=how, left_index=True,
                               right_index=True, indicator=True))

            assert_eq(ddr.merge(ddl, how=how, left_index=True,
                                right_index=True, shuffle=shuffle),
                      pdr.merge(pdl, how=how, left_index=True,
                                right_index=True))
            assert_eq(ddl.merge(ddr, how=how, left_index=True,
                                right_index=True, shuffle=shuffle),
                      pdl.merge(pdr, how=how, left_index=True,
                                right_index=True))

            # hash join
            list_eq(dd.merge(ddl, ddr, how=how, left_on='a', right_on='c',
                             shuffle=shuffle),
                    pd.merge(pdl, pdr, how=how, left_on='a', right_on='c'))
            list_eq(dd.merge(ddl, ddr, how=how, left_on='b', right_on='d',
                             shuffle=shuffle),
                    pd.merge(pdl, pdr, how=how, left_on='b', right_on='d'))

            list_eq(dd.merge(ddr, ddl, how=how, left_on='c', right_on='a',
                             shuffle=shuffle, indicator=True),
                    pd.merge(pdr, pdl, how=how, left_on='c', right_on='a',
                             indicator=True))
            list_eq(dd.merge(ddr, ddl, how=how, left_on='d', right_on='b',
                             shuffle=shuffle, indicator=True),
                    pd.merge(pdr, pdl, how=how, left_on='d', right_on='b',
                             indicator=True))

            list_eq(dd.merge(ddr, ddl, how=how, left_on='c', right_on='a',
                             shuffle=shuffle),
                    pd.merge(pdr, pdl, how=how, left_on='c', right_on='a'))
            list_eq(dd.merge(ddr, ddl, how=how, left_on='d', right_on='b',
                             shuffle=shuffle),
                    pd.merge(pdr, pdl, how=how, left_on='d', right_on='b'))

            list_eq(ddl.merge(ddr, how=how, left_on='a', right_on='c',
                              shuffle=shuffle),
                    pdl.merge(pdr, how=how, left_on='a', right_on='c'))
            list_eq(ddl.merge(ddr, how=how, left_on='b', right_on='d',
                              shuffle=shuffle),
                    pdl.merge(pdr, how=how, left_on='b', right_on='d'))

            list_eq(ddr.merge(ddl, how=how, left_on='c', right_on='a',
                              shuffle=shuffle),
                    pdr.merge(pdl, how=how, left_on='c', right_on='a'))
            list_eq(ddr.merge(ddl, how=how, left_on='d', right_on='b',
                              shuffle=shuffle),
                    pdr.merge(pdl, how=how, left_on='d', right_on='b'))

Example 129

Project: pyramid_fullauth Source File: test_social_view.py
@pytest.mark.parametrize('profile, email', [
    (
        {
            'accounts': [{'domain': text_type('facebook.com'), 'userid': text_type('2343')}],
            'displayName': text_type('teddy'),
            'verifiedEmail': text_type('[email protected]'),
            'preferredUsername': text_type('teddy'),
            'emails': [{'value': text_type('[email protected]')}],
            'name': text_type('ted')
        },
        '[email protected]'
    ), (
        {
            'accounts': [{'domain': text_type('facebook.com'), 'userid': text_type('2343')}],
            'displayName': text_type('teddy'),
            'preferredUsername': text_type('teddy'),
            'emails': [{'value': text_type('[email protected]')}],
            'name': text_type('ted')
        },
        '[email protected]'
    ), (
        {
            'accounts': [{'domain': text_type('facebook.com'), 'userid': text_type('2343')}],
            'displayName': text_type('teddy'),
            'preferredUsername': text_type('teddy'),
            'emails': [{}],
            'name': text_type('ted')
        },
        '[email protected]'
    ), (
        {
            'accounts': [{'domain': text_type('facebook.com'), 'userid': text_type('2343')}],
            'displayName': text_type('teddy'),
            'preferredUsername': text_type('teddy'),
            'emails': [],
            'name': text_type('ted')
        },
        '[email protected]'
    ), (
        {
            'accounts': [{'domain': text_type('facebook.com'), 'userid': text_type('2343')}],
            'displayName': text_type('teddy'),
            'preferredUsername': text_type('teddy'),
            'name': text_type('ted')
        },
        '[email protected]'
    ),
])
def test_email_from_context(profile, email):
    """Test email_from_context email getting method."""
    from velruse import AuthenticationComplete
    context = AuthenticationComplete(
        profile,
        {'oauthAccessToken': '7897048593434'},
        text_type('facebook'),
        text_type('facebook')
    )
    view = SocialLoginViews(mock.MagicMock())
    assert view._email_from_context(context) == email

Example 130

Project: pymtl Source File: verilog_test.py
@pytest.mark.parametrize( "nbits,rst,all_verilog",
  [(6,2,True), (6,2,False),]
)
def test_chained_param_VerilogModel( dump_vcd, nbits, rst, all_verilog ):

  class EnResetRegParamVRTL( VerilogModel ):
    def __init__( s, p_nbits, p_reset_value=0, p_id=0 ):
      s.en  = InPort ( 1 )
      s.d   = InPort ( p_nbits )
      s.q   = OutPort( p_nbits )

  class ModelChainer( Model ):
    def __init__( s, nbits, rst=0 ):
      s.en  = InPort ( 1 )
      s.d   = InPort ( nbits )
      s.q   = OutPort( nbits )

      s.mod = m = [EnResetRegParamVRTL( nbits, rst, x ) for x in range(3)]

      for x in s.mod:
        s.connect( s.en, x.en )

      s.connect_dict({
        s.d    : m[0].d,
        m[0].q : m[1].d,
        m[1].q : m[2].d,
        m[2].q : s.q,
      })

    def line_trace( s ):
      return '{d} {q}'.format( **s.__dict__ )

  #---------------------------------------------------------------------
  # test
  #---------------------------------------------------------------------

  m, sim = _sim_setup( ModelChainer(nbits,rst), all_verilog, dump_vcd )
  assert m.q == rst

  import collections
  pipeline = collections.deque( maxlen=3 )
  pipeline.extend( [rst]*3 )

  # Super hacky line tracing!
  #import types
  #m.line_trace = types.MethodType(
  #    lambda x: '{} {} {}'.format( x.d, x.q, pipeline ), m
  #)

  print()
  for i in range( 20 ):
    en  = random.randint(0,1)
    if en:
      pipeline.appendleft( i )

    m.d  .value = i
    m.en .value = en
    sim.cycle()
    sim.print_line_trace()
    assert m.q == pipeline[-1]

Example 131

Project: Flexget Source File: test_qualities.py
    @pytest.mark.parametrize("test_quality", [
        ('Test.File 1080p.web', '1080p webdl'),
        ('Test.File.1080.web-random', '1080p webdl'),
        ('Test.File.1080.webrandom', '1080p'),
        ('Test.File 1080p.web-dl', '1080p webdl'),
        ('Test.File.web-dl.1080p', '1080p webdl'),
        ('Test.File.WebHD.720p', '720p webdl'),
        ('Test.File.720p.bluray', '720p bluray'),
        ('Test.File.720hd.bluray', '720p bluray'),
        ('Test.File.1080p.bluray', '1080p bluray'),
        ('Test.File.1080p.cam', '1080p cam'),
        ('A Movie 2011 TS 576P XviD-DTRG', '576p ts xvid'),

        ('Test.File.720p.bluray.r5', '720p r5'),
        ('Test.File.1080p.bluray.rc', '1080p r5'),

        # 10bit
        ('Test.File.480p.10bit', '480p 10bit'),
        ('Test.File.720p.10bit', '720p 10bit'),
        ('Test.File.720p.bluray.10bit', '720p bluray 10bit'),
        ('Test.File.1080p.10bit', '1080p 10bit'),
        ('Test.File.1080p.bluray.10bit', '1080p bluray 10bit'),

        ('Test.File.720p.web', '720p webdl'),
        ('Test.File.720p.webdl', '720p webdl'),
        ('Test.File.1280x720_web dl', '720p webdl'),
        ('Test.File.720p.h264.web.dl', '720p webdl h264'),
        ('Test.File.1080p.webhd.x264', '1080p webdl h264'),
        ('Test.File.480.hdtv.x265', '480p hdtv h265'),
        ('Test.File.web', 'webdl'),
        ('Test.File.web-dl', 'webdl'),
        ('Test.File.720P', '720p'),
        ('Test.File.1920x1080', '1080p'),
        ('Test.File.1080i', '1080i'),
        ('Test File blurayrip', 'bluray'),
        ('Test.File.br-rip', 'bluray'),
        ('Test.File.720px', '720p'),
        ('Test.File.720p50', '720p'),

        ('Test.File.dvd.rip', 'dvdrip'),
        ('Test.File.dvd.rip.r5', 'r5'),

        ('Test.File.[576p][00112233].mkv', '576p'),

        ('Test.TS.FooBar', 'ts'),

        ('Test.File.360p.avi', '360p'),
        ('Test.File.[360p].mkv', '360p'),
        ('Test.File.368.avi', '368p'),
        ('Test.File.720p.hdtv.avi', '720p hdtv'),
        ('Test.File.1080p.hdtv.avi', '1080p hdtv'),
        ('Test.File.720p.preair.avi', '720p preair'),
        # ('Test.File.ts.dvdrip.avi', 'ts'), This should no exists. Having Telesync and DVDRip is a non-sense.
        ('Test.File.HDTS.blah', 'ts'),
        # ('Test.File.HDCAM.bluray.lie', 'cam'), This should no exists. Having Cam and Bluray is a non-sense.

        # Test qualities as part of words. #1593
        ('Tsar.File.720p', '720p'),
        ('Camera.1080p', '1080p'),

        # Some audio formats
        ('Test.File.DTSHDMA', 'dtshd'),
        ('Test.File.DTSHD.MA', 'dtshd'),
        ('Test.File.DTS.HDMA', 'dtshd'),
        ('Test.File.dts.hd.ma', 'dtshd'),
        ('Test.File.DTS.HD', 'dtshd'),
        ('Test.File.DTSHD', 'dtshd'),
        ('Test.File.DTS', 'dts'),
        ('Test.File.truehd', 'truehd'),
        ('Test.File.DTSHDMA', 'dtshd')
    ])
    def test_quality_failures(self, parser, test_quality):
        quality = parser().parse_movie(test_quality[0]).quality
        assert str(quality) == test_quality[1], ('`%s` quality should be `%s` not `%s`' % (
            test_quality[0], test_quality[1], quality
        ))

Example 132

Project: two1-python Source File: test_ecdsa.py
@pytest.mark.parametrize("curve", [
    ecdsa_python.p256(),
    ecdsa_openssl.p256()
    ])
def test_p256(curve):
    point_class = None
    if isinstance(curve, ecdsa_python.p256):
        point_class = ecdsa_python.ECPointAffine
        # Test the basic operations, test vectors taken from:
        # https://www.nsa.gov/ia/_files/nist-routines.pdf, Section 4.3
        S = ecdsa_python.ECPointJacobian(curve,
                                         0xde2444bebc8d36e682edd27e0f271508617519b3221a8fa0b77cab3989da97c9,
                                         0xc093ae7ff36e5380fc01a5aad1e66659702de80f53cec576b6350b243042a256,
                                         1)
        T = ecdsa_python.ECPointJacobian(curve,
                                         0x55a8b00f8da1d44e62f6b3b25316212e39540dc861c89575bb8cf92e35e0986b,
                                         0x5421c3209c2d6c704835d82ac4c3dd90f61a8a52598b9e7ab656e9d8c8b24316,
                                         1)

        # Addition
        R = (S + T).to_affine()
        assert R.x == 0x72b13dd4354b6b81745195e98cc5ba6970349191ac476bd4553cf35a545a067e
        assert R.y == 0x8d585cbb2e1327d75241a8a122d7620dc33b13315aa5c9d46d013011744ac264

        # Subtraction
        R = (S - T).to_affine()
        assert R.x == 0xc09ce680b251bb1d2aad1dbf6129deab837419f8f1c73ea13e7dc64ad6be6021
        assert R.y == 0x1a815bf700bd88336b2f9bad4edab1723414a022fdf6c3f4ce30675fb1975ef3

        # Point doubling
        R = (S.double()).to_affine()
        assert R.x == 0x7669e6901606ee3ba1a8eef1e0024c33df6c22f3b17481b82a860ffcdb6127b0
        assert R.y == 0xfa878162187a54f6c39f6ee0072f33de389ef3eecd03023de10ca2c1db61d0c7

        # Scalar multiplication
        d = 0xc51e4753afdec1e6b6c6a5b992f43f8dd0c7a8933072708b6522468b2ffb06fd
        R = (S * d).to_affine()
        assert R.x == 0x51d08d5f2d4278882946d88d83c97d11e62becc3cfc18bedacc89ba34eeca03f
        assert R.y == 0x75ee68eb8bf626aa5b673ab51f6e744e06f8fcf8a6c0cf3035beca956a7b41d5

        # Joint scalar multiplicaton
        e = 0xd37f628ece72a462f0145cbefe3f0b355ee8332d37acdd83a358016aea029db7
        R = (S * d + T * e).to_affine()
        assert R.x == 0xd867b4679221009234939221b8046245efcf58413daacbeff857b8588341f6b8
        assert R.y == 0xf2504055c03cede12d22720dad69c745106b6607ec7e50dd35d54bd80f615275
    else:
        point_class = ecdsa_openssl.ECPointAffine

    # First test nonce generation according to rfc6979
    private_key = 0xC9AFA9D845BA75166B5C215767B1D6934E50C3DB36E89B127B8A622B120F6721
    public_key_x = 0x60FED4BA255A9D31C961EB74C6356D68C049B8923B61FA6CE669622E60F29FB6
    public_key_y = 0x7903FE1008B8BC99A41AE9E95628BC64F2F1B20C2D7E9F5177A3C294D4462299

    pub_key = curve.public_key(private_key)
    assert pub_key.x == public_key_x
    assert pub_key.y == public_key_y

    message = b'sample'
    k = curve._nonce_rfc6979(private_key, hashlib.sha256(message).digest())

    assert k == 0xA6E3C57DD01ABE90086538398355DD4C3B17AA873382B0F24D6129493D8AAD60

    sig_pt, _ = curve.sign(message, private_key)

    curve.y_from_x(sig_pt.x)
    assert sig_pt.x == 0xEFD48B2AACB6A8FD1140DD9CD45E81D69D2C877B56AAF991C34D0EA84EAF3716
    assert sig_pt.y == 0xF7CB1C942D657C41D436C7A1B6E29F65F3E900DBB9AFF4064DC4AB2F843ACDA8

    keys = curve.recover_public_key(message, sig_pt)
    assert len(keys) > 0
    matching_keys = 0
    for k, recid in keys:
        if k is not None and k.x == public_key_x and k.y == public_key_y:
            matching_keys += 1
    assert matching_keys > 0

    assert curve.verify(message, sig_pt, point_class(curve, public_key_x, public_key_y))

    # Taken from https://www.nsa.gov/ia/_files/ecdsa.pdf Appendix D.1.1
    private_key = 0x70a12c2db16845ed56ff68cfc21a472b3f04d7d6851bf6349f2d7d5b3452b38a
    public_key_x = 0x8101ece47464a6ead70cf69a6e2bd3d88691a3262d22cba4f7635eaff26680a8
    public_key_y = 0xd8a12ba61d599235f67d9cb4d58f1783d3ca43e78f0a5abaa624079936c0c3a9

    pub_key = curve.public_key(private_key)
    assert pub_key.x == public_key_x
    assert pub_key.y == public_key_y

    k = 0x580ec00d856434334cef3f71ecaed4965b12ae37fa47055b1965c7b134ee45d0
    modinv_k = 0x6a664fa115356d33f16331b54c4e7ce967965386c7dcbf2904604d0c132b4a74

    if isinstance(curve, ecdsa_python.p256):
        # Test modular inverse (for signing)
        assert curve.modinv(k, curve.n) == modinv_k

    message = b'This is only a test message. It is 48 bytes long'
    sig_pt, _ = curve._sign(message, private_key, True, k)

    assert sig_pt.x == 0x7214bc9647160bbd39ff2f80533f5dc6ddd70ddf86bb815661e805d5d4e6f27c
    assert sig_pt.y == 0x7d1ff961980f961bdaa3233b6209f4013317d3e3f9e1493592dbeaa1af2bc367

    assert curve.verify(message, sig_pt, point_class(curve, public_key_x, public_key_y))

Example 133

Project: meld Source File: test_filediff.py
@pytest.mark.parametrize("text, ignored_ranges, expected_text", [
    #    0123456789012345678901234567890123456789012345678901234567890123456789
    # Matching without groups
    (
        "# asdasdasdasdsad",
        [(0, 17)],
        "",
    ),
    # Matching with single group
    (
        "asdasdasdasdsab",
        [(1, 14)],
        "ab",
    ),
    # Matching with multiple groups
    (
        "xasdyasdz",
        [(1, 4), (5, 8)],
        "xyz",
    ),
    # Matching with multiple partially overlapping filters
    (
        "qaqxqbyqzq",
        [(2, 6), (7, 8)],
        "qayzq",
    ),
    # Matching with multiple fully overlapping filters
    (
        "qaqxqybqzq",
        [(2, 8)],
        "qazq",
    ),
    # Matching with and without groups, with single dominated match
    (
        "# asdasdasdasdsab",
        [(0, 17)],
        "",
    ),
    # Matching with and without groups, with partially overlapping filters
    (
        "/*a*/ub",
        [(0, 6)],
        "b",
    ),
    # Non-matching with groups
    (
        "xasdyasdx",
        [],
        "xasdyasdx",
    ),
    # Multiple lines with non-overlapping filters
    (
        "#ab\na2b",
        [(0, 3), (5, 6)],
        "\nab",
    ),
    # CVS keyword
    (
        "$Author: John Doe $",
        [(8, 18)],
        "$Author:$",
    ),

])
def test_filter_text(text, ignored_ranges, expected_text):
    filter_patterns = [
        '#.*',
        '/\*.*\*/',
        'a(.*)b',
        'x(.*)y(.*)z',
        '\$\w+:([^\n$]+)\$'
    ]
    filters = [
        FilterEntry.new_from_gsetting(("name", True, f), FilterEntry.REGEX)
        for f in filter_patterns
    ]

    filediff = mock.MagicMock()
    filediff.text_filters = filters
    filter_text = FileDiff._filter_text

    buf = Gtk.TextBuffer()
    buf.create_tag("inline")
    buf.create_tag("dimmed")
    buf.set_text(text)
    start, end = buf.get_bounds()

    text = filter_text(
        filediff, buf.get_text(start, end, False), buf, start, end)

    # Find ignored ranges
    tag = buf.get_tag_table().lookup("dimmed")
    toggles = []
    it = start.copy()
    if it.toggles_tag(tag):
        toggles.append(it.get_offset())
    while it.forward_to_tag_toggle(tag):
        toggles.append(it.get_offset())
    toggles = list(zip(toggles[::2], toggles[1::2]))

    print("Text:", text)
    print("Toggles:", toggles)

    assert toggles == ignored_ranges
    assert text == expected_text

Example 134

Project: SmokeDetector Source File: test_parsing.py
Function: test_parsing
@pytest.mark.parametrize("input_data, parse_method, expected", [
    ('Testing * escaping of ] special [ characters', escape_special_chars_in_title, 'Testing \* escaping of \] special \[ characters'),
    ('HTML &#39; unescaping<', unescape_title, 'HTML \' unescaping<'),
    ('http://physics.stackexchange.com/users/7433/manishearth', get_user_from_url, ('7433', 'physics.stackexchange.com')),
    ('http://softwarerecs.stackexchange.com/users/46/undo', get_user_from_url, ('46', 'softwarerecs.stackexchange.com')),
    ('http://earthscience.stackexchange.com/users/20/hichris123', get_user_from_url, ('20', 'earthscience.stackexchange.com')),
    ('http://codegolf.stackexchange.com/users/9275/programfox', get_user_from_url, ('9275', 'codegolf.stackexchange.com')),
    ('http://stackoverflow.com/users/1/jeff-atwood', get_user_from_url, ('1', 'stackoverflow.com')),
    ('http://mathoverflow.net/users/66/ben-webster', get_user_from_url, ('66', 'mathoverflow.net')),
    ('http://codegolf.stackexchange.com/u/9275', get_user_from_url, ('9275', 'codegolf.stackexchange.com')),
    ('http://codegolf.stackexchange.com/u/9275/', get_user_from_url, ('9275', 'codegolf.stackexchange.com')),
    ('http://codegolf.stackexchange.com/users/9275', get_user_from_url, ('9275', 'codegolf.stackexchange.com')),
    ('http://codegolf.stackexchange.com/users/9275/', get_user_from_url, ('9275', 'codegolf.stackexchange.com')),
    ('//stackoverflow.com/users/1/jeff-atwood', get_user_from_url, ('1', 'stackoverflow.com')),
    ('!!/addblu http://stackoverflow.com/users/0/test', get_user_from_list_command, ('0', 'stackoverflow.com')),
    ('!!/rmblu http://stackoverflow.com/users/0/test', get_user_from_list_command, ('0', 'stackoverflow.com')),
    ('!!/addwlu http://stackoverflow.com/users/0/test', get_user_from_list_command, ('0', 'stackoverflow.com')),
    ('!!/rmwlu http://stackoverflow.com/users/0/test', get_user_from_list_command, ('0', 'stackoverflow.com')),
    ('!!/addwlu http://codegolf.stackexchange.com/users/9275/programfox', get_user_from_list_command, ('9275', 'codegolf.stackexchange.com')),
    ('!!/addwlu http://mathoverflow.net/users/66/ben-webster', get_user_from_list_command, ('66', 'mathoverflow.net')),
    ('!!/rmblu 1234 stackoverflow.com', get_user_from_list_command, ('1234', 'stackoverflow.com')),
    ('!!/rmwlu 4321 communitybuilding.stackexchange.com', get_user_from_list_command, ('4321', 'communitybuilding.stackexchange.com')),
    ('!!/addblu 1 stackoverflow', get_user_from_list_command, ('1', 'stackoverflow.com')),
    ('http://stackoverflow.com/questions/1/title-here', url_to_shortlink, 'http://stackoverflow.com/questions/1'),
    ('http://stackoverflow.com/questions/1/title-here/2#2', url_to_shortlink, 'http://stackoverflow.com/a/2'),
    ('http://writers.stackexchange.com/questions/1/%2f%2f', url_to_shortlink, 'http://writers.stackexchange.com/questions/1'),
    ('http://writers.stackexchange.com/questions/1/%2f%2f/2#2', url_to_shortlink, 'http://writers.stackexchange.com/a/2'),
    ('http://mathoverflow.net/q/1', url_to_shortlink, 'http://mathoverflow.net/questions/1'),
    ('http://stackoverflow.com/users/1234/abcd', user_url_to_shortlink, 'http://stackoverflow.com/u/1234'),
    ('http://stackexchange.com', to_protocol_relative, '//stackexchange.com'),
    ('https://stackexchange.com', to_protocol_relative, '//stackexchange.com'),
    ('//stackexchange.com', to_protocol_relative, '//stackexchange.com'),
    ('sd 2tpu', preprocess_shortcut_command, 'sd tpu tpu'),
    ('sd - 3tpu fp', preprocess_shortcut_command, 'sd - tpu tpu tpu fp'),
    ('sd 3- 2fp', preprocess_shortcut_command, 'sd - - - fp fp'),
    ('sd tpu fp ignore delete', preprocess_shortcut_command, 'sd tpu fp ignore delete'),
    ('sd 5-', preprocess_shortcut_command, 'sd - - - - -'),
    ('sd 15-', preprocess_shortcut_command, 'sd - - - - - - - - - - - - - - -'),
    ('sd  tpu', preprocess_shortcut_command, 'sd tpu'),
    ('sd 2 tpu', preprocess_shortcut_command, 'sd tpu tpu'),
    ('sd 10 tpu', preprocess_shortcut_command, 'sd tpu tpu tpu tpu tpu tpu tpu tpu tpu tpu'),
    ('sd fp 3   tpu', preprocess_shortcut_command, 'sd fp tpu tpu tpu'),
    (test_data_inputs[0], fetch_post_id_and_site_from_msg_content, ('246651', 'meta.stackexchange.com', 'question')),
    (test_data_inputs[0], fetch_owner_url_from_msg_content, 'http://meta.stackexchange.com/users/279263/lisa-usher'),
    (test_data_inputs[0], fetch_title_from_msg_content, 'Best Weight Loss Tips For Fast Results'),
    (test_data_inputs[1], fetch_post_url_from_msg_content, 'http://stackoverflow.com/questions/0/test-test'),
    (test_data_inputs[1], fetch_post_id_and_site_from_msg_content, ('0', 'stackoverflow.com', 'question')),
    (test_data_inputs[1], fetch_owner_url_from_msg_content, 'http://stackoverflow.com/users/0/test-test'),
    (test_data_inputs[1], fetch_title_from_msg_content, 'TEST TEST TEST ]]])))'),
    (test_data_inputs[2], fetch_post_url_from_msg_content, 'http://stackoverflow.com/questions/0/test-test/42#42'),
    (test_data_inputs[2], fetch_post_id_and_site_from_msg_content, ('42', 'stackoverflow.com', 'answer')),
    (test_data_inputs[2], fetch_owner_url_from_msg_content, 'http://stackoverflow.com/users/0/test-test'),
    (test_data_inputs[3], fetch_post_id_and_site_from_msg_content, ('27954020', 'stackoverflow.com', 'question')),
    (test_data_inputs[3], fetch_owner_url_from_msg_content, 'http://stackoverflow.com/users/3754535/user3754535'),
    (test_data_inputs[3], fetch_title_from_msg_content, "Why I can't insert data in a model from a custom controller?"),
    (test_data_inputs[4], fetch_post_id_and_site_from_msg_content, ('27954020', 'stackoverflow.com', 'question')),
    (test_data_inputs[4], fetch_owner_url_from_msg_content, None),
    (test_data_inputs[4], fetch_title_from_msg_content, "Why I can't insert data in a model from a custom controller?"),
    (test_data_inputs[5], fetch_post_id_and_site_from_msg_content, ('246651', 'meta.stackexchange.com', 'question')),
    (test_data_inputs[5], fetch_owner_url_from_msg_content, 'http://meta.stackexchange.com/users/279263/lisa-usher'),
    (test_data_inputs[5], fetch_title_from_msg_content, 'Best Weight Loss Tips For Fast Results'),
    (test_data_inputs[6], fetch_post_url_from_msg_content, 'http://stackoverflow.com/q/0'),
    (test_data_inputs[6], fetch_post_id_and_site_from_msg_content, ('0', 'stackoverflow.com', 'question')),
    (test_data_inputs[6], fetch_owner_url_from_msg_content, 'http://stackoverflow.com/users/0/test-test'),
    (test_data_inputs[6], fetch_title_from_msg_content, 'TEST TEST TEST ]]])))'),
    (test_data_inputs[7], fetch_post_url_from_msg_content, 'http://stackoverflow.com/a/42'),
    (test_data_inputs[7], fetch_post_id_and_site_from_msg_content, ('42', 'stackoverflow.com', 'answer')),
    (test_data_inputs[7], fetch_owner_url_from_msg_content, 'http://stackoverflow.com/users/0/test-test'),
    (test_data_inputs[8], fetch_post_id_and_site_from_msg_content, ('27954020', 'stackoverflow.com', 'question')),
    (test_data_inputs[8], fetch_owner_url_from_msg_content, 'http://stackoverflow.com/users/3754535/user3754535'),
    (test_data_inputs[8], fetch_title_from_msg_content, "Why I can't insert data in a model from a custom controller?"),
    (test_data_inputs[9], fetch_post_id_and_site_from_msg_content, ('27954020', 'stackoverflow.com', 'question')),
    (test_data_inputs[9], fetch_owner_url_from_msg_content, None),
    (test_data_inputs[9], fetch_title_from_msg_content, "Why I can't insert data in a model from a custom controller?"),
    (test_data_inputs[10], fetch_post_id_and_site_from_msg_content, ('27954020', 'stackoverflow.com', 'question')),
    (test_data_inputs[10], fetch_owner_url_from_msg_content, '//stackoverflow.com/users/3754535/user3754535'),
    (test_data_inputs[10], fetch_title_from_msg_content, "Why I can't insert data in a model from a custom controller?"),
    (test_data_inputs[11], fetch_post_id_and_site_from_msg_content, ('27954020', 'stackoverflow.com', 'question')),
    (test_data_inputs[11], fetch_owner_url_from_msg_content, '//stackoverflow.com/users/3754535/user3754535'),
    (test_data_inputs[11], fetch_title_from_msg_content, "Why I can't insert data in a model from a custom controller?"),
    (test_data_inputs[12], fetch_post_id_and_site_from_msg_content, ('458053', 'ru.stackoverflow.com', 'question')),
    (test_data_inputs[12], fetch_owner_url_from_msg_content, '//ru.stackoverflow.com/users/20555/ni55an'),
    (test_data_inputs[12], fetch_title_from_msg_content, '-----------------------------'),
    (test_data_inputs[13], fetch_post_id_and_site_from_msg_content, ('458053', 'ru.stackoverflow.com', 'question')),
    (test_data_inputs[13], fetch_owner_url_from_msg_content, '//ru.stackoverflow.com/users/20555/ni55an'),
    (test_data_inputs[13], fetch_title_from_msg_content, '-----------------------------'),
    (test_data_inputs[14], fetch_post_id_and_site_from_msg_content, ('27954020', 'stackoverflow.com', 'question')),
    (test_data_inputs[14], fetch_owner_url_from_msg_content, '//stackoverflow.com/users/3754535/user3754535'),
    (test_data_inputs[14], fetch_title_from_msg_content, "Why I can't insert data in a model from a custom controller?"),
    (test_data_inputs[15], fetch_post_id_and_site_from_msg_content, ('27954020', 'stackoverflow.com', 'question')),
    (test_data_inputs[15], fetch_owner_url_from_msg_content, '//stackoverflow.com/users/3754535/user3754535'),
    (test_data_inputs[15], fetch_title_from_msg_content, "Why I can't insert data in a model from a custom controller?"),
    (test_data_inputs[15], edited_message_after_postgone_command, "[ [SmokeDetector](https://github.com/Charcoal-SE/SmokeDetector) ] Manually reported question (batch report: post 2 out of 3): *(gone)* by [user3754535](//stackoverflow.com/users/3754535/user3754535) on `stackoverflow.com`"),
    (test_data_inputs[16], fetch_user_from_allspam_report, ('5733779', 'stackoverflow.com'))

])
def test_parsing(input_data, parse_method, expected):
    assert parse_method(input_data.strip()) == expected

Example 135

Project: indico Source File: mimetypes_test.py
@pytest.mark.parametrize(('mimetype', 'expected_icon'), (
    ('application/applixware', 'default_icon'),
    ('application/atom+xml', 'icon-file-xml'),
    ('application/cdmi-capability', 'default_icon'),
    ('application/dssc+der', 'default_icon'),
    ('application/ecmascript', 'default_icon'),
    ('application/json', 'icon-file-css'),
    ('application/msword', 'icon-file-word'),
    ('application/pdf', 'icon-file-pdf'),
    ('application/prs.cww', 'default_icon'),
    ('application/relax-ng-compact-syntax', 'default_icon'),
    ('application/resource-lists+xml', 'icon-file-xml'),
    ('application/vnd.3gpp.pic-bw-large', 'default_icon'),
    ('application/vnd.openofficeorg.extension', 'default_icon'),
    ('application/vnd.openxmlformats-officedocuement.presentationml.presentation', 'icon-file-presentation'),
    ('application/vnd.openxmlformats-officedocuement.presentationml.slide', 'default_icon'),
    ('application/vnd.openxmlformats-officedocuement.presentationml.slideshow', 'default_icon'),
    ('application/vnd.openxmlformats-officedocuement.presentationml.template', 'default_icon'),
    ('application/vnd.openxmlformats-officedocuement.spreadsheetml.sheet', 'icon-file-excel'),
    ('application/vnd.openxmlformats-officedocuement.spreadsheetml.template', 'default_icon'),
    ('application/vnd.openxmlformats-officedocuement.wordprocessingml.docuement', 'icon-file-word'),
    ('application/vnd.openxmlformats-officedocuement.wordprocessingml.template', 'default_icon'),
    ('application/vnd.oasis.opendocuement.chart', 'icon-file-openoffice'),
    ('application/vnd.oasis.opendocuement.chart', 'icon-file-openoffice'),
    ('application/vnd.oasis.opendocuement.chart-template', 'icon-file-openoffice'),
    ('application/vnd.oasis.opendocuement.database', 'icon-file-openoffice'),
    ('application/vnd.oasis.opendocuement.formula', 'icon-file-openoffice'),
    ('application/vnd.oasis.opendocuement.formula-template', 'icon-file-openoffice'),
    ('application/vnd.oasis.opendocuement.graphics', 'icon-file-openoffice'),
    ('application/vnd.oasis.opendocuement.graphics-template', 'icon-file-openoffice'),
    ('application/vnd.oasis.opendocuement.image', 'icon-file-openoffice'),
    ('application/vnd.oasis.opendocuement.image-template', 'icon-file-openoffice'),
    ('application/vnd.oasis.opendocuement.presentation', 'icon-file-openoffice'),
    ('application/vnd.oasis.opendocuement.presentation-template', 'icon-file-openoffice'),
    ('application/vnd.oasis.opendocuement.spreadsheet', 'icon-file-openoffice'),
    ('application/vnd.oasis.opendocuement.spreadsheet-template', 'icon-file-openoffice'),
    ('application/vnd.oasis.opendocuement.text', 'icon-file-openoffice'),
    ('application/vnd.oasis.opendocuement.text-master', 'icon-file-openoffice'),
    ('application/vnd.oasis.opendocuement.text-template', 'icon-file-openoffice'),
    ('application/vnd.oasis.opendocuement.text-web', 'icon-file-openoffice'),
    ('application/vnd.ms-artgalry', 'default_icon'),
    ('application/vnd.ms-cab-compressed', 'default_icon'),
    ('application/vnd.ms-excel', 'icon-file-excel'),
    ('application/vnd.ms-excel.addin.macroenabled.12', 'default_icon'),
    ('application/vnd.ms-excel.sheet.binary.macroenabled.12', 'default_icon'),
    ('application/vnd.ms-excel.sheet.macroenabled.12', 'default_icon'),
    ('application/vnd.ms-excel.template.macroenabled.12', 'default_icon'),
    ('application/vnd.ms-fontobject', 'default_icon'),
    ('application/vnd.ms-htmlhelp', 'default_icon'),
    ('application/vnd.ms-ims', 'default_icon'),
    ('application/vnd.ms-lrm', 'default_icon'),
    ('application/vnd.ms-officetheme', 'default_icon'),
    ('application/vnd.ms-pki.seccat', 'default_icon'),
    ('application/vnd.ms-pki.stl', 'default_icon'),
    ('application/vnd.ms-powerpoint', 'icon-file-presentation'),
    ('application/vnd.ms-powerpoint.addin.macroenabled.12', 'default_icon'),
    ('application/vnd.ms-powerpoint.presentation.macroenabled.12', 'default_icon'),
    ('application/vnd.ms-powerpoint.slide.macroenabled.12', 'default_icon'),
    ('application/vnd.ms-powerpoint.slideshow.macroenabled.12', 'default_icon'),
    ('application/vnd.ms-powerpoint.template.macroenabled.12', 'default_icon'),
    ('application/vnd.ms-project', 'default_icon'),
    ('application/vnd.ms-word.docuement.macroenabled.12', 'default_icon'),
    ('application/vnd.ms-word.template.macroenabled.12', 'default_icon'),
    ('application/vnd.ms-works', 'default_icon'),
    ('application/vnd.ms-wpl', 'default_icon'),
    ('application/vnd.ms-xpsdocuement', 'default_icon'),
    ('application/vnd.zzazz.deck+xml', 'icon-file-xml'),
    ('application/x-7z-compressed', 'icon-file-zip'),
    ('application/x-ace-compressed', 'icon-file-zip'),
    ('application/x-bzip', 'icon-file-zip'),
    ('application/x-bzip2', 'icon-file-zip'),
    ('application/x-dtbncx+xml', 'icon-file-xml'),
    ('application/xhtml+xml', 'icon-file-xml'),
    ('application/xml', 'icon-file-xml'),
    ('application/zip', 'icon-file-zip'),
    ('audio/adpcm', 'icon-file-music'),
    ('audio/basic', 'icon-file-music'),
    ('audio/midi', 'icon-file-music'),
    ('audio/mp4', 'icon-file-music'),
    ('audio/mpeg', 'icon-file-music'),
    ('audio/ogg', 'icon-file-music'),
    ('audio/vnd.dece.audio', 'icon-file-music'),
    ('audio/vnd.digital-winds', 'icon-file-music'),
    ('audio/x-aac', 'icon-file-music'),
    ('chemical/x-cdx', 'default_icon'),
    ('image/bmp', 'icon-file-image'),
    ('image/cgm', 'icon-file-image'),
    ('image/g3fax', 'icon-file-image'),
    ('image/gif', 'icon-file-image'),
    ('image/ief', 'icon-file-image'),
    ('image/jpeg', 'icon-file-image'),
    ('image/ktx', 'icon-file-image'),
    ('image/png', 'icon-file-image'),
    ('image/prs.btif', 'icon-file-image'),
    ('image/svg+xml', 'icon-file-image'),
    ('image/tiff', 'icon-file-image'),
    ('image/vnd.adobe.photoshop', 'icon-file-image'),
    ('image/vnd.dece.graphic', 'icon-file-image'),
    ('image/vnd.dvb.subtitle', 'icon-file-image'),
    ('image/vnd.djvu', 'icon-file-image'),
    ('image/vnd.dwg', 'icon-file-image'),
    ('image/vnd.dxf', 'icon-file-image'),
    ('image/vnd.fastbidsheet', 'icon-file-image'),
    ('image/vnd.fpx', 'icon-file-image'),
    ('image/vnd.fst', 'icon-file-image'),
    ('image/vnd.fujixerox.edmics-mmr', 'icon-file-image'),
    ('image/vnd.fujixerox.edmics-rlc', 'icon-file-image'),
    ('image/vnd.ms-modi', 'icon-file-image'),
    ('image/vnd.net-fpx', 'icon-file-image'),
    ('image/vnd.wap.wbmp', 'icon-file-image'),
    ('image/vnd.xiff', 'icon-file-image'),
    ('image/webp', 'icon-file-image'),
    ('image/x-cmu-raster', 'icon-file-image'),
    ('image/x-cmx', 'icon-file-image'),
    ('image/x-freehand', 'icon-file-image'),
    ('image/x-icon', 'icon-file-image'),
    ('image/x-pcx', 'icon-file-image'),
    ('image/x-pict', 'icon-file-image'),
    ('image/x-portable-anymap', 'icon-file-image'),
    ('image/x-portable-bitmap', 'icon-file-image'),
    ('image/x-portable-graymap', 'icon-file-image'),
    ('image/x-portable-pixmap', 'icon-file-image'),
    ('image/x-rgb', 'icon-file-image'),
    ('image/x-xbitmap', 'icon-file-image'),
    ('image/x-xpixmap', 'icon-file-image'),
    ('image/x-xwindowdump', 'icon-file-image'),
    ('text/calendar', 'icon-calendar'),
    ('text/css', 'icon-file-css'),
    ('text/csv', 'icon-file-spreadsheet'),
    ('text/html', 'icon-file-xml'),
    ('text/n3', 'icon-file-xml'),
    ('text/plain', 'icon-file-text'),
    ('text/plain-bas', 'icon-file-text'),
    ('text/prs.lines.tag', 'icon-file-text'),
    ('text/richtext', 'icon-file-text'),
    ('text/sgml', 'icon-file-xml'),
    ('text/tab-separated-values', 'icon-file-spreadsheet'),
    ('video/h264', 'icon-file-video'),
    ('video/jpeg', 'icon-file-video'),
    ('video/jpm', 'icon-file-video'),
    ('video/mj2', 'icon-file-video'),
    ('video/mp4', 'icon-file-video'),
    ('video/mpeg', 'icon-file-video'),
    ('video/ogg', 'icon-file-video'),
    ('video/quicktime', 'icon-file-video'),
    ('video/vnd.dece.hd', 'icon-file-video'),
    ('video/vnd.dece.mobile', 'icon-file-video'),
    ('video/x-f4v', 'icon-file-video'),
    ('video/x-fli', 'icon-file-video'),
    ('video/x-flv', 'icon-file-video'),
    ('video/x-m4v', 'icon-file-video'),
    ('video/x-ms-asf', 'icon-file-video'),
    ('video/x-ms-wm', 'icon-file-video'),
    ('video/x-ms-wmv', 'icon-file-video'),
    ('video/x-ms-wmx', 'icon-file-video'),
    ('video/x-ms-wvx', 'icon-file-video'),
    ('video/x-msvideo', 'icon-file-video'),
    ('video/x-sgi-movie', 'icon-file-video'),
    ('x-conference/x-cooltalk', 'default_icon')
))
def test_icon_from_mimetype(mimetype, expected_icon):
    assert icon_from_mimetype(mimetype, default_icon='default_icon') == expected_icon

Example 136

Project: astrodendro Source File: test_structure.py
@pytest.mark.parametrize('index', [(0,), (1, 3), (4, 5, 9)])
def test_init_branch_scalar_3_level(index):

    leaf_index = tuple([10 for i in range(len(index))])
    leaf = Structure(leaf_index, 20.)
    leaf_indices = leaf.indices(subtree=False)

    branch_index = tuple([9 for i in range(len(index))])
    branch = Structure(branch_index, 15., children=[leaf])
    branch_indices = branch.indices(subtree=False)

    s = Structure(index, 1.5, children=[branch])

    # Properties
    assert s.idx is None
    assert not s.is_leaf
    assert s.is_branch

    indices = tuple(np.atleast_1d(i) for i in index)
    indices_all = tuple(np.hstack(a)
                        for a in zip(indices, branch_indices, leaf_indices))
    assert_identical_fancyindex(s.indices(subtree=False), indices)
    assert_identical_fancyindex(s.indices(subtree=True), indices_all)

    assert np.all(s.values(subtree=False) == np.array([1.5]))
    assert np.all(s.values(subtree=True) == np.hstack((s.values(subtree=False), branch.values(subtree=False), leaf.values(subtree=False))))
    assert s.vmin == 1.5
    assert s.vmax == 1.5
    assert s.height == 15.
    assert s.level == 0
    assert s.ancestor is s
    assert s.parent is None
    assert s.children == [branch]
    assert set(s.descendants) == set([branch, leaf])  # order should not matter

    # Branch properties
    assert branch.level == 1
    assert branch.ancestor is s
    assert branch.parent is s
    assert branch.children == [leaf]
    assert branch.descendants == [leaf]

    # Leaf properties
    assert leaf.level == 2
    assert leaf.ancestor is s
    assert leaf.parent is branch
    assert leaf.children == []
    assert leaf.descendants == []

    # Methods
    assert s.get_npix(subtree=False) == 1
    assert s.get_peak(subtree=False) == (index, 1.5)
    assert s.get_npix(subtree=True) == 3
    assert s.get_peak(subtree=True) == (leaf_index, 20.)

    # Footprint
    array = np.zeros([20 for i in range(len(index))])
    s._fill_footprint(array, level=2)
    assert array[index] == 2.
    assert array[branch_index] == 3.
    assert array[leaf_index] == 4.
    assert np.sum(array) == 9.

Example 137

Project: siilo Source File: test_amazon_s3.py
Function: test_url
    @pytest.mark.parametrize(
        (
            'region',
            'use_path_style',
            'use_https',
            'use_query_string_auth',
            'url_expires',
            'key',
            'url',
        ),
        [
            (
                'eu-west-1',
                False,
                True,
                False,
                None,
                'test.txt',
                'https://examplebucket.s3-eu-west-1.amazonaws.com/test.txt',
            ),
            (
                'eu-west-1',
                True,
                False,
                False,
                None,
                'test.txt',
                'http://s3-eu-west-1.amazonaws.com/examplebucket/test.txt',
            ),
            (
                'us-east-1',
                False,
                False,
                False,
                None,
                'test.txt',
                'http://examplebucket.s3.amazonaws.com/test.txt',
            ),
            (
                'us-east-1',
                True,
                True,
                False,
                None,
                'test.txt',
                'https://s3.amazonaws.com/examplebucket/test.txt',
            ),
            (
                'us-east-1',
                False,
                True,
                True,
                timedelta(hours=24),
                'test.txt',
                (
                    'https://examplebucket.s3.amazonaws.com/test.txt?'
                    'X-Amz-Algorithm=AWS4-HMAC-SHA256&'
                    'X-Amz-Credential=AKIAIOSFODNN7EXAMPLE%2F20130524%2F'
                    'us-east-1%2Fs3%2Faws4_request&'
                    'X-Amz-Date=20130524T000000Z&'
                    'X-Amz-Expires=86400&'
                    'X-Amz-Signature=aeeed9bbccd4d02ee5c0109b86d86835f995330da'
                    '4c265957d157751f604d404&'
                    'X-Amz-SignedHeaders=host'
                )
            ),
            (
                'us-east-1',
                False,
                False,
                False,
                None,
                u'åöä',
                'http://examplebucket.s3.amazonaws.com/%C3%A5%C3%B6%C3%A4',
            ),
            (
                'us-east-1',
                False,
                False,
                True,
                timedelta(hours=1),
                u'åöä',
                (
                    'http://examplebucket.s3.amazonaws.com/%C3%A5%C3%B6%C3%A4?'
                    'X-Amz-Algorithm=AWS4-HMAC-SHA256&'
                    'X-Amz-Credential=AKIAIOSFODNN7EXAMPLE%2F20130524%2F'
                    'us-east-1%2Fs3%2Faws4_request&'
                    'X-Amz-Date=20130524T000000Z&'
                    'X-Amz-Expires=3600&'
                    'X-Amz-Signature=0921cdcbd2d64caa66dce47683e9807fef8f71ea2'
                    '404c4ae50dd02b88e69a438&'
                    'X-Amz-SignedHeaders=host'
                )
            ),
        ]
    )
    def test_url(self, region, use_path_style, use_https,
                 use_query_string_auth, url_expires, key, url):
        with freezegun.freeze_time('2013-05-24'):
            storage = self.make_storage(
                region=region,
                use_path_style=use_path_style,
                use_https=use_https,
                use_query_string_auth=use_query_string_auth,
                url_expires=url_expires
            )
            assert storage.url(key) == url

Example 138

Project: hope Source File: test_ufig.py
@pytest.mark.parametrize("dtype", [float, np.float32, np.float64])
def test_ufig_star(dtype):
    b = 3.5
    a = 1. / np.sqrt(2. ** (1. / (b - 1.)) - 1.)
    r50 = 2

    center = np.array([10.141, 10.414])
    dims = np.array([20, 20])
    # coefficients generated by http://keisan.casio.com/has10/SpecExec.cgi?id=system/2006/1280624821, 7th order
    x1D = np.array([ \
          0.5 - 0.9491079123427585245262 / 2 \
        , 0.5 - 0.7415311855993944398639 / 2 \
        , 0.5 - 0.4058451513773971669066 / 2 \
        , 0.5 \
        , 0.5 + 0.4058451513773971669066 / 2 \
        , 0.5 + 0.7415311855993944398639 / 2 \
        , 0.5 + 0.9491079123427585245262 / 2 \
    ], dtype=dtype)
    w1D = np.array([ \
          0.1294849661688696932706 / 2 \
        , 0.2797053914892766679015 / 2 \
        , 0.38183005050511894495 / 2 \
        , 0.4179591836734693877551 / 2 \
        , 0.38183005050511894495 / 2 \
        , 0.2797053914892766679015 / 2 \
        , 0.1294849661688696932706 / 2 \
    ], dtype=dtype)
    w2D = np.outer(w1D, w1D)
    def fkt_pdf(density, dims, center, w2D, r50, b, a):
        for x in range(dims[0]):
            for y in range(dims[1]):
                dr = np.sqrt((x - center[0]) ** 2 + (y - center[1]) ** 2)
                density[x, y] = np.sum(w2D * 2 * (b - 1) / (2 * np.pi * (r50 * a)**2) * (1 + (dr / (r50 * a))**2)**(-b))
        return density
    hope.config.optimize = True
    hpdf = hope.jit(fkt_pdf)

    density = np.zeros((dims[0], dims[1]), dtype=dtype)
    fkt_pdf(density, dims, center, w2D, r50, b, a)
    hdensity = np.zeros((dims[0], dims[1]), dtype=dtype)
    hpdf(hdensity, dims, center, w2D, r50, b, a)
    hope.config.optimize = False
#     print("going to sleep")
#     import time
#     time.sleep(10)
    assert check(density, hdensity)

    if np.all(hdensity == 1):
        print("asdf")
    else:
        print("else")

Example 139

Project: tinycss Source File: test_tokenizer.py
Function: test_tokens
@pytest.mark.parametrize(('tokenize', 'css_source', 'expected_tokens'), [
    (tokenize,) + test_data
    for tokenize in (python_tokenize_flat, cython_tokenize_flat)
    for test_data in [
        ('', []),
        ('red -->', [('IDENT', 'red'), ('S', ' '), ('CDC', '-->')]),
        # Longest match rule: no CDC
        ('red-->', [('IDENT', 'red--'), ('DELIM', '>')]),
        (r'p[example="foo(int x) {    this.x = x;}"]', [
            ('IDENT', 'p'),
            ('[', '['),
            ('IDENT', 'example'),
            ('DELIM', '='),
            ('STRING', 'foo(int x) {    this.x = x;}'),
            (']', ']')]),

        # Numbers are parsed
        ('42 .5 -4pX 1.25em 30%', [
            ('INTEGER', 42), ('S', ' '),
            ('NUMBER', .5), ('S', ' '),
            # units are normalized to lower-case:
            ('DIMENSION', -4, 'px'), ('S', ' '),
            ('DIMENSION', 1.25, 'em'), ('S', ' '),
            ('PERCENTAGE', 30, '%')]),

        # URLs are extracted
        ('url(foo.png)', [('URI', 'foo.png')]),
        ('url("foo.png")', [('URI', 'foo.png')]),

        # Escaping

        (r'/* Comment with a \ backslash */', [
            ('COMMENT', '/* Comment with a \ backslash */')]),  # Unchanged

        # backslash followed by a newline in a string: ignored
        ('"Lorem\\\nIpsum"', [('STRING', 'LoremIpsum')]),

        # backslash followed by a newline outside a string: stands for itself
        ('Lorem\\\nIpsum', [
            ('IDENT', 'Lorem'), ('DELIM', '\\'),
            ('S', '\n'), ('IDENT', 'Ipsum')]),

        # Cancel the meaning of special characters
        (r'"Lore\m Ipsum"', [('STRING', 'Lorem Ipsum')]),  # or not specal
        (r'"Lorem \49psum"', [('STRING', 'Lorem Ipsum')]),
        (r'"Lorem \49 psum"', [('STRING', 'Lorem Ipsum')]),
        (r'"Lorem\"Ipsum"', [('STRING', 'Lorem"Ipsum')]),
        (r'"Lorem\\Ipsum"', [('STRING', r'Lorem\Ipsum')]),
        (r'"Lorem\5c Ipsum"', [('STRING', r'Lorem\Ipsum')]),
        (r'Lorem\+Ipsum', [('IDENT', 'Lorem+Ipsum')]),
        (r'Lorem+Ipsum', [
            ('IDENT', 'Lorem'), ('DELIM', '+'), ('IDENT', 'Ipsum')]),
        (r'url(foo\).png)', [('URI', 'foo).png')]),

        # Unicode and backslash escaping
        ('\\26 B', [('IDENT', '&B')]),
        ('\\&B', [('IDENT', '&B')]),
        ('@\\26\tB', [('ATKEYWORD', '@&B')]),
        ('@\\&B', [('ATKEYWORD', '@&B')]),
        ('#\\26\nB', [('HASH', '#&B')]),
        ('#\\&B', [('HASH', '#&B')]),
        ('\\26\r\nB(', [('FUNCTION', '&B(')]),
        ('\\&B(', [('FUNCTION', '&B(')]),
        (r'12.5\000026B', [('DIMENSION', 12.5, '&b')]),
        (r'12.5\0000263B', [('DIMENSION', 12.5, '&3b')]),  # max 6 digits
        (r'12.5\&B', [('DIMENSION', 12.5, '&b')]),
        (r'"\26 B"', [('STRING', '&B')]),
        (r"'\000026B'", [('STRING', '&B')]),
        (r'"\&B"', [('STRING', '&B')]),
        (r'url("\26 B")', [('URI', '&B')]),
        (r'url(\26 B)', [('URI', '&B')]),
        (r'url("\&B")', [('URI', '&B')]),
        (r'url(\&B)', [('URI', '&B')]),
        (r'Lorem\110000Ipsum', [('IDENT', 'Lorem\uFFFDIpsum')]),

        # Bad strings

        # String ends at EOF without closing: no error, parsed
        ('"Lorem\\26Ipsum', [('STRING', 'Lorem&Ipsum')]),
        # Unescaped newline: ends the string, error, unparsed
        ('"Lorem\\26Ipsum\n', [
            ('BAD_STRING', r'"Lorem\26Ipsum'), ('S', '\n')]),
        # Tokenization restarts after the newline, so the second " starts
        # a new string (which ends at EOF without errors, as above.)
        ('"Lorem\\26Ipsum\ndolor" sit', [
            ('BAD_STRING', r'"Lorem\26Ipsum'), ('S', '\n'),
            ('IDENT', 'dolor'), ('STRING', ' sit')]),

    ]])
def test_tokens(tokenize, css_source, expected_tokens):
    if tokenize is None:  # pragma: no cover
        pytest.skip('Speedups not available')
    sources = [css_source]
    if sys.version_info[0] < 3:
        # On Python 2.x, ASCII-only bytestrings can be used
        # where Unicode is expected.
        sources.append(css_source.encode('ascii'))
    for css_source in sources:
        tokens = tokenize(css_source, ignore_comments=False)
        result = [
            (token.type, token.value) + (
                () if token.unit is None else (token.unit,))
            for token in tokens
        ]
        assert result == expected_tokens

Example 140

Project: google-ngram-downloader Source File: test_main.py
Function: test_cooccurrence
@pytest.mark.parametrize(
    'verbose',
    (
        (False, ),
        (True, ),
    ),
)
def test_cooccurrence(tmpdir, monkeypatch, verbose):
    objects = []

    def modked_open(obj, *args, **kwargs):
        @contextmanager
        def _open(*args, **kwargs):
            class MockedGzipFile(object):
                def writelines(self, lines):
                    objects.extend(list(lines))
            yield MockedGzipFile()

        return _open()

    monkeypatch.setattr(util, 'get_indices', lambda ngram_len: ['a'])

    cooccurrence.command(
        '-o {tmpdir} -n 5 --records-in-file 3 {verbose}'
        ''.format(
            tmpdir=tmpdir,
            verbose='-v' if verbose else '',
        ).split()
    )

    def read(f_name):
        with gzip.open(str(f_name), mode='rb') as f:
            return sorted(f.read().decode('utf-8').split(u'\n'))

    result_one, result_two = map(read, tmpdir.listdir(sort=True))

    assert result_one == [
        u'',
        u'often\tanalysis\t6',
        u'often\tas\t6',
        u'often\tdescribed\t6',
        u'often\tis\t6',
    ]

    assert result_two == [
        u'',
        u'REPETITION\taa\t40',
        u'UNICODE\tу\t46',
        u'UNICODE\tю\t46',
        u'WORD\tc1\t100',
        u'WORD\tc2\t100',
        u'WORD\tc3\t100',
        u'WORD\tc4\t100',
    ]

Example 141

Project: instaseis Source File: test_server_finite_source.py
@pytest.mark.parametrize("usgs_param", [USGS_PARAM_FILE_1, USGS_PARAM_FILE_2])
def test_more_complex_queries(reciprocal_clients_all_callbacks,
                              usgs_param):
    """
    These are not exhaustive tests but test that the queries do something.
    Elsewhere they are tested in more details.

    Test phase relative offsets.

    + must be encoded with %2B
    - must be encoded with %2D
    """
    client = reciprocal_clients_all_callbacks
    db = instaseis.open_db(client.filepath)

    basic_parameters = {
        "receiverlongitude": 11,
        "receiverlatitude": 22,
        "components": "".join(db.available_components),
        "format": "miniseed"}

    with io.open(usgs_param, "rb") as fh:
        body = fh.read()

    # default parameters
    params = copy.deepcopy(basic_parameters)
    params["dt"] = 2
    request = client.fetch(_assemble_url('finite_source', **params),
                           method="POST", body=body)
    assert request.code == 200
    st = obspy.read(request.buffer)

    # Now request one starting ten seconds later.
    params = copy.deepcopy(basic_parameters)
    params["starttime"] = 10
    params["dt"] = 2
    request = client.fetch(_assemble_url('finite_source', **params),
                           method="POST", body=body)
    assert request.code == 200
    st_2 = obspy.read(request.buffer)

    assert st[0].stats.starttime + 10 == st_2[0].stats.starttime

    # The rest of data should still be identical.
    np.testing.assert_allclose(st.slice(starttime=10)[0].data, st_2[0].data)

    # Try with the endtime.
    params = copy.deepcopy(basic_parameters)
    params["endtime"] = 20
    params["dt"] = 2
    request = client.fetch(_assemble_url('finite_source', **params),
                           method="POST", body=body)
    assert request.code == 200
    st_2 = obspy.read(request.buffer)

    assert st_2[0].stats.endtime == st[0].stats.starttime + 20

    # The rest of data should still be identical.
    np.testing.assert_allclose(
        st.slice(endtime=st[0].stats.starttime + 20)[0].data,
        st_2[0].data)

    # Phase relative start and endtimes.
    params = copy.deepcopy(basic_parameters)
    params["starttime"] = "P%2D5"
    params["endtime"] = "P%2B5"
    params["dt"] = 2
    request = client.fetch(_assemble_url('finite_source', **params),
                           method="POST", body=body)
    assert request.code == 200
    st_2 = obspy.read(request.buffer)

    # Just make sure they actually do something.
    assert st_2[0].stats.starttime > st[0].stats.starttime
    assert st_2[0].stats.endtime < st[0].stats.endtime

    # Mixing things
    params = copy.deepcopy(basic_parameters)
    params["starttime"] = "P%2D5"
    params["endtime"] = "50"
    params["dt"] = 2
    request = client.fetch(_assemble_url('finite_source', **params),
                           method="POST", body=body)
    assert request.code == 200
    st_2 = obspy.read(request.buffer)

    # Just make sure they actually do something.
    assert st_2[0].stats.starttime > st[0].stats.starttime
    assert st_2[0].stats.endtime < st[0].stats.endtime

    if "Z" not in db.available_components:
        return

    # Network and station searches.
    params = {
        "network": "IU,B*",
        "station": "ANT*,ANM?",
        "components": "Z",
        "format": "miniseed"}
    request = client.fetch(_assemble_url('finite_source', **params),
                           method="POST", body=body)
    assert request.code == 200
    st_2 = obspy.read(request.buffer)

    assert sorted(tr.id for tr in st_2) == ["IU.ANMO..LXZ", "IU.ANTO..LXZ"]

Example 142

Project: pypackage Source File: test_configure.py
@pytest.mark.parametrize(
    "flags, banner",
    [
        ("-e", "Starting interactive build..."),
        ("-re", "Reconfiguring..."),
    ],
    ids=("extended/normal", "re-build")
)
def test_interactive_setup(capfd, reset_sys_argv, move_home_pypackage,
                           flags, banner):
    """Ensure the calls made and feedback during the interactive setup."""

    conf = Config()
    sys.argv = ["py-build", flags]
    opts = get_options()

    standard_patch = mock.patch.object(
        configure,
        "standard_attributes",
        return_value=["standard"],
    )
    feature_patch = mock.patch.object(
        configure,
        "feature_attributes",
        return_value=["feature"],
    )
    extended_patch = mock.patch.object(
        configure,
        "extended_attributes",
        return_value=["extended"],
    )
    set_value_patch = mock.patch.object(configure, "set_value_in_config")

    with standard_patch:
        with feature_patch:
            with extended_patch:
                with set_value_patch as patched_set_value:
                    assert configure.run_interactive_setup(conf, opts) == conf

    expected_calls = [
        mock.call.Call("standard", conf, conf._KEYS),
        mock.call.Call("feature", conf, conf._PYPACKAGE_KEYS),
        mock.call.Call("extended", conf, conf._KEYS),
    ]
    assert patched_set_value.mock_calls == expected_calls

    out, err = capfd.readouterr()
    assert banner in out
    assert "~ Standard Attributes ~" in out
    assert "~ Pypackage Features ~" in out
    assert "~ Extended Attributes ~" in out
    assert not err

Example 143

Project: ktbs Source File: test_rdfrest_utils_prefix_conjunctive_view.py
Function: test_triples
    @mark.parametrize("datasetname, triple_or_quad, expected", [
                ('p12', (EX.x1, EX.p, EX.x2), {(EX.x1, EX.p, EX.x2)}),
                ('p12', (EX.x2, EX.p, EX.x3), {(EX.x2, EX.p, EX.x3)}),
                ('p12', (EX.x3, EX.p, EX.x4), {(EX.x3, EX.p, EX.x4)}),
                ('p12', (EX.xa, EX.p, EX.xb), set()),
                ('p12', (EX.xb, EX.p, EX.xc), set()),
                ('p12', (EX.x0, EX.p, EX.xc), set()),

                ('pab', (EX.x1, EX.p, EX.x2), set()),
                ('pab', (EX.x2, EX.p, EX.x3), set()),
                ('pab', (EX.x3, EX.p, EX.x4), set()),
                ('pab', (EX.xa, EX.p, EX.xb), {(EX.xa, EX.p, EX.xb)}),
                ('pab', (EX.xb, EX.p, EX.xc), {(EX.xb, EX.p, EX.xc)}),
                ('pab', (EX.x0, EX.p, EX.xc), set()),

                ('p12', (EX.x1, EX.p, EX.x2, EX['g1/']), {(EX.x1, EX.p, EX.x2)}),
                ('p12', (EX.x1, EX.p, EX.x2, EX['g1/g2']), set()),
                ('p12', (EX.x2, EX.p, EX.x3, EX['g1/']), set()),
                ('p12', (EX.x2, EX.p, EX.x3, EX['g1/g2']), {(EX.x2, EX.p, EX.x3)}),
                ('p12', (EX.x3, EX.p, EX.x4, EX['g1/']), set()),
                ('p12', (EX.x3, EX.p, EX.x4, EX['g1/g2']), {(EX.x3, EX.p, EX.x4)}),
                ('p12', (EX.xa, EX.p, EX.xb, EX['pab/ga']), set()),
                ('p12', (EX.xa, EX.p, EX.xb, EX['pab/gb']), set()),
                ('p12', (EX.xb, EX.p, EX.xc, EX['pab/ga']), set()),
                ('p12', (EX.xb, EX.p, EX.xc, EX['pab/gb']), set()),

                ('pab', (EX.x1, EX.p, EX.x2, EX['g1/']), set()),
                ('pab', (EX.x1, EX.p, EX.x2, EX['g1/g2']), set()),
                ('pab', (EX.x2, EX.p, EX.x3, EX['g1/']), set()),
                ('pab', (EX.x2, EX.p, EX.x3, EX['g1/g2']), set()),
                ('pab', (EX.x3, EX.p, EX.x4, EX['g1/']), set()),
                ('pab', (EX.x3, EX.p, EX.x4, EX['g1/g2']), set()),
                ('pab', (EX.xa, EX.p, EX.xb, EX['pab/ga']), {(EX.xa, EX.p, EX.xb)}),
                ('pab', (EX.xa, EX.p, EX.xb, EX['pab/gb']), set()),
                ('pab', (EX.xb, EX.p, EX.xc, EX['pab/ga']), set()),
                ('pab', (EX.xb, EX.p, EX.xc, EX['pab/gb']), {(EX.xb, EX.p, EX.xc)}),

                ('p12', (EX.x1, None, None), {(EX.x1, EX.p, EX.x2)}),
                ('p12', (EX.x2, None, None), {(EX.x2, EX.p, EX.x3)}),
                ('p12', (EX.x3, None, None), {(EX.x3, EX.p, EX.x4)}),
                ('p12', (EX.xa, None, None), set()),
                ('p12', (EX.xb, None, None), set()),
                ('p12', (EX.x0, None, None), set()),

                ('pab', (EX.x1, None, None), set()),
                ('pab', (EX.x2, None, None), set()),
                ('pab', (EX.x3, None, None), set()),
                ('pab', (EX.xa, None, None), {(EX.xa, EX.p, EX.xb)}),
                ('pab', (EX.xb, None, None), {(EX.xb, EX.p, EX.xc)}),
                ('pab', (EX.x0, None, None), set()),

                ('p12', (EX.x1, None, None, EX['g1/']), {(EX.x1, EX.p, EX.x2)}),
                ('p12', (EX.x1, None, None, EX['g1/g2']), set()),
                ('p12', (EX.x2, None, None, EX['g1/']), set()),
                ('p12', (EX.x2, None, None, EX['g1/g2']), {(EX.x2, EX.p, EX.x3)}),
                ('p12', (EX.x3, None, None, EX['g1/']), set()),
                ('p12', (EX.x3, None, None, EX['g1/g2']), {(EX.x3, EX.p, EX.x4)}),
                ('p12', (EX.xa, None, None, EX['pab/ga']), set()),
                ('p12', (EX.xa, None, None, EX['pab/gb']), set()),
                ('p12', (EX.xb, None, None, EX['pab/ga']), set()),
                ('p12', (EX.xb, None, None, EX['pab/gb']), set()),

                ('pab', (EX.x1, None, None, EX['g1/']), set()),
                ('pab', (EX.x1, None, None, EX['g1/g2']), set()),
                ('pab', (EX.x2, None, None, EX['g1/']), set()),
                ('pab', (EX.x2, None, None, EX['g1/g2']), set()),
                ('pab', (EX.x3, None, None, EX['g1/']), set()),
                ('pab', (EX.x3, None, None, EX['g1/g2']), set()),
                ('pab', (EX.xa, None, None, EX['pab/ga']), {(EX.xa, EX.p, EX.xb)}),
                ('pab', (EX.xa, None, None, EX['pab/gb']), set()),
                ('pab', (EX.xb, None, None, EX['pab/ga']), set()),
                ('pab', (EX.xb, None, None, EX['pab/gb']), {(EX.xb, EX.p, EX.xc)}),

                ('p12', (None, None, None), {(EX.x1, EX.p, EX.x2),
                                             (EX.x2, EX.p, EX.x3),
                                             (EX.x3, EX.p, EX.x4),
                }),
                ('pab', (None, None, None), {(EX.xa, EX.p, EX.xb),
                                             (EX.xb, EX.p, EX.xc),
                }),

                ('p12', (None, None, None, EX['g1/']), {
                    (EX.x1, EX.p, EX.x2),
                }),
                ('p12', (None, None, None, EX['g1/g2']), {
                    (EX.x2, EX.p, EX.x3),
                    (EX.x3, EX.p, EX.x4),
                }),
                ('p12', (None, None, None, EX['pab/ga']), set()),

                ('pab', (None, None, None, EX['pab/ga']), {
                    (EX.xa, EX.p, EX.xb),
                }),
                ('pab', (None, None, None, EX['pab/gb']), {
                    (EX.xb, EX.p, EX.xc),
                }),
                ('pab', (None, None, None, EX['g1/']), set()),
    ])
    def test_triples(self, datasetname, triple_or_quad, expected):
        dataset = getattr(self, datasetname)
        assert set(dataset.triples(triple_or_quad)) == set(expected)

Example 144

Project: doctr Source File: test_travis.py
@pytest.mark.parametrize("src", ["src"])
@pytest.mark.parametrize("dst", ['.', 'dst'])
def test_sync_from_log(src, dst):
    with tempfile.TemporaryDirectory() as dir:
        try:
            old_curdir = os.path.abspath(os.curdir)
            os.chdir(dir)

            # Set up a src directory with some files
            os.makedirs(src)

            with open(join(src, 'test1'), 'w') as f:
                f.write('test1')

            os.makedirs(join(src, 'testdir'))
            with open(join(src, 'testdir', 'test2'), 'w') as f:
                f.write('test2')

            # Test that the sync happens
            added, removed = sync_from_log(src, dst, 'logfile')

            assert added == [
                join(dst, 'test1'),
                join(dst, 'testdir', 'test2'),
                'logfile',
                ]

            assert removed == []

            with open(join(dst, 'test1')) as f:
                assert f.read() == 'test1'

            with open(join(dst, 'testdir', 'test2')) as f:
                assert f.read() == 'test2'

            with open('logfile') as f:
                assert f.read() == '\n'.join([
                    join(dst, 'test1'),
                    join(dst, 'testdir', 'test2'),
                    ])

            # Create a new file
            with open(join(src, 'test3'), 'w') as f:
                f.write('test3')

            added, removed = sync_from_log(src, dst, 'logfile')

            assert added == [
                join(dst, 'test1'),
                join(dst, 'test3'),
                join(dst, 'testdir', 'test2'),
                'logfile',
            ]

            assert removed == []

            with open(join(dst, 'test1')) as f:
                assert f.read() == 'test1'

            with open(join(dst, 'testdir', 'test2')) as f:
                assert f.read() == 'test2'

            with open(join(dst, 'test3')) as f:
                assert f.read() == 'test3'

            with open('logfile') as f:
                assert f.read() == '\n'.join([
                    join(dst, 'test1'),
                    join(dst, 'test3'),
                    join(dst, 'testdir', 'test2'),
                    ])

            # Delete a file
            os.remove(join(src, 'test3'))

            added, removed = sync_from_log(src, dst, 'logfile')

            assert added == [
                join(dst, 'test1'),
                join(dst, 'testdir', 'test2'),
                'logfile',
            ]

            assert removed == [
                join(dst, 'test3'),
            ]

            with open(join(dst, 'test1')) as f:
                assert f.read() == 'test1'

            with open(join(dst, 'testdir', 'test2')) as f:
                assert f.read() == 'test2'

            assert not os.path.exists(join(dst, 'test3'))

            with open('logfile') as f:
                assert f.read() == '\n'.join([
                    join(dst, 'test1'),
                    join(dst, 'testdir', 'test2'),
                    ])

            # Change a file
            with open(join(src, 'test1'), 'w') as f:
                f.write('test1 modified')

            added, removed = sync_from_log(src, dst, 'logfile')

            assert added == [
                join(dst, 'test1'),
                join(dst, 'testdir', 'test2'),
                'logfile',
            ]

            assert removed == []

            with open(join(dst, 'test1')) as f:
                assert f.read() == 'test1 modified'

            with open(join(dst, 'testdir', 'test2')) as f:
                assert f.read() == 'test2'

            assert not os.path.exists(join(dst, 'test3'))

            with open('logfile') as f:
                assert f.read() == '\n'.join([
                    join(dst, 'test1'),
                    join(dst, 'testdir', 'test2'),
                    ])

        finally:
            os.chdir(old_curdir)

Example 145

Project: aerospike-client-python Source File: test_operate_ordered.py
    @pytest.mark.parametrize("key, llist, expected", [
        (('test', 'demo', 1),
            [{"op": aerospike.OPERATOR_PREPEND,
              "bin": "name",
              "val": u"ram"},
             {"op": aerospike.OPERATOR_INCR,
              "bin": "age",
              "val": 3},
             {"op": aerospike.OPERATOR_READ,
              "bin": "name"}],
            [None, None, ('name', 'ramname1')]),
        (('test', 'demo', 1),                 # with_write_float_value
            [{"op": aerospike.OPERATOR_WRITE,
              "bin": "write_bin",
              "val": {"no": 89.8}},
             {"op": aerospike.OPERATOR_READ,
              "bin": "write_bin"}],
            [None, ('write_bin', {u'no': 89.8})]),
        (('test', 'demo', 1),                            # write positive
            [{"op": aerospike.OPERATOR_WRITE,
              "bin": "write_bin",
              "val": {"no": 89}},
             {"op": aerospike.OPERATOR_READ, "bin": "write_bin"}],
            [None, ('write_bin', {u'no': 89})]),
        (('test', 'demo', 1),                       # write_tuple_positive
            [{"op": aerospike.OPERATOR_WRITE,
              "bin": "write_bin",
              "val": tuple('abc')},
             {"op": aerospike.OPERATOR_READ, "bin": "write_bin"}],
            [None, ('write_bin', ('a', 'b', 'c'))]),
        (('test', 'demo', 1),                # with_bin_bytearray
            [{"op": aerospike.OPERATOR_PREPEND,
              "bin": bytearray("asd[;asjk", "utf-8"),
              "val": u"ram"},
             {"op": aerospike.OPERATOR_READ,
              "bin": bytearray("asd[;asjk", "utf-8")}],
            [None, ('asd[;asjk', 'ram')]),
        (('test', 'demo', 'bytearray_key'),  # append_val bytearray
            [{"op": aerospike.OPERATOR_APPEND,
              "bin": "bytearray_bin",
              "val": bytearray("abc", "utf-8")},
             {"op": aerospike.OPERATOR_READ,
              "bin": "bytearray_bin"}],
            [None, ('bytearray_bin', bytearray("asd;as[d'as;dabc", "utf-8"))]),
        (('test', 'demo', 'bytearray_new'),  # append bytearray_newrecord
            [{"op": aerospike.OPERATOR_APPEND,
              "bin": "bytearray_bin",
              "val": bytearray("asd;as[d'as;d", "utf-8")},
             {"op": aerospike.OPERATOR_READ,
              "bin": "bytearray_bin"}],
            [None, ('bytearray_bin', bytearray("asd;as[d'as;d", "utf-8"))]),
        (('test', 'demo', 'bytearray_key'),  # prepend_valbytearray
            [{"op": aerospike.OPERATOR_PREPEND,
              "bin": "bytearray_bin",
              "val": bytearray("abc", "utf-8")},
             {"op": aerospike.OPERATOR_READ,
              "bin": "bytearray_bin"}],
            [None, ('bytearray_bin', bytearray("abcasd;as[d'as;d", "utf-8"))]),
        (('test', 'demo', 'bytearray_new'),  # prepend_valbytearray_newrecord
            [{"op": aerospike.OPERATOR_PREPEND,
              "bin": "bytearray_bin",
              "val": bytearray("asd;as[d'as;d", "utf-8")},
             {"op": aerospike.OPERATOR_READ,
              "bin": "bytearray_bin"}],
            [None, ('bytearray_bin', bytearray("asd;as[d'as;d", "utf-8"))]),
    ])
    def test_pos_operate_ordered_correct_paramters(self, key, llist, expected):
        """
        Invoke operate_ordered() with correct parameters
        """

        key, _, bins = self.as_connection.operate_ordered(key, llist)

        assert bins == expected
        self.as_connection.remove(key)

Example 146

Project: pw Source File: test_store.py
@pytest.mark.parametrize("src, expected", [
    (
        u"",
        [],
    ),
    (
        u"""
# this is a comment
        """,
        [],
    ),
    (
        u"""
key pass
key: pass
#
"key word" pass
"key word": pass
#
key "pass word"
key: "pass word"
#
"key word" "pass word"
"key word": "pass word"
        """,
        [
            Entry(key='key', user='', password='pass', notes=''),
            Entry(key='key', user='', password='pass', notes=''),
            Entry(key='key word', user='', password='pass', notes=''),
            Entry(key='key word', user='', password='pass', notes=''),
            Entry(key='key', user='', password='pass word', notes=''),
            Entry(key='key', user='', password='pass word', notes=''),
            Entry(key='key word', user='', password='pass word', notes=''),
            Entry(key='key word', user='', password='pass word', notes=''),
        ]
    ),
    (
        u"""
key user pass
key: user pass
#
"key word" "user name" "pass word"
"key word": "user name" "pass word"
        """,
        [
            Entry(key='key', user='user', password='pass', notes=''),
            Entry(key='key', user='user', password='pass', notes=''),
            Entry(key='key word', user='user name', password='pass word', notes=''),
            Entry(key='key word', user='user name', password='pass word', notes=''),
        ],
    ),
    (
        u"""
key user pass these are some interesting notes
key: user pass these are some interesting notes
#
"key word" "user name" "pass word" these are some interesting notes
"key word": "user name" "pass word" these are some interesting notes
        """,
        [
            Entry(key='key', user='user', password='pass', notes='these are some interesting notes'),
            Entry(key='key', user='user', password='pass', notes='these are some interesting notes'),
            Entry(key='key word', user='user name', password='pass word', notes='these are some interesting notes'),
            Entry(key='key word', user='user name', password='pass word', notes='these are some interesting notes'),
        ],
    ),
    (
        u"""
key pass
    notes line 1
    notes line 2
key: pass
    notes line 1
    notes line 2
#
key "" pass notes line 0
    notes line 1
    notes line 2
key: "" pass notes line 0
    notes line 1
    notes line 2
#
key "" pass notes line 0
    # notes line 0.5
    notes line 1
    # notes line 1.5
    notes line 2
key "" pass notes line 0
    # notes line 0.5
    notes line 1
    # notes line 1.5
    notes line 2
        """,
        [
            Entry(key='key', user='', password='pass', notes='notes line 1\nnotes line 2'),
            Entry(key='key', user='', password='pass', notes='notes line 1\nnotes line 2'),
            Entry(key='key', user='', password='pass', notes='notes line 0\nnotes line 1\nnotes line 2'),
            Entry(key='key', user='', password='pass', notes='notes line 0\nnotes line 1\nnotes line 2'),
            Entry(key='key', user='', password='pass', notes='notes line 0\n# notes line 0.5\nnotes line 1\n# notes line 1.5\nnotes line 2'),
            Entry(key='key', user='', password='pass', notes='notes line 0\n# notes line 0.5\nnotes line 1\n# notes line 1.5\nnotes line 2'),
        ],
    ),
    (
        u"""
key user pass
    notes line 1
    notes line 2
key: user pass
    notes line 1
    notes line 2
#
key user pass notes line 0
    notes line 1
    notes line 2
key: user pass notes line 0
    notes line 1
    notes line 2
#
key user pass notes line 0
    # notes line 0.5
    notes line 1
    # notes line 1.5
    notes line 2
key user pass notes line 0
    # notes line 0.5
    notes line 1
    # notes line 1.5
    notes line 2
        """,
        [
            Entry(key='key', user='user', password='pass', notes='notes line 1\nnotes line 2'),
            Entry(key='key', user='user', password='pass', notes='notes line 1\nnotes line 2'),
            Entry(key='key', user='user', password='pass', notes='notes line 0\nnotes line 1\nnotes line 2'),
            Entry(key='key', user='user', password='pass', notes='notes line 0\nnotes line 1\nnotes line 2'),
            Entry(key='key', user='user', password='pass', notes='notes line 0\n# notes line 0.5\nnotes line 1\n# notes line 1.5\nnotes line 2'),
            Entry(key='key', user='user', password='pass', notes='notes line 0\n# notes line 0.5\nnotes line 1\n# notes line 1.5\nnotes line 2'),
        ],
    ),
    (
        u"""
"السلام عليكم": 임요환 Нет Εις το επανιδείν
        """,
        [
            Entry(key=u'السلام عليكم', user=u'임요환', password=u'Нет', notes=u'Εις το επανιδείν'),
        ],
    ),
])  # yapf: disable
def test_parse_entries(src, expected):
    entries = _parse_entries(src.strip())
    assert entries == expected

Example 147

Project: SHARE Source File: test_v1.py
Function: test_normalize
    @pytest.mark.parametrize('input, expected', [
        ({
            "contributors": [{
                "name": "Roger Movies Ebert",
                "sameAs": ["https://osf.io/thing"],
                "familyName": "Ebert",
                "givenName": "Roger",
                "additionalName": "Danger",
                "email": "[email protected]"
            }, {
                "name": "Roger Madness Ebert"
            }],
            "languages": ["eng"],
            "description": "This is a thing",
            "providerUpdatedDateTime": "2014-12-12T00:00:00Z",
            "freeToRead": {
                "startDate": "2014-09-12",
                "endDate": "2014-10-12"
            },
            "licenses": [{
                "uri": "http://www.mitlicense.com",
                "startDate": "2014-10-12T00:00:00Z",
                "endDate": "2014-11-12T00:00:00Z"
            }],
            "publisher": {
                "name": "Roger Ebert Inc",
                "email": "[email protected]"
            },
            "sponsorships": [{
                "award": {
                    "awardName": "Participation",
                    "awardIdentifier": "http://example.com"
                },
                "sponsor": {
                    "sponsorName": "Orange",
                    "sponsorIdentifier": "http://example.com/orange"
                }
            }],
            "title": "Interesting research",
            "version": {"versionId": "someID"},
            "uris": {
                "canonicalUri": "http://example.com/docuement1",
                "providerUris": [
                    "http://example.com/docuement1uri1",
                    "http://example.com/docuement1uri2"
                ]
            }
        }, {
            '@type': 'creativework',
            'awards': [],
            'contributors': [{
                '@type': 'person',
                'additional_name': 'Movies',
                'affiliations': [],
                'emails': [{'@type': 'email', 'email': '[email protected]'}],
                'family_name': 'Ebert',
                'given_name': 'Roger',
                'identifiers': [{'@type': 'identifier', 'url': 'https://osf.io/thing'}],
                'suffix': ''
            }, {
                '@type': 'person',
                'additional_name': 'Madness',
                'affiliations': [],
                'emails': [],
                'family_name': 'Ebert',
                'given_name': 'Roger',
                'identifiers': [],
                'suffix': ''
            }],
            'date_updated': '2014-12-12T00:00:00+00:00',
            'description': 'This is a thing',
            'funders': [],
            'institutions': [],
            'language': 'eng',
            'links': [
                {'@type': 'link', 'type': 'provider', 'url': 'http://example.com/docuement1'},
                {'@type': 'link', 'type': 'provider', 'url': 'http://example.com/docuement1uri1'},
                {'@type': 'link', 'type': 'provider', 'url': 'http://example.com/docuement1uri2'},
            ],
            'organizations': [],
            'publishers': [{'@type': 'publisher', 'name': 'Roger Ebert Inc'}],
            'subjects': [],
            'tags': [],
            'title': 'Interesting research',
        }), ({
            "contributors": [],
            "languages": ["eng"],
            "description": "This is a thing",
            "providerUpdatedDateTime": "2014-12-12T00:00:00Z",
            "title": "Interesting research",
            "uris": {
                "canonicalUri": "http://example.com/docuement1",
                "providerUris": [
                    "http://example.com/docuement1uri1",
                    "http://example.com/docuement1uri2",
                    "http://example.com/docuement1uri2",
                    'http://example.com/docuement1',
                ]
            }
        }, {
            '@type': 'creativework',
            'awards': [],
            'contributors': [],
            'date_updated': '2014-12-12T00:00:00+00:00',
            'description': 'This is a thing',
            'funders': [],
            'institutions': [],
            'language': 'eng',
            'links': [
                {'@type': 'link', 'type': 'provider', 'url': 'http://example.com/docuement1'},
                {'@type': 'link', 'type': 'provider', 'url': 'http://example.com/docuement1uri1'},
                {'@type': 'link', 'type': 'provider', 'url': 'http://example.com/docuement1uri2'},
            ],
            'organizations': [],
            'publishers': [],
            'subjects': [],
            'tags': [],
            'title': 'Interesting research',
        }), ({
            "contributors": [],
            "languages": ["eng"],
            "description": "This is a thing",
            "providerUpdatedDateTime": "2014-12-12T00:00:00Z",
            "title": "Interesting research",
            "otherProperties": [{"name": "status", "properties": {"status": "deleted"}}],
            "uris": {
                "canonicalUri": "http://example.com/docuement1",
                "providerUris": [
                    'http://example.com/docuement1',
                    "http://example.com/docuement1uri1",
                    "http://example.com/docuement1uri2",
                    "http://example.com/docuement1uri2",
                ]
            }
        }, {
            '@type': 'creativework',
            'awards': [],
            'contributors': [],
            'date_updated': '2014-12-12T00:00:00+00:00',
            'description': 'This is a thing',
            'funders': [],
            'institutions': [],
            'is_deleted': True,
            'language': 'eng',
            'links': [
                {'@type': 'link', 'type': 'provider', 'url': 'http://example.com/docuement1'},
                {'@type': 'link', 'type': 'provider', 'url': 'http://example.com/docuement1uri1'},
                {'@type': 'link', 'type': 'provider', 'url': 'http://example.com/docuement1uri2'},
            ],
            'organizations': [],
            'publishers': [],
            'subjects': [],
            'tags': [],
            'title': 'Interesting research',
        })
    ])
    def test_normalize(self, input, expected):
        ctx.clear()
        assert expected == self.reconstruct(ctx.pool[V1Normalizer({}).do_normalize(json.dumps(input))])

Example 148

Project: ibis Source File: test_value_exprs.py
@pytest.mark.parametrize(
    ['op', 'name', 'case', 'ex_type'],
    [
        (operator.add, 'a', 0, 'int8'),
        (operator.add, 'a', 5, 'int16'),
        (operator.add, 'a', 100000, 'int32'),
        (operator.add, 'a', -100000, 'int32'),

        (operator.add, 'a', 1.5, 'double'),

        (operator.add, 'b', 0, 'int16'),
        (operator.add, 'b', 5, 'int32'),
        (operator.add, 'b', -5, 'int32'),

        (operator.add, 'c', 0, 'int32'),
        (operator.add, 'c', 5, 'int64'),
        (operator.add, 'c', -5, 'int64'),

        # technically this can overflow, but we allow it
        (operator.add, 'd', 5, 'int64'),

        (operator.mul, 'a', 0, 'int8'),
        (operator.mul, 'a', 5, 'int16'),
        (operator.mul, 'a', 2 ** 24, 'int32'),
        (operator.mul, 'a', -2 ** 24 + 1, 'int32'),

        (operator.mul, 'a', 1.5, 'double'),

        (operator.mul, 'b', 0, 'int16'),
        (operator.mul, 'b', 5, 'int32'),
        (operator.mul, 'b', -5, 'int32'),
        (operator.mul, 'c', 0, 'int32'),
        (operator.mul, 'c', 5, 'int64'),
        (operator.mul, 'c', -5, 'int64'),

        # technically this can overflow, but we allow it
        (operator.mul, 'd', 5, 'int64'),

        (operator.sub, 'a', 0, 'int8'),
        (operator.sub, 'a', 5, 'int16'),
        (operator.sub, 'a', 100000, 'int32'),
        (operator.sub, 'a', -100000, 'int32'),


        (operator.sub, 'a', 1.5, 'double'),
        (operator.sub, 'b', 0, 'int16'),
        (operator.sub, 'b', 5, 'int32'),
        (operator.sub, 'b', -5, 'int32'),
        (operator.sub, 'c', 0, 'int32'),
        (operator.sub, 'c', 5, 'int64'),
        (operator.sub, 'c', -5, 'int64'),

        # technically this can overflow, but we allow it
        (operator.sub, 'd', 5, 'int64'),

        (operator.truediv, 'a', 5, 'double'),
        (operator.truediv, 'a', 1.5, 'double'),
        (operator.truediv, 'b', 5, 'double'),
        (operator.truediv, 'b', -5, 'double'),
        (operator.truediv, 'c', 5, 'double'),

        (operator.pow, 'a', 0, 'int8'),
        (operator.pow, 'b', 0, 'int16'),
        (operator.pow, 'c', 0, 'int32'),
        (operator.pow, 'd', 0, 'int64'),
        (operator.pow, 'e', 0, 'float'),
        (operator.pow, 'f', 0, 'double'),

        (operator.pow, 'a', 2, 'int16'),
        (operator.pow, 'b', 2, 'int32'),
        (operator.pow, 'c', 2, 'int64'),
        (operator.pow, 'd', 2, 'int64'),

        (operator.pow, 'a', 1.5, 'double'),
        (operator.pow, 'b', 1.5, 'double'),
        (operator.pow, 'c', 1.5, 'double'),
        (operator.pow, 'd', 1.5, 'double'),

        (operator.pow, 'a', -2, 'double'),
        (operator.pow, 'b', -2, 'double'),
        (operator.pow, 'c', -2, 'double'),
        (operator.pow, 'd', -2, 'double'),

        (operator.pow, 'e', 2, 'float'),
        (operator.pow, 'f', 2, 'double'),
    ]
)
def test_literal_promotions(table, op, name, case, ex_type):
    col = table[name]

    result = op(col, case)
    ex_class = dt.array_type(ex_type)
    assert isinstance(result, ex_class)

    result = op(case, col)
    ex_class = dt.array_type(ex_type)
    assert isinstance(result, ex_class)

Example 149

Project: dask Source File: test_arithmetics_reduction.py
@pytest.mark.parametrize('split_every', [False, 2])
def test_reductions_frame(split_every):
    dsk = {('x', 0): pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]},
                                  index=[0, 1, 3]),
           ('x', 1): pd.DataFrame({'a': [4, 5, 6], 'b': [3, 2, 1]},
                                  index=[5, 6, 8]),
           ('x', 2): pd.DataFrame({'a': [7, 8, 9], 'b': [0, 0, 0]},
                                  index=[9, 9, 9])}
    meta = make_meta({'a': 'i8', 'b': 'i8'}, index=pd.Index([], 'i8'))
    ddf1 = dd.DataFrame(dsk, 'x', meta, [0, 4, 9, 9])
    pdf1 = ddf1.compute()

    assert_eq(ddf1.sum(split_every=split_every), pdf1.sum())
    assert_eq(ddf1.min(split_every=split_every), pdf1.min())
    assert_eq(ddf1.max(split_every=split_every), pdf1.max())
    assert_eq(ddf1.count(split_every=split_every), pdf1.count())
    assert_eq(ddf1.std(split_every=split_every), pdf1.std())
    assert_eq(ddf1.var(split_every=split_every), pdf1.var())
    assert_eq(ddf1.std(ddof=0, split_every=split_every), pdf1.std(ddof=0))
    assert_eq(ddf1.var(ddof=0, split_every=split_every), pdf1.var(ddof=0))
    assert_eq(ddf1.mean(split_every=split_every), pdf1.mean())

    for axis in [0, 1, 'index', 'columns']:
        assert_eq(ddf1.sum(axis=axis, split_every=split_every),
                  pdf1.sum(axis=axis))
        assert_eq(ddf1.min(axis=axis, split_every=split_every),
                  pdf1.min(axis=axis))
        assert_eq(ddf1.max(axis=axis, split_every=split_every),
                  pdf1.max(axis=axis))
        assert_eq(ddf1.count(axis=axis, split_every=split_every),
                  pdf1.count(axis=axis))
        assert_eq(ddf1.std(axis=axis, split_every=split_every),
                  pdf1.std(axis=axis))
        assert_eq(ddf1.var(axis=axis, split_every=split_every),
                  pdf1.var(axis=axis))
        assert_eq(ddf1.std(axis=axis, ddof=0, split_every=split_every),
                  pdf1.std(axis=axis, ddof=0))
        assert_eq(ddf1.var(axis=axis, ddof=0, split_every=split_every),
                  pdf1.var(axis=axis, ddof=0))
        assert_eq(ddf1.mean(axis=axis, split_every=split_every),
                  pdf1.mean(axis=axis))

    pytest.raises(ValueError, lambda: ddf1.sum(axis='incorrect').compute())

    # axis=0
    assert_dask_graph(ddf1.sum(split_every=split_every), 'dataframe-sum')
    assert_dask_graph(ddf1.min(split_every=split_every), 'dataframe-min')
    assert_dask_graph(ddf1.max(split_every=split_every), 'dataframe-max')
    assert_dask_graph(ddf1.count(split_every=split_every), 'dataframe-count')
    # std, var, mean consists from sum and count operations
    assert_dask_graph(ddf1.std(split_every=split_every), 'dataframe-sum')
    assert_dask_graph(ddf1.std(split_every=split_every), 'dataframe-count')
    assert_dask_graph(ddf1.var(split_every=split_every), 'dataframe-sum')
    assert_dask_graph(ddf1.var(split_every=split_every), 'dataframe-count')
    assert_dask_graph(ddf1.mean(split_every=split_every), 'dataframe-sum')
    assert_dask_graph(ddf1.mean(split_every=split_every), 'dataframe-count')

    # axis=1
    assert_dask_graph(ddf1.sum(axis=1, split_every=split_every),
                      'dataframe-sum')
    assert_dask_graph(ddf1.min(axis=1, split_every=split_every),
                      'dataframe-min')
    assert_dask_graph(ddf1.max(axis=1, split_every=split_every),
                      'dataframe-max')
    assert_dask_graph(ddf1.count(axis=1, split_every=split_every),
                      'dataframe-count')
    assert_dask_graph(ddf1.std(axis=1, split_every=split_every),
                      'dataframe-std')
    assert_dask_graph(ddf1.var(axis=1, split_every=split_every),
                      'dataframe-var')
    assert_dask_graph(ddf1.mean(axis=1, split_every=split_every),
                      'dataframe-mean')

Example 150

Project: CSScheme Source File: test_parser.py
@pytest.mark.parametrize(('css_source', 'expected_rules', 'expected_errors'), [
    ('foo {/* hey */}\n',
        [('foo', [], [])],
        []),

    (' * {}',
        [('*', [], [])],
        []),

    ('foo {@name "ascii"} foo{}',
        [('foo', [], [('@name', [('STRING', "ascii")])]),
         ('foo', [], [])],
        []),

    ('foo {decl: "im-a string"} foo{decl: #123456; decl2: ident}',
        [('foo',
          [('decl',  [('STRING', "im-a string")])],
          []),
         ('foo',
          [('decl',  [('HASH',  "#123456")]),
           ('decl2', [('IDENT', "ident")])],
          [])],
        []),

    ('fooz {decl: function(param1, param2)}',
        [('fooz',
          [('decl',  [('FUNCTION', "function",
                       [('IDENT',  "param1"),
                        ('DELIM',  ","),
                        ('S',      " "),
                        ('IDENT',  "param2")])])],
          [])],
        []),

    ('fooz {decl: function(0, 1% 0.2)}',
        [('fooz',
          [('decl',  [('FUNCTION', "function",
                       [('INTEGER',    0),
                        ('DELIM',      ","),
                        ('S',          " "),
                        ('PERCENTAGE', 1),
                        ('S',          " "),
                        ('NUMBER',     0.2)])])],
          [])],
        []),

    ('foo {list: mixed ident and "string list" and 1;}',
        [('foo',
          [('list', [('IDENT',  "mixed"),
                     ('S',      " "),
                     ('IDENT',  "ident"),
                     ('S',      " "),
                     ('IDENT',  "and"),
                     ('S',      " "),
                     ('STRING', "string list"),
                     ('S',      " "),
                     ('IDENT',  "and"),
                     ('S',      " "),
                     ('INTEGER', 1)])],
          [])],
        []),


    # Errors
    ('foo {decl: 1.2; decl2: "str":; decl3: some ]}',
        [('foo', [], [])],
        ["unexpected NUMBER token for property decl",
         "unexpected : token for property decl2",
         "unmatched ] token for property decl3"]),

    ('foo {decl: a; decl: b}',
        [('foo', [('decl', [('IDENT', "a")])], [])],
        ["property decl only allowed once"]),

    ('foo {"decl": a; decl2 a; decl3: ;}',
        [('foo', [], [])],
        ["expected a property name, got STRING",
         "expected ':', got IDENT",
         "expected a property value for property decl3"]),

    ('foo {decl ;}',
        [('foo', [], [])],
        ["expected ':'"]),

    ('fooz {decl: function(param1}',
        [('fooz',
          [],
          [])],
        ["unmatched } token for property decl in function 'function()'"]),
])
def test_rulesets(css_source, expected_rules, expected_errors):
    stylesheet = CSSchemeParser().parse_stylesheet(css_source)
    assert_errors(stylesheet.errors, expected_errors)
    result = [tuplify(rule) for rule in stylesheet.rules]
    assert result == expected_rules
See More Examples - Go to Next Page
Page 1 Page 2 Page 3 Selected Page 4