コード例 #1
0
    def test_specified_file_does_not_exist(self):
        def fail_to_open(foo):
            open('/a/b/c/d', 'r')
 
        observed = app.redirect_must_exist(fail_to_open)('elephant')
        expected = { "error": "That redirect doesn't exist. Use PUT to create it." }
        n.assert_dict_equal(observed, expected)
コード例 #2
0
    def test_user_info(self):
        client = self.get_client()
        subject = "Joe USER"
        headers = {
            HTTP_HEADER_USER_INFO: subject,
            HTTP_HEADER_SIGNATURE: ""
        }
        t = client.fetch_user_token(headers)

        nt.assert_equal(self.appId, t.validity.issuedTo)
        nt.assert_equal(self.appId, t.validity.issuedFor)
        nt.assert_equal(subject, t.tokenPrincipal.principal)
        nt.assert_equal("Joe User", t.tokenPrincipal.name)
        nt.assert_set_equal({'A', 'B', 'C'}, t.authorizations.formalAuthorizations)
        nt.assert_equal("EzBake", t.organization)
        nt.assert_equal("USA", t.citizenship)
        nt.assert_equal("low", t.authorizationLevel)
        nt.assert_dict_equal(dict([
            ('EzBake', ['Core']),
            ('42six', ['Dev', 'Emp']),
            ('Nothing', ['groups', 'group2'])]), t.externalProjectGroups)
        community_membership = t.externalCommunities['EzBake']
        nt.assert_equal("office", community_membership.type)
        nt.assert_equal("EzBake", community_membership.organization)
        nt.assert_true(community_membership.flags['ACIP'])
        nt.assert_list_equal(['topic1', 'topic2'], community_membership.topics)
        nt.assert_list_equal(['region1', 'region2', 'region3'], community_membership.regions)
        nt.assert_list_equal([], community_membership.groups)
コード例 #3
0
    def test_read_from_project_using_filename(self, filename):
        with open(filename, 'r', encoding="utf-8") as doors_file:
            def resource_open(a, b, astext):
                return doors_file

            self.module.read_from_project(resource_open)

        # Very simple verification by checking the amount of different types of doors that were read
        assert_equal(len(self.module.door_areas), 40 * 32)
        num_door_types = dict()
        num_empty_areas = 0
        for area in self.module.door_areas:
            if area is not None and len(area) > 0:
                for door in area:
                    if door.__class__.__name__ not in num_door_types:
                        num_door_types[door.__class__.__name__] = 1
                    else:
                        num_door_types[door.__class__.__name__] += 1
            else:
                num_empty_areas += 1
        assert_equal(num_empty_areas, 679)
        assert_dict_equal(num_door_types, {
            "SwitchDoor": 6,
            "EscalatorOrStairwayDoor": 92,
            "Door": 1072,
            "NpcDoor": 269,
            "RopeOrLadderDoor": 641,
        })
コード例 #4
0
ファイル: test.py プロジェクト: tlevine/cgitrepos
def _check_fixture(name):
    "Check a cgitrepos file in the fixtures directory."
    cgitrepos = open(os.path.join('fixtures', name))
    cgitrepos_json = open(os.path.join('fixtures', name + '.json'))

    # Check that the cgitrepos file matches the JSON.
    try:
        observed = _parse(cgitrepos.read())
    except:
        # Such a hack
        observed = {}

    expected = json.loads(cgitrepos_json.read())
    cgitrepos.close()
    cgitrepos_json.close()

    if type(expected) != dict:
        # Point out that the JSON file is bad.
        assert False, 'The test is malformed; the file %s must be a dict at its root.'

    elif type(observed) != dict:
        # Point out that the JSON file is bad.
        assert False, 'The parser returned a type other than dict.'

    else:
        # Test each associative array (repository).
        for name in expected:
            n.assert_in(name, observed)
            n.assert_dict_equal(observed[name], expected[name])
コード例 #5
0
ファイル: test_subfields.py プロジェクト: dwwoelfel/dibble
def test_nested_subfield_operation():
    tm = TestModel()
    nsf = tm.foo['bar']['baz']

    nsf.set('fumm')

    assert_dict_equal(dict(tm._update), {'$set': {'foo.bar.baz': 'fumm'}})
コード例 #6
0
ファイル: test_scoresheet.py プロジェクト: TythonLee/linkpred
    def test_from_file(self):
        with temp_file() as fname:
            with open(fname, "wb") as fh:
                fh.write(self.expected)

            sheet = Scoresheet.from_file(fname)
            assert_dict_equal(sheet, self.sheet)
コード例 #7
0
def test_cache():
    scheme = 'https'
    gotten = set()
    def get(url):
        raise AssertionError('This should not run.')
    n_threads = 4

    search_url = 'https://chicago.craigslist.org/sub/index000.html'
    listing_url = 'https://chicago.craigslist.org/sub/42832238.html'
    warehouse = {
        (search_url,fake_datetime.date().isoformat()):fake_response(search_url),
        listing_url:fake_response(listing_url),
    }
    site = 'chicago.craigslist.org'
    section = 'sub'

    parse_listing = lambda response: {'html':response.text,'foo':'bar'}
    parse_search = lambda response: [{'href':listing_url, 'date': None}]

    searched = set()
    def parse_next_search_url(scheme, site, section, html):
        if html == None:
            searched.clear()
        url = '%s://%s/%s/index%d00.html' % (scheme, site, section, len(searched))
        searched.add(url)
        return url

    l = listings(scheme, get, n_threads, warehouse, site, section,
                 parse_listing, parse_search, parse_next_search_url,
                 fake_download, lambda: fake_datetime)
    n.assert_dict_equal(next(l), fake_result(listing_url))
