Python collections.UserDict() Examples

The following are 30 code examples of collections.UserDict(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module collections , or try the search function .
Example #1
Source File: test_auth.py    From backend.ai-manager with GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_extract_auth_params():
    request = UserDict()

    request.headers = {}
    assert _extract_auth_params(request) is None

    request.headers = {'Authorization': 'no-space'}
    with pytest.raises(InvalidAuthParameters):
        _extract_auth_params(request)

    request.headers = {'Authorization': ('BadAuthType signMethod=HMAC-SHA256,'
                                         'credential=fake-ak:fake-sig')}
    with pytest.raises(InvalidAuthParameters):
        _extract_auth_params(request)

    request.headers = {'Authorization': ('BackendAI signMethod=HMAC-SHA256,'
                                         'credential=fake-ak:fake-sig')}
    ret = _extract_auth_params(request)
    assert ret[0] == 'HMAC-SHA256'
    assert ret[1] == 'fake-ak'
    assert ret[2] == 'fake-sig' 
Example #2
Source File: test_json.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_custom_asserts(self):
        # This would always trigger the KeyError from trying to put
        # an array of equal-length UserDicts inside an ndarray.
        data = JSONArray([collections.UserDict({'a': 1}),
                          collections.UserDict({'b': 2}),
                          collections.UserDict({'c': 3})])
        a = pd.Series(data)
        self.assert_series_equal(a, a)
        self.assert_frame_equal(a.to_frame(), a.to_frame())

        b = pd.Series(data.take([0, 0, 1]))
        with pytest.raises(AssertionError):
            self.assert_series_equal(a, b)

        with pytest.raises(AssertionError):
            self.assert_frame_equal(a.to_frame(), b.to_frame()) 
Example #3
Source File: test_json.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_custom_asserts(self):
        # This would always trigger the KeyError from trying to put
        # an array of equal-length UserDicts inside an ndarray.
        data = JSONArray([collections.UserDict({'a': 1}),
                          collections.UserDict({'b': 2}),
                          collections.UserDict({'c': 3})])
        a = pd.Series(data)
        self.assert_series_equal(a, a)
        self.assert_frame_equal(a.to_frame(), a.to_frame())

        b = pd.Series(data.take([0, 0, 1]))
        with pytest.raises(AssertionError):
            self.assert_series_equal(a, b)

        with pytest.raises(AssertionError):
            self.assert_frame_equal(a.to_frame(), b.to_frame()) 
Example #4
Source File: test_json.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 6 votes vote down vote up
def test_custom_asserts(self):
        # This would always trigger the KeyError from trying to put
        # an array of equal-length UserDicts inside an ndarray.
        data = JSONArray([collections.UserDict({'a': 1}),
                          collections.UserDict({'b': 2}),
                          collections.UserDict({'c': 3})])
        a = pd.Series(data)
        self.assert_series_equal(a, a)
        self.assert_frame_equal(a.to_frame(), a.to_frame())

        b = pd.Series(data.take([0, 0, 1]))
        with pytest.raises(AssertionError):
            self.assert_series_equal(a, b)

        with pytest.raises(AssertionError):
            self.assert_frame_equal(a.to_frame(), b.to_frame()) 
Example #5
Source File: test_collections.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_MutableMapping_subclass(self):
        # Test issue 9214
        mymap = UserDict()
        mymap['red'] = 5
        self.assertIsInstance(mymap.keys(), Set)
        self.assertIsInstance(mymap.keys(), KeysView)
        self.assertIsInstance(mymap.items(), Set)
        self.assertIsInstance(mymap.items(), ItemsView)

        mymap = UserDict()
        mymap['red'] = 5
        z = mymap.keys() | {'orange'}
        self.assertIsInstance(z, set)
        list(z)
        mymap['blue'] = 7               # Shouldn't affect 'z'
        self.assertEqual(sorted(z), ['orange', 'red'])

        mymap = UserDict()
        mymap['red'] = 5
        z = mymap.items() | {('orange', 3)}
        self.assertIsInstance(z, set)
        list(z)
        mymap['blue'] = 7               # Shouldn't affect 'z'
        self.assertEqual(sorted(z), [('orange', 3), ('red', 5)]) 
Example #6
Source File: pickletester.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_compat_pickle(self):
        tests = [
            (range(1, 7), '__builtin__', 'xrange'),
            (map(int, '123'), 'itertools', 'imap'),
            (functools.reduce, '__builtin__', 'reduce'),
            (dbm.whichdb, 'whichdb', 'whichdb'),
            (Exception(), 'exceptions', 'Exception'),
            (collections.UserDict(), 'UserDict', 'IterableUserDict'),
            (collections.UserList(), 'UserList', 'UserList'),
            (collections.defaultdict(), 'collections', 'defaultdict'),
        ]
        for val, mod, name in tests:
            for proto in range(3):
                with self.subTest(type=type(val), proto=proto):
                    pickled = self.dumps(val, proto)
                    self.assertIn(('c%s\n%s' % (mod, name)).encode(), pickled)
                    self.assertIs(type(self.loads(pickled)), type(val)) 
Example #7
Source File: test_inspect.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_plain(self):
        f = self.makeCallable('a, b=1')
        self.assertEqualCallArgs(f, '2')
        self.assertEqualCallArgs(f, '2, 3')
        self.assertEqualCallArgs(f, 'a=2')
        self.assertEqualCallArgs(f, 'b=3, a=2')
        self.assertEqualCallArgs(f, '2, b=3')
        # expand *iterable / **mapping
        self.assertEqualCallArgs(f, '*(2,)')
        self.assertEqualCallArgs(f, '*[2]')
        self.assertEqualCallArgs(f, '*(2, 3)')
        self.assertEqualCallArgs(f, '*[2, 3]')
        self.assertEqualCallArgs(f, '**{"a":2}')
        self.assertEqualCallArgs(f, 'b=3, **{"a":2}')
        self.assertEqualCallArgs(f, '2, **{"b":3}')
        self.assertEqualCallArgs(f, '**{"b":3, "a":2}')
        # expand UserList / UserDict
        self.assertEqualCallArgs(f, '*collections.UserList([2])')
        self.assertEqualCallArgs(f, '*collections.UserList([2, 3])')
        self.assertEqualCallArgs(f, '**collections.UserDict(a=2)')
        self.assertEqualCallArgs(f, '2, **collections.UserDict(b=3)')
        self.assertEqualCallArgs(f, 'b=2, **collections.UserDict(a=3)') 
Example #8
Source File: test_inspect.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_multiple_features(self):
        f = self.makeCallable('a, b=2, *f, **g')
        self.assertEqualCallArgs(f, '2, 3, 7')
        self.assertEqualCallArgs(f, '2, 3, x=8')
        self.assertEqualCallArgs(f, '2, 3, x=8, *[(4,[5,6]), 7]')
        self.assertEqualCallArgs(f, '2, x=8, *[3, (4,[5,6]), 7], y=9')
        self.assertEqualCallArgs(f, 'x=8, *[2, 3, (4,[5,6])], y=9')
        self.assertEqualCallArgs(f, 'x=8, *collections.UserList('
                                 '[2, 3, (4,[5,6])]), **{"y":9, "z":10}')
        self.assertEqualCallArgs(f, '2, x=8, *collections.UserList([3, '
                                 '(4,[5,6])]), **collections.UserDict('
                                 'y=9, z=10)')

        f = self.makeCallable('a, b=2, *f, x, y=99, **g')
        self.assertEqualCallArgs(f, '2, 3, x=8')
        self.assertEqualCallArgs(f, '2, 3, x=8, *[(4,[5,6]), 7]')
        self.assertEqualCallArgs(f, '2, x=8, *[3, (4,[5,6]), 7], y=9, z=10')
        self.assertEqualCallArgs(f, 'x=8, *[2, 3, (4,[5,6])], y=9, z=10')
        self.assertEqualCallArgs(f, 'x=8, *collections.UserList('
                                 '[2, 3, (4,[5,6])]), q=0, **{"y":9, "z":10}')
        self.assertEqualCallArgs(f, '2, x=8, *collections.UserList([3, '
                                 '(4,[5,6])]), q=0, **collections.UserDict('
                                 'y=9, z=10)') 
Example #9
Source File: test_collections.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_MutableMapping_subclass(self):
        # Test issue 9214
        mymap = UserDict()
        mymap['red'] = 5
        self.assertIsInstance(mymap.keys(), Set)
        self.assertIsInstance(mymap.keys(), KeysView)
        self.assertIsInstance(mymap.items(), Set)
        self.assertIsInstance(mymap.items(), ItemsView)

        mymap = UserDict()
        mymap['red'] = 5
        z = mymap.keys() | {'orange'}
        self.assertIsInstance(z, set)
        list(z)
        mymap['blue'] = 7               # Shouldn't affect 'z'
        self.assertEqual(sorted(z), ['orange', 'red'])

        mymap = UserDict()
        mymap['red'] = 5
        z = mymap.items() | {('orange', 3)}
        self.assertIsInstance(z, set)
        list(z)
        mymap['blue'] = 7               # Shouldn't affect 'z'
        self.assertEqual(sorted(z), [('orange', 3), ('red', 5)]) 
Example #10
Source File: pickletester.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_compat_pickle(self):
        tests = [
            (range(1, 7), '__builtin__', 'xrange'),
            (map(int, '123'), 'itertools', 'imap'),
            (functools.reduce, '__builtin__', 'reduce'),
            (dbm.whichdb, 'whichdb', 'whichdb'),
            (Exception(), 'exceptions', 'Exception'),
            (collections.UserDict(), 'UserDict', 'IterableUserDict'),
            (collections.UserList(), 'UserList', 'UserList'),
            (collections.defaultdict(), 'collections', 'defaultdict'),
        ]
        for val, mod, name in tests:
            for proto in range(3):
                with self.subTest(type=type(val), proto=proto):
                    pickled = self.dumps(val, proto)
                    self.assertIn(('c%s\n%s' % (mod, name)).encode(), pickled)
                    self.assertIs(type(self.loads(pickled)), type(val)) 
Example #11
Source File: test_inspect.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_plain(self):
        f = self.makeCallable('a, b=1')
        self.assertEqualCallArgs(f, '2')
        self.assertEqualCallArgs(f, '2, 3')
        self.assertEqualCallArgs(f, 'a=2')
        self.assertEqualCallArgs(f, 'b=3, a=2')
        self.assertEqualCallArgs(f, '2, b=3')
        # expand *iterable / **mapping
        self.assertEqualCallArgs(f, '*(2,)')
        self.assertEqualCallArgs(f, '*[2]')
        self.assertEqualCallArgs(f, '*(2, 3)')
        self.assertEqualCallArgs(f, '*[2, 3]')
        self.assertEqualCallArgs(f, '**{"a":2}')
        self.assertEqualCallArgs(f, 'b=3, **{"a":2}')
        self.assertEqualCallArgs(f, '2, **{"b":3}')
        self.assertEqualCallArgs(f, '**{"b":3, "a":2}')
        # expand UserList / UserDict
        self.assertEqualCallArgs(f, '*collections.UserList([2])')
        self.assertEqualCallArgs(f, '*collections.UserList([2, 3])')
        self.assertEqualCallArgs(f, '**collections.UserDict(a=2)')
        self.assertEqualCallArgs(f, '2, **collections.UserDict(b=3)')
        self.assertEqualCallArgs(f, 'b=2, **collections.UserDict(a=3)') 
Example #12
Source File: test_inspect.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_multiple_features(self):
        f = self.makeCallable('a, b=2, *f, **g')
        self.assertEqualCallArgs(f, '2, 3, 7')
        self.assertEqualCallArgs(f, '2, 3, x=8')
        self.assertEqualCallArgs(f, '2, 3, x=8, *[(4,[5,6]), 7]')
        self.assertEqualCallArgs(f, '2, x=8, *[3, (4,[5,6]), 7], y=9')
        self.assertEqualCallArgs(f, 'x=8, *[2, 3, (4,[5,6])], y=9')
        self.assertEqualCallArgs(f, 'x=8, *collections.UserList('
                                 '[2, 3, (4,[5,6])]), **{"y":9, "z":10}')
        self.assertEqualCallArgs(f, '2, x=8, *collections.UserList([3, '
                                 '(4,[5,6])]), **collections.UserDict('
                                 'y=9, z=10)')

        f = self.makeCallable('a, b=2, *f, x, y=99, **g')
        self.assertEqualCallArgs(f, '2, 3, x=8')
        self.assertEqualCallArgs(f, '2, 3, x=8, *[(4,[5,6]), 7]')
        self.assertEqualCallArgs(f, '2, x=8, *[3, (4,[5,6]), 7], y=9, z=10')
        self.assertEqualCallArgs(f, 'x=8, *[2, 3, (4,[5,6])], y=9, z=10')
        self.assertEqualCallArgs(f, 'x=8, *collections.UserList('
                                 '[2, 3, (4,[5,6])]), q=0, **{"y":9, "z":10}')
        self.assertEqualCallArgs(f, '2, x=8, *collections.UserList([3, '
                                 '(4,[5,6])]), q=0, **collections.UserDict('
                                 'y=9, z=10)') 
Example #13
Source File: main_test.py    From python-docs-samples with Apache License 2.0 6 votes vote down vote up
def test_avoid_infinite_retries(capsys):
    now = datetime.now(timezone.utc)

    with patch('main.datetime', wraps=datetime) as datetime_mock:
        datetime_mock.now = Mock(return_value=now)

        old_context = UserDict()
        old_context.timestamp = (now - timedelta(seconds=15)).isoformat()
        old_context.event_id = 'old_event_id'

        young_context = UserDict()
        young_context.timestamp = (now - timedelta(seconds=5)).isoformat()
        young_context.event_id = 'young_event_id'

        main.avoid_infinite_retries(None, old_context)
        out, _ = capsys.readouterr()
        assert f"Dropped {old_context.event_id} (age 15000.0ms)" in out

        main.avoid_infinite_retries(None, young_context)
        out, _ = capsys.readouterr()
        assert f"Processed {young_context.event_id} (age 5000.0ms)" in out 
Example #14
Source File: main_test.py    From python-docs-samples with Apache License 2.0 6 votes vote down vote up
def test_process_offensive_image(
  storage_client,
  vision_client,
  __blur_image,
  capsys):
    result = UserDict()
    result.safe_search_annotation = UserDict()
    result.safe_search_annotation.adult = 5
    result.safe_search_annotation.violence = 5
    vision_client.safe_search_detection = MagicMock(return_value=result)

    filename = str(uuid.uuid4())
    data = {
      'bucket': 'my-bucket',
      'name': filename
    }

    main.blur_offensive_images(data, None)

    out, _ = capsys.readouterr()
    assert 'Analyzing %s.' % filename in out
    assert 'The image %s was detected as inappropriate.' % filename in out
    assert main.__blur_image.called 
Example #15
Source File: main_test.py    From python-docs-samples with Apache License 2.0 6 votes vote down vote up
def test_process_safe_image(
  storage_client,
  vision_client,
  __blur_image,
  capsys):
    result = UserDict()
    result.safe_search_annotation = UserDict()
    result.safe_search_annotation.adult = 1
    result.safe_search_annotation.violence = 1
    vision_client.safe_search_detection = MagicMock(return_value=result)

    filename = str(uuid.uuid4())
    data = {
      'bucket': 'my-bucket',
      'name': filename
    }

    main.blur_offensive_images(data, None)

    out, _ = capsys.readouterr()

    assert 'Analyzing %s.' % filename in out
    assert 'The image %s was detected as OK.' % filename in out
    assert __blur_image.called is False 
Example #16
Source File: image_test.py    From python-docs-samples with Apache License 2.0 6 votes vote down vote up
def test_process_safe_image(
  storage_client,
  vision_client,
  __blur_image,
  capsys):
    result = UserDict()
    result.safe_search_annotation = UserDict()
    result.safe_search_annotation.adult = 1
    result.safe_search_annotation.violence = 1
    vision_client.safe_search_detection = MagicMock(return_value=result)

    filename = str(uuid.uuid4())
    data = {
      'bucket': 'my-bucket',
      'name': filename
    }

    image.blur_offensive_images(data)

    out, _ = capsys.readouterr()

    assert 'Analyzing %s.' % filename in out
    assert 'The image %s was detected as OK.' % filename in out
    assert __blur_image.called is False 
Example #17
Source File: __init__.py    From jx-sqlite with Mozilla Public License 2.0 6 votes vote down vote up
def __init__(*args, **kwargs):
            if not args:
                raise TypeError("descriptor '__init__' of 'UserDict' object "
                                "needs an argument")
            self, args = args[0], args[1:]
            if len(args) > 1:
                raise TypeError('expected at most 1 arguments, got %d' % len(args))
            if args:
                dict = args[0]
            elif 'dict' in kwargs:
                dict = kwargs.pop('dict')
                import warnings
                warnings.warn("Passing 'dict' as keyword argument is deprecated",
                              DeprecationWarning, stacklevel=2)
            else:
                dict = None
            self.data = {}
            if dict is not None:
                self.update(dict)
            if len(kwargs):
                self.update(kwargs) 
Example #18
Source File: test_misc.py    From http-observatory with Mozilla Public License 2.0 6 votes vote down vote up
def test_redirects_to_https_with_port_number(self):
        # same thing, but with :443 on the URL, see issue #180
        self.reqs['responses']['http'].url = 'https://http-observatory.security.mozilla.org:443/'

        history1 = UserDict()
        history1.request = UserDict()
        history1.request.url = 'http://http-observatory.security.mozilla.org/'

        self.reqs['responses']['http'].history.append(history1)

        result = redirection(self.reqs)

        self.assertEquals('redirection-to-https', result['result'])
        self.assertEquals(['http://http-observatory.security.mozilla.org/',
                           'https://http-observatory.security.mozilla.org:443/'], result['route'])
        self.assertTrue(result['pass']) 
Example #19
Source File: test_misc.py    From http-observatory with Mozilla Public License 2.0 6 votes vote down vote up
def test_first_redirection_still_http(self):
        self.reqs['responses']['http'].url = 'https://http-observatory.security.mozilla.org/foo'

        history1 = UserDict()
        history1.request = UserDict()
        history1.request.url = 'http://http-observatory.security.mozilla.org/'

        history2 = UserDict()
        history2.request = UserDict()
        history2.request.url = 'http://http-observatory.security.mozilla.org/foo'

        self.reqs['responses']['http'].history.append(history1)
        self.reqs['responses']['http'].history.append(history2)

        result = redirection(self.reqs)

        self.assertEquals('redirection-not-to-https-on-initial-redirection', result['result'])
        self.assertFalse(result['pass']) 
Example #20
Source File: test_misc.py    From http-observatory with Mozilla Public License 2.0 6 votes vote down vote up
def test_all_redirections_preloaded(self):
        self.reqs['responses']['http'].url = 'https://www.pokeinthe.io/foo/bar'

        for url in ('http://pokeinthe.io/',
                    'https://pokeinthe.io/',
                    'https://www.pokeinthe.io/',
                    'https://baz.pokeinthe.io/foo'):
            history = UserDict()
            history.request = UserDict()
            history.request.url = url

            self.reqs['responses']['http'].history.append(history)

        result = redirection(self.reqs)

        self.assertEquals('redirection-all-redirects-preloaded', result['result'])
        self.assertTrue(result['pass']) 
Example #21
Source File: array.py    From recruit with Apache License 2.0 5 votes vote down vote up
def _from_factorized(cls, values, original):
        return cls([collections.UserDict(x) for x in values if x != ()]) 
Example #22
Source File: array.py    From recruit with Apache License 2.0 5 votes vote down vote up
def astype(self, dtype, copy=True):
        # NumPy has issues when all the dicts are the same length.
        # np.array([UserDict(...), UserDict(...)]) fails,
        # but np.array([{...}, {...}]) works, so cast.

        # needed to add this check for the Series constructor
        if isinstance(dtype, type(self.dtype)) and dtype == self.dtype:
            if copy:
                return self.copy()
            return self
        return np.array([dict(x) for x in self], dtype=dtype, copy=copy) 
Example #23
Source File: array.py    From recruit with Apache License 2.0 5 votes vote down vote up
def make_data():
    # TODO: Use a regular dict. See _NDFrameIndexer._setitem_with_indexer
    return [collections.UserDict([
        (random.choice(string.ascii_letters), random.randint(0, 100))
        for _ in range(random.randint(0, 10))]) for _ in range(100)] 
Example #24
Source File: test_json.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_groupby_extension_apply(self):
        """
        This fails in Index._do_unique_check with

        >   hash(val)
        E   TypeError: unhashable type: 'UserDict' with

        I suspect that once we support Index[ExtensionArray],
        we'll be able to dispatch unique.
        """ 
Example #25
Source File: utils.py    From fac with MIT License 5 votes vote down vote up
def _unwrap(obj):
    if isinstance(obj, UserList) or isinstance(obj, UserDict):
        return obj.data
    return obj 
Example #26
Source File: Builder.py    From arnold-usd with Apache License 2.0 5 votes vote down vote up
def __init__(self, dict):
        collections.UserDict.__init__(self, dict)
        if SCons.Debug.track_instances: logInstanceCreation(self, 'Builder.OverrideWarner')
        self.already_warned = None 
Example #27
Source File: test_type.py    From pledgeservice with Apache License 2.0 5 votes vote down vote up
def test_UserDict_is_object(self):
        # A UserDict (and similar classes) are not dicts, but they're dict-like
        # and should be treated as objects

        try:
            # Python 2
            from UserDict import UserDict
        except ImportError:
            # Python 3
            from collections import UserDict

        valids = [UserDict({"a": "b"})]
        invalids = []
        self._test_type('object', valids, invalids) 
Example #28
Source File: Builder.py    From web2board with GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, dict):
        collections.UserDict.__init__(self, dict)
        if SCons.Debug.track_instances: logInstanceCreation(self, 'Builder.OverrideWarner')
        self.already_warned = None 
Example #29
Source File: array.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def _from_factorized(cls, values, original):
        return cls([collections.UserDict(x) for x in values if x != ()]) 
Example #30
Source File: array.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def astype(self, dtype, copy=True):
        # NumPy has issues when all the dicts are the same length.
        # np.array([UserDict(...), UserDict(...)]) fails,
        # but np.array([{...}, {...}]) works, so cast.
        return np.array([dict(x) for x in self], dtype=dtype, copy=copy)