コード例 #8
0
ファイル: test_client.py プロジェクト: qwang2505/ssdb-py
 def test_scan(self):
     keys = [
         'zzz0',
         'zzz1',
         'zzz2',
         'zzz3',
         'zzz4',
         'zzz5',
         'zzz6',
         'zzz7'
     ]
     values = [
         'a1',
         'b2',
         'c3',
         'd4',
         'e5',
         'f6',
         'g7',
         'h8'
     ]
     params = {}
     for i in range(len(keys)):
         params[keys[i]] = values[i]
     a = self.client.multi_set(**params)
     assert_equals(a,len(params))
     b = self.client.scan('zzz ','zzzz',10)
     assert_dict_equal(b,params)
     index = 0
     for k,v in b.items():
         assert_equals(k, keys[index])
         assert_equals(v, values[index])
         index += 1
     d = self.client.multi_del(*params.keys())
     assert_equals(d,len(params))
コード例 #9
0
ファイル: test_ncss_dataset.py プロジェクト: scollis/siphon
 def test_coord_transform_valid(self):
     xml = '<coordTransform name="LambertConformal_Projection" ' \
           'transformType="Projection">' \
           '<parameter name="grid_mapping_name" ' \
           'value="lambert_conformal_conic"/>' \
           '<parameter name="latitude_of_projection_origin" ' \
           'value="40.0 "/>' \
           '<parameter name="longitude_of_central_meridian" ' \
           'value="262.0 "/>' \
           '<parameter name="standard_parallel" value="40.0 "/>' \
           '<parameter name="earth_radius" value="6371229.0 "/>' \
           '</coordTransform>'
     element = ET.fromstring(xml)
     actual = NCSSDataset(element).coordinate_transforms
     assert actual
     assert actual["LambertConformal_Projection"]
     assert_equal(len(actual["LambertConformal_Projection"]), 2)
     assert_equal(actual["LambertConformal_Projection"]["transformType"],
                  "Projection")
     parameters = actual["LambertConformal_Projection"]["parameters"]
     assert_equal(len(parameters), 5)
     expected = {"grid_mapping_name": "lambert_conformal_conic",
                 "latitude_of_projection_origin": "40.0",
                 "longitude_of_central_meridian": "262.0",
                 "standard_parallel": "40.0",
                 "earth_radius": "6371229.0"}
     assert_dict_equal(parameters, expected)
コード例 #10
0
def test_TimeAttribute_from_dict():
    """results.TimeAttribute.from_dict: returns expected value"""
    # Type is included because to_json() adds it.
    baseline = {'start': 0.1, 'end': 1.0, '__type__': 'TimeAttribute'}
    test = results.TimeAttribute.from_dict(baseline).to_json()

    nt.assert_dict_equal(baseline, test)
コード例 #11
0
ファイル: test_read.py プロジェクト: niutyut/wos
    def test_multiline_fields_nosplit(self):
        f = StringIO(preamble_s + "PT abc\nSC Here; there\n  be dragons; Yes"
                     "\nER\nEF")

        r = PlainTextReader(f)
        expected = {"PT": "abc", "SC": "Here; there be dragons; Yes"}
        assert_dict_equal(next(r), expected)
コード例 #12
0
ファイル: test_api.py プロジェクト: abeusher/happybase
def test_delete():
    row_key = 'row-test-delete'
    data = {'cf1:col1': 'v1',
            'cf1:col2': 'v2',
            'cf1:col3': 'v3'}
    table.put(row_key, {'cf1:col2': 'v2old'}, timestamp=1234)
    table.put(row_key, data)

    table.delete(row_key, ['cf1:col2'], timestamp=2345)
    assert_equal(1, len(table.cells(row_key, 'cf1:col2', versions=2)))
    assert_dict_equal(data, table.row(row_key))

    table.delete(row_key, ['cf1:col1'])
    res = table.row(row_key)
    assert_not_in('cf1:col1', res)
    assert_in('cf1:col2', res)
    assert_in('cf1:col3', res)

    table.delete(row_key, timestamp=12345)
    res = table.row(row_key)
    assert_in('cf1:col2', res)
    assert_in('cf1:col3', res)

    table.delete(row_key)
    assert_dict_equal({}, table.row(row_key))
コード例 #13
0
ファイル: test_ncss_dataset.py プロジェクト: scollis/siphon
 def test_attribute_1(self):
     xml = '<attribute name="long_name" ' \
           'value="Specified height level above ground"/>'
     element = ET.fromstring(xml)
     expected = {"long_name": "Specified height level above ground"}
     actual = self.types.handle_attribute(element)
     assert_dict_equal(expected, actual)
コード例 #14
0
def dict_eq(one, two):
    """Assert two dict-like objects are equal.

    Casts to dict, and then uses nose.tools.assert_dict_equal.

    """
    nt.assert_dict_equal(dict(one), dict(two))
コード例 #15
0
ファイル: test_scenario.py プロジェクト: portante/ssbench
 def test_bench_job_3_with_block_size(self):
     self.scenario.block_size = 111
     bench_job = self.scenario.bench_job('huge', 3, 30230)
     assert_dict_equal(dict(
         type=ssbench.DELETE_OBJECT,
         size_str='huge',
     ), bench_job)
def test_readManifestFile__synapseStore_values_are_set():

    project_id = "syn123"
    header = 'path\tparent\tsynapseStore\n'
    path1 = os.path.abspath(os.path.expanduser('~/file1.txt'))
    path2 = 'http://www.synapse.org'
    path3 = os.path.abspath(os.path.expanduser('~/file3.txt'))
    path4 = 'http://www.github.com'
    path5 = os.path.abspath(os.path.expanduser('~/file5.txt'))
    path6 = 'http://www.checkoutmymixtapefam.com/fire.mp3'

    row1 = '%s\t%s\tTrue\n' % (path1, project_id)
    row2 = '%s\t%s\tTrue\n' % (path2, project_id)
    row3 = '%s\t%s\tFalse\n' % (path3, project_id)
    row4 = '%s\t%s\tFalse\n' % (path4, project_id)
    row5 = '%s\t%s\t""\n' % (path5, project_id)
    row6 = '%s\t%s\t""\n' % (path6, project_id)

    expected_synapseStore = {
        str(path1): True,
        str(path2): False,
        str(path3): False,
        str(path4): False,
        str(path5): True,
        str(path6): False
    }

    manifest = StringIO(header+row1+row2+row3+row4+row5+row6)
    with patch.object(syn, "get", return_value=Project()),\
         patch.object(os.path, "isfile", return_value=True):  # mocks values for: file1.txt, file3.txt, file5.txt
        manifest_dataframe = synapseutils.sync.readManifestFile(syn, manifest)

        actual_synapseStore = (manifest_dataframe.set_index('path')['synapseStore'].to_dict())
        assert_dict_equal(expected_synapseStore, actual_synapseStore)
コード例 #17
0
ファイル: test_read.py プロジェクト: niutyut/wos
    def test_one_record(self):
        f = StringIO("PT\tAF\tC1\nJ\tAa; Bb\tX; Y")

        r = TabDelimitedReader(f)
        expected = {"PT": "J", "AF": "Aa; Bb", "C1": "X; Y"}

        assert_dict_equal(next(r), expected)
コード例 #18
0
ファイル: results_tests.py プロジェクト: Jul13t/piglit
 def test_node_values(self):
     """results.TestrunResult.totals: Tests with subtests values are correct"""
     expect = results.Totals()
     expect['pass'] += 1
     expect['crash'] += 1
     expect['fail'] += 1
     nt.assert_dict_equal(self.test[grouptools.join('sub', 'test')], expect)
コード例 #19
0
    def test_load_dictionary(self):
        c = self.comp
        d = c.as_dictionary(True)
        n = Component(self.parameter_names)

        n._id_name = 'dummy names yay!'
        _ = n._load_dictionary(d)
        nt.assert_equal(c.name, n.name)
        nt.assert_equal(c.active, n.active)
        nt.assert_equal(
            c.active_is_multidimensional,
            n.active_is_multidimensional)

        for pn, pc in zip(n.parameters, c.parameters):
            rn = np.random.random()
            nt.assert_equal(pn.twin_function(rn), pc.twin_function(rn))
            nt.assert_equal(
                pn.twin_inverse_function(rn),
                pc.twin_inverse_function(rn))
            dn = pn.as_dictionary()
            del dn['self']
            del dn['twin_function']
            del dn['twin_inverse_function']
            dc = pc.as_dictionary()
            del dc['self']
            del dc['twin_function']
            del dc['twin_inverse_function']
            print(list(dn.keys()))
            print(list(dc.keys()))
            nt.assert_dict_equal(dn, dc)
コード例 #20
0
ファイル: results_tests.py プロジェクト: Jul13t/piglit
 def test_root(self):
     """results.TestrunResult.totals: The root is correct with subtests"""
     expect = results.Totals()
     expect['pass'] += 1
     expect['crash'] += 1
     expect['fail'] += 1
     nt.assert_dict_equal(self.test['root'], expect)
コード例 #21
0
ファイル: test_graph_fields.py プロジェクト: Carralex/landlab
def test_getitem():
    fields = ModelDataFields()
    fields.new_field_location('node', 12)

    assert_dict_equal(dict(), fields['node'])
    assert_raises(GroupError, lambda k: fields[k], 'cell')
    assert_raises(KeyError, lambda k: fields[k], 'cell')
コード例 #22
0
ファイル: results_tests.py プロジェクト: Jul13t/piglit
 def test_recurse(self):
     """results.TestrunResult.totals: Recurses correctly"""
     expected = results.Totals()
     expected['fail'] += 1
     expected['crash'] += 1
     expected['skip'] += 1
     nt.assert_dict_equal(self.test['foo'], expected)
コード例 #23
0
def test_empty_ns_in_consul():
    fn = 'test_empty_ns_in_consul'
    check_call('consulconf -i %s -p %s/test-%s --delete'
               % (CWD, AGENT, fn), shell=True)
    nt.assert_dict_equal(
        json.loads(check_output(
            'consulconf -i %s/test-%s --dry_run' % (AGENT, fn), shell=True)
            .decode()),
        {
            "test": {},
            "test-namespace": {},
            "test-ns1": {"key1": "val1"},
            "test-ns2": {"key1": "val1"},
            "test/app1": {},
            "test/app2": {"key1": "val1"},
            "test/app20": {"key": "value"},
            "test/app21": {"key": "value", "key1": "val1"},
            "test/app22": {"key1": "val1"},
            "test/app3": {},
            "test/app4": {"key2": "val2"},
            "test/app5": {"key1": "val1", "key2": "val2"},
            "test/app6": {"key1": "val11"},
            "test/app7": {"key1": "val11", "key2": "val2"},
            "test/app8": {"key1": "val1", "key2": "val22"},
            "test/app9": {"key1": "val1", "key2": "val222"}
        }

    )
コード例 #24
0
ファイル: profile_tests.py プロジェクト: ThirteenFish/piglit
def check_flatten(tests, testlist):
    """ TestProfile.prepare_test_list flattens TestProfile.tests """
    profile_ = profile.TestProfile()
    profile_.tests = tests
    profile_._flatten_group_hierarchy()

    nt.assert_dict_equal(profile_.test_list, testlist)
コード例 #25
0
ファイル: asserter.py プロジェクト: dudycooly/python_helpers
def check_items_equal(actual_value, expected_value, msg=""):
    """
    :param actual_value:
    :param expected_value:
    :param msg:
    :return:

    """
    if isinstance(actual_value, (list, dict, tuple)):
        msg = "\n" + msg + "\n\nDiffering items :\nFirst Argument(Usually Actual) marked with (-)," \
                           "Second Argument(Usually Expected) marked with (+)"
    else:
        msg = "\n" + msg + "\nFirst Argument(Usually Actual), Second Argument(Usually Expected)"

    if not actual_value or not expected_value:
        assert_equal(actual_value, expected_value, u"{}\n{} != {}".format(msg, actual_value, expected_value))

    elif isinstance(actual_value, (list, tuple)):
        assert_items_equal(sorted(actual_value), sorted(expected_value),
                           u"{}\n{}".format(msg, unicode(diff(sorted(actual_value),
                                                          sorted(expected_value)))))
    elif isinstance(actual_value, dict):
        assert_dict_equal(actual_value, expected_value,
                     u"{}\n{}".format(msg, unicode(diff(actual_value, dict(expected_value)))))
    elif isinstance(actual_value, (str, bool)):
        assert_equal(actual_value, expected_value,
                     u"{}\n{} != {}".format(msg, unicode(actual_value), unicode(expected_value)))
    else:
        assert_equal(actual_value, expected_value,
                     u"{}\n{} != {}".format(msg, actual_value, expected_value))
コード例 #26
0
ファイル: test_scenario.py プロジェクト: portante/ssbench
 def test_bench_job_1(self):
     bench_job = self.scenario.bench_job('large', 1, 492)
     assert_dict_equal(dict(
         type=ssbench.READ_OBJECT,
         size_str='large',
         block_size=None,
     ), bench_job)
コード例 #27
0
ファイル: test_api.py プロジェクト: Cadasta/ckanext-project
    def test_error_from_cadasta_api_raises_validation_error(self):
        for action, cadasta_endpoint in get_api_map.items():
            print "testing {action}".format(action=action),

            # add the expected parameters (everything is a 1)
            api_url = cadasta_endpoint.url
            url_args = dict([(a[1], 1) for a in string.Formatter().parse(api_url) if a[1]])

            # make sure the point parameters are filled out
            endpoint = urljoin(self.test_api, api_url).format(**url_args)

            # fake out our response
            responses.add(
                responses.GET,
                endpoint,
                body='{"error": {"code": 1}, "message": "err msg"}',
                content_type="application/json",
            )

            with assert_raises(toolkit.ValidationError) as cm:
                helpers.call_action(action, **url_args)

            assert_dict_equal({u"code": [1], "message": [u"err msg"], "type": [""]}, cm.exception.error_dict)

            print "\t[OK]"
コード例 #28
0
def test_TimeAttribute_to_json():
    """results.TimeAttribute.to_json(): returns expected dictionary"""
    baseline = {'start': 0.1, 'end': 1.0}
    test = results.TimeAttribute(**baseline)
    baseline['__type__'] = 'TimeAttribute'

    nt.assert_dict_equal(baseline, test.to_json())
コード例 #29
0
ファイル: test_model.py プロジェクト: siriagus/hyperspy
 def test_model2plot_other_am(self):
     m = self.model
     res = m._model2plot(m.axes_manager.deepcopy(), out_of_range2nans=False)
     np.testing.assert_array_equal(res, np.array([0.5, 0.25]))
     nt.assert_true(m.__call__.called)
     nt.assert_dict_equal(m.__call__.call_args[1], {"non_convolved": False, "onlyactive": True})
     nt.assert_equal(2, m.fetch_stored_values.call_count)
コード例 #30
0
    def test_score(
            self,
            _score_ratio_mock,
            _score_special_mock,
            _score_numbers_mock,
            _score_case_mock,
            _score_length_mock):

        _score_ratio_mock.return_value = 2
        _score_special_mock.return_value = 3
        _score_numbers_mock.return_value = 5
        _score_case_mock.return_value = 7
        _score_length_mock.return_value = 11

        expected_result = {
            'length': 11,
            'case': 7,
            'numbers': 5,
            'special': 3,
            'ratio': 2,
            'total': 28,
        }

        validator = PasswordValidator('')

        assert_dict_equal(expected_result, validator.score())
コード例 #31
0
    def test_axis0_input(self):
        kws = self.default_kws.copy()
        kws['axis'] = 0
        p = mat._DendrogramPlotter(self.df_norm.T, **kws)

        npt.assert_array_equal(p.array, np.asarray(self.df_norm.T))
        pdt.assert_frame_equal(p.data, self.df_norm.T)

        npt.assert_array_equal(p.linkage, self.x_norm_linkage)
        nt.assert_dict_equal(p.dendrogram, self.x_norm_dendrogram)

        npt.assert_array_equal(p.xticklabels, self.df_norm_leaves)
        npt.assert_array_equal(p.yticklabels, [])

        nt.assert_equal(p.xlabel, 'letters')
        nt.assert_equal(p.ylabel, '')
コード例 #32
0
    def test_getitem(self):
        """Testing Fetch.__getitem__"""
        list1 = sorted(self.subject.proj().fetch.as_dict(), key=itemgetter('subject_id'))
        list2 = sorted(self.subject.fetch[dj.key], key=itemgetter('subject_id'))
        for l1, l2 in zip(list1, list2):
            assert_dict_equal(l1, l2,  'Primary key is not returned correctly')

        tmp = self.subject.fetch(order_by=['subject_id'])

        subject_notes, key, real_id = self.subject.fetch['subject_notes', dj.key, 'real_id']

        np.testing.assert_array_equal(sorted(subject_notes), sorted(tmp['subject_notes']))
        np.testing.assert_array_equal(sorted(real_id), sorted(tmp['real_id']))
        list1 = sorted(key, key=itemgetter('subject_id'))
        for l1, l2 in zip(list1, list2):
            assert_dict_equal(l1, l2,  'Primary key is not returned correctly')
コード例 #33
0
ファイル: test_5_mut.py プロジェクト: jdcourcol/MorphIO
def test_connectivity():
    cells = OrderedDict({
        'asc':
        Morphology(os.path.join(_path, "simple.asc")),
        'swc':
        Morphology(os.path.join(_path, "simple.swc")),
        'h5':
        Morphology(os.path.join(_path, "h5/v1/simple.h5")),
    })

    for cell in cells:
        assert_dict_equal(cells[cell].connectivity, {
            -1: [0, 3],
            0: [1, 2],
            3: [4, 5]
        })
コード例 #34
0
    def test_to_dictionary(self):
        d = self.comp.as_dictionary()
        c = self.comp

        nt.assert_equal(c.name, d['name'])
        nt.assert_equal(c._id_name, d['_id_name'])
        nt.assert_false(d['active_is_multidimensional'])
        nt.assert_true(d['active'])
        nt.assert_is_none(d['_active_array'])
        for ip, p in enumerate(c.parameters):
            nt.assert_dict_equal(p.as_dictionary(), d['parameters'][ip])

        c.active_is_multidimensional = True
        d1 = c.as_dictionary()
        nt.assert_true(d1['active_is_multidimensional'])
        np.testing.assert_array_equal(d1['_active_array'], c._active_array)
コード例 #35
0
def test_convert_extra_values():
    """select_combos.table_processing: test convert_extra_values"""

    # dict grows with given field
    for field in ['threshold_current', 'holding_current']:
        value = 42
        data = {'extra_values': json.dumps({field: value})}
        ret = table_processing.convert_extra_values(data)
        nt.assert_equal(ret[field], value)

    # dict does not change
    for field in ['random']:
        value = 42
        data = {'extra_values': json.dumps({field: value})}
        ret = table_processing.convert_extra_values(data)
        nt.assert_dict_equal(ret, data)
コード例 #36
0
    def test_getattribute(self):
        """Testing Fetch.__call__ with attributes"""
        list1 = sorted(self.subject.proj().fetch(as_dict=True), key=itemgetter('subject_id'))
        list2 = sorted(self.subject.fetch(dj.key), key=itemgetter('subject_id'))
        for l1, l2 in zip(list1, list2):
            assert_dict_equal(l1, l2, 'Primary key is not returned correctly')

        tmp = self.subject.fetch(order_by='subject_id')

        subject_notes, key, real_id = self.subject.fetch('subject_notes', dj.key, 'real_id')

        np.testing.assert_array_equal(sorted(subject_notes), sorted(tmp['subject_notes']))
        np.testing.assert_array_equal(sorted(real_id), sorted(tmp['real_id']))
        list1 = sorted(key, key=itemgetter('subject_id'))
        for l1, l2 in zip(list1, list2):
            assert_dict_equal(l1, l2, 'Primary key is not returned correctly')
コード例 #37
0
def test_filterns():
    dct = {
        'test/app3': {},
        'test/app4': {
            'key2': 'val2'
        },
        'test/app5': {
            'key1': 'val1',
            'key2': 'val2'
        }
    }
    nt.assert_dict_equal(
        json.loads(
            check_output(
                "consulconf -i %s --dry_run --filterns '^.*app[345]$'" % (CWD),
                shell=True).decode()), dct)
コード例 #38
0
 def test_003_update_defaults_flat_with_dict(self):
     self.defaults.update({'flat_key': 'flat_val'})
     updates = {'flat_key': {'nkey': 'nval'}}
     expected = {
         'bus': {
             'jid': 'test@localhost',
             'password': '******',
             'host': '127.0.0.1',
             'port': 5555
         },
         'flat_key': {
             'nkey': 'nval'
         }
     }
     d = nested_update(self.defaults, updates)
     assert_dict_equal(d, expected)
コード例 #39
0
ファイル: profile_tests.py プロジェクト: passdedd/piglit
def test_testprofile_update_test_list():
    """ TestProfile.update() updates TestProfile.test_list """
    profile1 = profile.TestProfile()
    group1 = grouptools.join('group1', 'test1')
    group2 = grouptools.join('group1', 'test2')

    profile1.test_list[group1] = utils.Test(['test1'])


    profile2 = profile.TestProfile()
    profile2.test_list[group1] = utils.Test(['test3'])
    profile2.test_list[group2] = utils.Test(['test2'])

    profile1.update(profile2)

    nt.assert_dict_equal(profile1.test_list, profile2.test_list)
コード例 #40
0
 def test_001_update_defaults_dict_with_dict(self):
     updates = {
         'bus': {
             'password': '******'
         },
     }
     expected = {
         'bus': {
             'jid': 'test@localhost',
             'password': '******',
             'host': '127.0.0.1',
             'port': 5555
         }
     }
     d = nested_update(self.defaults, updates)
     assert_dict_equal(d, expected)
コード例 #41
0
def test_to_schema(dg_json, schema_json):
    test_dg = Dataguid(dg_json=dg_json)

    test_dg.to_schema()

    # hashes

    cs = list(filter(lambda x: isinstance(x,dict), test_dg.schema_json.get('identifier')))

    assert_dict_equal(cs[0], schema_json.get('identifier')[0])

    # urls
    assert_equal(test_dg.schema_json.get('contentUrl'), schema_json.get('contentUrl'))

    # size
    assert_equal(test_dg.schema_json.get('contentSize'), schema_json.get('contentSize'))
コード例 #42
0
def test_parse_data_line():
    parser = MADISObservationParser()

    expected = {
        'station_ref': 'FALE',
        'time': datetime(2016, 10, 28, 9, 14),
        'provider_ref': 'af.mtr',
        'dew': 20,
        'rel_hum': 88.426,
        'pressure': 1004.068,
        'temp': 22,
        'wind_dir': 190.0,
        'wind_speed': 4.1
    }

    assert_dict_equal(expected, parser.parse_data_line(line))
コード例 #43
0
 def test_ints_to_floats_w_words(self):
     df = pd.DataFrame([[1, 1], [1, 2], ["henry", -np.nan], [0, np.inf]])
     df_floats = pd.DataFrame([[1, 1.0], [1, 2.0], ["henry", -np.nan],
                               [0, np.inf]])
     #  later
     # df_floats = pd.DataFrame([[1,   1.0],
     #                      [1,        2.0],
     #                      ["henry",  -np.nan],
     #                      [0,        np.inf]])
     print(df)
     print(df_floats)
     print(ints_to_floats(df))
     print(df.dtypes)
     print(df_floats.dtypes)
     print(ints_to_floats(df).dtypes)
     assert_dict_equal(ints_to_floats(df).to_dict(), df_floats.to_dict())
コード例 #44
0
ファイル: test_component.py プロジェクト: temcode/hyperspy
 def test_export_all_twins(self):
     c = self.c
     c.one.export = mock.MagicMock()
     c.two.export = mock.MagicMock()
     c.two.twin = c.one
     c.free_parameters = {
         c.two,
     }
     call_args = {
         'folder': 'folder1',
         'format': 'format1',
         'save_std': 'save_std1'
     }
     c.export(only_free=False, **call_args)
     nt.assert_dict_equal(c.one.export.call_args[1], call_args)
     nt.assert_false(c.two.export.called)
コード例 #45
0
 def test_signal_to_dictionary(self):
     tree = self.tree
     s = BaseSignal([1., 2, 3])
     s.axes_manager[0].name = 'x'
     s.axes_manager[0].units = 'ly'
     tree.set_item('Some name', s)
     d = tree.as_dictionary()
     np.testing.assert_array_equal(d['_sig_Some name']['data'], s.data)
     d['_sig_Some name']['data'] = 0
     nt.assert_dict_equal(
         {
             "Node1": {
                 "leaf11": 11,
                 "Node11": {
                     "leaf111": 111},
             },
             "Node2": {
                 "leaf21": 21,
                 "Node21": {
                     "leaf211": 211},
             },
             "_sig_Some name": {
                 'axes': [
                     {
                         'name': 'x',
                         'navigate': False,
                                 'offset': 0.0,
                                 'scale': 1.0,
                                 'size': 3,
                                 'units': 'ly'}],
                 'data': 0,
                 'learning_results': {},
                 'metadata': {
                     'General': {
                         'title': ''},
                     'Signal': {
                         'binned': False,
                         'signal_type': ''},
                     '_HyperSpy': {
                         'Folding': {
                             'original_axes_manager': None,
                             'original_shape': None,
                             'unfolded': False,
                             'signal_unfolded': False}}},
                 'original_metadata': {},
                 'tmp_parameters': {}}},
         d)
コード例 #46
0
ファイル: tests.py プロジェクト: krasch/quickargs
def test_loader_from_file():
    yaml_params = {
        "key1": "yaml_value_key1",
        "key2": {
            "key2_1": 21,
            "key2_2": 22
        }
    }
    command_line_params = ["--key1=cmd_value_key1", "--key2.key2_2=7"]
    expected = {"key1": "cmd_value_key1", "key2": {"key2_1": 21, "key2_2": 7}}

    with temp_yaml_file(yaml_params) as temp_file:
        with open(temp_file) as f:
            with set_sys_argv(command_line_params):
                actual = yaml.load(f, Loader=YAMLArgsLoader)

    assert_dict_equal(expected, actual)
コード例 #47
0
def test_attributes():
    attr_markdown = r"""{#identify .class1 .class2
    key1=blah key2="o'brien = 1" -}"""
    attr_dict = {
        'id': 'identify',
        'classes': ['class1', 'class2', 'unnumbered'],
        'key1': 'blah',
        'key2': '"o\'brien = 1"'
    }
    attr_html = '''id="identify" class="class1 class2 unnumbered" key1=blah key2="o'brien = 1"'''

    attr = internalreferences.PandocAttributes(attr_markdown, 'markdown')

    print attr_dict
    print attr.to_dict()
    nt.assert_dict_equal(attr_dict, attr.to_dict())
    nt.assert_equal(attr_html, attr.to_html())
コード例 #48
0
    def test_dict(self):
        """
        Tests the to-dict and from-dict methods.
        :return:
        """
        params = {"x": 1, "name": "B"}
        cand1 = Candidate(params)
        entry = cand1.to_dict()
        d = {}
        d["params"] = params
        d["result"] = None
        d["cost"] = None
        d["worker_information"] = None
        assert_dict_equal(entry, d)

        cand2 = from_dict(entry)
        assert_equal(cand1, cand2)
コード例 #49
0
 def test_lat_lon_box(self):
     xml = '<LatLonBox>' \
           '<west>-140.1465</west>' \
           '<east>-56.1753</east>' \
           '<south>19.8791</south>' \
           '<north>49.9041</north>' \
           '</LatLonBox>'
     element = ET.fromstring(xml)
     expected = {
         "west": -140.1465,
         "east": -56.1753,
         "south": 19.8791,
         "north": 49.9041
     }
     actual = NCSSDataset(element).lat_lon_box
     assert actual
     assert_dict_equal(expected, actual)
コード例 #50
0
 def test_query_header1(self):
     expected_result = { #'targetname':'SDSSJ022721.25-010445.8',
                         'band':'JH',
                         'grism':'JH',
                         'exptime':90.,
                         'lnrs': 6,
                         'rdmode': '6'
                        }
     ad = AstroData(TestBookkeeping.f2sciencefile)
     result = {}
     #result['targetname'] = bookkeeping.query_header(ad, 'targetname')
     result['band'] = bookkeeping.query_header(ad, 'band')
     result['grism'] = bookkeeping.query_header(ad, 'grism')
     result['exptime'] = bookkeeping.query_header(ad, 'exptime')
     result['lnrs'] = bookkeeping.query_header(ad, 'lnrs')
     result['rdmode'] = bookkeeping.query_header(ad, 'rdmode')
     assert_dict_equal(result, expected_result)
コード例 #51
0
 def test_scan(self):
     keys = ['zzz0', 'zzz1', 'zzz2', 'zzz3', 'zzz4', 'zzz5', 'zzz6', 'zzz7']
     values = ['a1', 'b2', 'c3', 'd4', 'e5', 'f6', 'g7', 'h8']
     params = {}
     for i in range(len(keys)):
         params[keys[i]] = values[i]
     a = self.client.multi_set(**params)
     assert_equals(a, len(params))
     b = self.client.scan('zzz ', 'zzzz', 10)
     assert_dict_equal(b, params)
     index = 0
     for k, v in b.items():
         assert_equals(k, keys[index])
         assert_equals(v, values[index])
         index += 1
     d = self.client.multi_del(*params.keys())
     assert_equals(d, len(params))
コード例 #52
0
def test_composite_maybe_none():
    p = SeparatedTextObservationParser(' +', [
        ('a_float', float, 2),
        ('maybe_none', float_or_na, 1),
        ('bar', unicode, 3),
    ])
    r = p.parse_data_line('NA 3 3 3 NA')
    assert_dict_equal(r, {
        'a_float': 3.0,
        'maybe_none': 3.0,
        'bar': '3'
    })
    r = p.parse_data_line('NA NA 3 3 NA')
    assert_dict_equal(r, {
        'a_float': 3.0,
        'maybe_none': None,
        'bar': '3'
    })
コード例 #53
0
def test_landsverk_vaisala_parse_data_line():
    p_v = LandsverkVaisalaObservationParser()
    line_v = '2013 01 01 00:08 3.5 82 0.7 0 1.0 192 NA 4.3 0.00 NA NA 979.4 NA NA NA 1 NA NA NA NA NA NA 0 NA NA' \
             ' 2.0 243 NA NA NA NA 0.0 0.0 NA NA NA NA NA NA NA NA NA NA NA NA NA 0.0 0.0 NA NA NA NA NA NA NA NA NA'
    exp = {
        'time': round_timestamp_10min(datetime(2013, 1, 1, 0, 8, 0)),
        'temp': 3.5,
        'rel_hum': 82.0,
        'wind_speed': 1.0,
        'wind_dir': 192.0,
        'pressure': 979.4,
        'wind_gust': 2.0,
        'temp_road': None
    }
    act = p_v.parse_data_line(line_v)
    LOG.info('act["time"] = %s', act["time"])
    LOG.info('exp["time"] = %s', exp["time"])
    assert_dict_equal(exp, act)
コード例 #54
0
ファイル: test_read.py プロジェクト: ybj2004/wos-1
    def test_multiple_records(self):
        f = StringIO("PT\tAF\tC1\nJ\tAa; Bb\tX; Y\nJ\tBb; Cc\tY; Z")
        r = TabDelimitedReader(f)

        results = [result for result in r]
        expected = [{
            "PT": "J",
            "AF": "Aa; Bb",
            "C1": "X; Y"
        }, {
            "PT": "J",
            "AF": "Bb; Cc",
            "C1": "Y; Z"
        }]

        assert_equal(len(results), len(expected))
        for result, exp in zip(results, expected):
            assert_dict_equal(result, exp)
コード例 #55
0
ファイル: test_read.py プロジェクト: ybj2004/wos-1
    def test_multiple_records(self):
        f = StringIO(preamble_s + "PT abc\nAU xyz\nER\n\nPT abc2\n AU xyz2\n"
                     "AB abstract\nER\nEF")
        r = PlainTextReader(f)

        results = list(r)
        expected = [{
            "PT": "abc",
            "AU": "xyz"
        }, {
            "PT": "abc2",
            "AU": "xyz2",
            "AB": "abstract"
        }]

        assert_equal(len(results), len(expected))
        for result, exp in zip(results, expected):
            assert_dict_equal(result, exp)
コード例 #56
0
 def test_projection_box(self):
     xml = '<projectionBox>' \
           '<minx>-2959.1533203125</minx>' \
           '<maxx>2932.8466796875</maxx>' \
           '<miny>-1827.929443359375</miny>' \
           '<maxy>1808.070556640625</maxy>' \
           '</projectionBox>'
     element = ET.fromstring(xml)
     expected = {
         "projectionBox": {
             "minx": -2959.1533203125,
             "maxx": 2932.8466796875,
             "miny": -1827.929443359375,
             "maxy": 1808.070556640625
         }
     }
     actual = self.types.handle_projectionBox(element)
     assert_dict_equal(expected, actual)
コード例 #57
0
def test_simple():
    p = SeparatedTextObservationParser(' +', [
        ('smu', str, 0),
        ('foo', str, 2),
        ('bar', str, 5)
    ])

    r = p.parse_header_line('abba   bar   ceres   denali  eifel falaffel giraffe hotel')
    assert_false(r)

    r = p.parse_data_line('Abba   bar   Ceres   denali  eiffel falaffel giraffe hotel')
    assert_dict_equal(r, {'smu': 'Abba', 'foo': 'Ceres', 'bar': 'falaffel'})

    r = p.parse_data_line('Aragorn   Bilbo  Celeborn   Dáin  Éowyn Faramir Gandalf  Háma')
    assert_dict_equal(r, {'smu': 'Aragorn', 'foo': 'Celeborn', 'bar': 'Faramir'})

    r = p.end_input()
    assert_is_none(r)
コード例 #58
0
def test_get_configuration_unit():
    with patch("raspi.scripts.get_serial.open") as mock_open:
        with NamedTemporaryFile() as tmp:
            with open(tmp.name, "r+w") as mock_config_file:
                mock_config_file.write(MOCK_CONFIG_FILE)
                mock_config_file.flush()
                mock_config_file.seek(0)
                mock_open.return_value = mock_config_file
                config_dict = get_configuration("foo/bar")
                assert_dict_equal(
                    config_dict, {
                        "baudrate": 38400,
                        "tty_file": "foo/bar",
                        "data_path": "pi/mock/data",
                        "refresh_rate": 1000,
                        "vent_disconnect_tolerance": 1,
                    }
                )
コード例 #59
0
ファイル: test_apis.py プロジェクト: jyeg/snapwagon
    def test_new_customer_can_place_order(self):
        # Mock call to Stripe.
        mock_charge = Mock(amount=1500, status='succeeded')
        patch('organizations.apis.stripe.Charge.create',
              return_value=mock_charge).start()

        # Mock call to SparkPost.
        patch('organizations.apis.sparkpost.SparkPost').start()

        assert_equal(0, Customer.objects.count())
        order = self.create_order(self.offer.id)
        response = self.client.post(reverse('api:order_list'),
                                    data=order,
                                    format='json')
        assert_equal(1, Customer.objects.count())
        assert_equal(1, Order.objects.count())
        order = Order.objects.last()
        assert_dict_equal(OrderSerializer(order).data, response.data)
コード例 #60
0
    def test_custom_linkage(self):
        kws = self.default_kws.copy()

        try:
            import fastcluster

            linkage = fastcluster.linkage_vector(self.x_norm, method='single',
                                                 metric='euclidean')
        except ImportError:
            d = distance.pdist(self.x_norm, metric='euclidean')
            linkage = hierarchy.linkage(d, method='single')
        dendrogram = hierarchy.dendrogram(linkage, no_plot=True,
                                          color_threshold=-np.inf)
        kws['linkage'] = linkage
        p = mat._DendrogramPlotter(self.df_norm, **kws)

        npt.assert_array_equal(p.linkage, linkage)
        nt.assert_dict_equal(p.dendrogram, dendrogram)