Python types.SimpleNamespace() Examples

The following are code examples for showing how to use types.SimpleNamespace(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: serious-django-graphene   Author: serioeseGmbH   File: test_failable_mutation.py    MIT License 6 votes vote down vote up
def test_default_mutate_calls_perform_mutate(self):
        class MyFailableMutation(FailableMutation):
            __method_calls__ = 0
            some_result = graphene.Int()

            @classmethod
            def perform_mutate(cls, info, *args, **kwargs):
                cls.__method_calls__ += 1
                return cls(some_result=42)

        mut = MyFailableMutation()
        self.assertEqual(MyFailableMutation.__method_calls__, 0)
        mutation_result = mut.mutate(SimpleNamespace())
        self.assertEqual(mutation_result.some_result, 42)
        self.assertEqual(MyFailableMutation.__method_calls__, 1)
        mut.mutate(SimpleNamespace())
        self.assertEqual(MyFailableMutation.__method_calls__, 2) 
Example 2
Project: sanic   Author: huge-success   File: request.py    MIT License 6 votes vote down vote up
def __init__(self, url_bytes, headers, version, method, transport, app):
        self.raw_url = url_bytes
        # TODO: Content-Encoding detection
        self._parsed_url = parse_url(url_bytes)
        self.app = app

        self.headers = headers
        self.version = version
        self.method = method
        self.transport = transport

        # Init but do not inhale
        self.body_init()
        self.ctx = SimpleNamespace()
        self.parsed_forwarded = None
        self.parsed_json = None
        self.parsed_form = None
        self.parsed_files = None
        self.parsed_args = defaultdict(RequestParameters)
        self.parsed_not_grouped_args = defaultdict(list)
        self.uri_template = None
        self._cookies = None
        self.stream = None
        self.endpoint = None 
Example 3
Project: pywren-ibm-cloud   Author: pywren   File: invoker.py    Apache License 2.0 6 votes vote down vote up
def _remote_invoke(self, job_description):
        """
        Method used to send a job_description to the remote invoker
        """
        start = time.time()
        compute_handler = random.choice(self.compute_handlers)
        job = SimpleNamespace(**job_description)

        payload = {'config': self.config,
                   'log_level': self.log_level,
                   'job_description': job_description,
                   'remote_invoker': True,
                   'pywren_version': __version__}

        activation_id = compute_handler.invoke(job.runtime_name, REMOTE_INVOKER_MEMORY, payload)
        roundtrip = time.time() - start
        resp_time = format(round(roundtrip, 3), '.3f')

        if activation_id:
            logger.debug('ExecutorID {} | JobID {} - Remote function invocation done! ({}s) - Activation'
                         ' ID: {}'.format(job.executor_id, job.job_id, resp_time, activation_id))
        else:
            raise Exception('Unable to spawn remote invoker') 
Example 4
Project: NiujiaoDebugger   Author: MrSrc   File: runtest_mp.py    GNU General Public License v3.0 6 votes vote down vote up
def run_tests_worker(worker_args):
    ns_dict, testname = json.loads(worker_args)
    ns = types.SimpleNamespace(**ns_dict)

    setup_tests(ns)

    try:
        result = runtest(ns, testname)
    except KeyboardInterrupt:
        result = INTERRUPTED, '', None
    except BaseException as e:
        traceback.print_exc()
        result = CHILD_ERROR, str(e)

    print()   # Force a newline (just in case)
    print(json.dumps(result), flush=True)
    sys.exit(0)


# We do not use a generator so multiple threads can call next(). 
Example 5
Project: NiujiaoDebugger   Author: MrSrc   File: test_types.py    GNU General Public License v3.0 6 votes vote down vote up
def test_constructor(self):
        ns1 = types.SimpleNamespace()
        ns2 = types.SimpleNamespace(x=1, y=2)
        ns3 = types.SimpleNamespace(**dict(x=1, y=2))

        with self.assertRaises(TypeError):
            types.SimpleNamespace(1, 2, 3)
        with self.assertRaises(TypeError):
            types.SimpleNamespace(**{1: 2})

        self.assertEqual(len(ns1.__dict__), 0)
        self.assertEqual(vars(ns1), {})
        self.assertEqual(len(ns2.__dict__), 2)
        self.assertEqual(vars(ns2), {'y': 2, 'x': 1})
        self.assertEqual(len(ns3.__dict__), 2)
        self.assertEqual(vars(ns3), {'y': 2, 'x': 1}) 
Example 6
Project: NiujiaoDebugger   Author: MrSrc   File: test_types.py    GNU General Public License v3.0 6 votes vote down vote up
def test_attrdel(self):
        ns1 = types.SimpleNamespace()
        ns2 = types.SimpleNamespace(x=1, y=2, w=3)

        with self.assertRaises(AttributeError):
            del ns1.spam
        with self.assertRaises(AttributeError):
            del ns2.spam

        del ns2.y
        self.assertEqual(vars(ns2), dict(w=3, x=1))
        ns2.y = 'spam'
        self.assertEqual(vars(ns2), dict(w=3, x=1, y='spam'))
        del ns2.y
        self.assertEqual(vars(ns2), dict(w=3, x=1))

        ns1.spam = 5
        self.assertEqual(vars(ns1), dict(spam=5))
        del ns1.spam
        self.assertEqual(vars(ns1), {}) 
Example 7
Project: cimon_controller   Author: SchweizerischeBundesbahnen   File: test_collector.py    Apache License 2.0 6 votes vote down vote up
def create_http_client(self, response_str="", http_error_codes=None, authentication_handler=EmptyAuthenticationHandler(), header=None):
        h = HttpClient(base_url="http://irgendw.as",
                       authentication_handler= authentication_handler,
                       retry_delay_sec=0)
        response = SimpleNamespace()
        response.read = Mock(spec=(""), return_value=response_str.encode("UTF-8"))
        response.headers = SimpleNamespace()
        response.headers.get_content_charset= Mock(spec=(""), return_value="UTF-8")
        response.getheader = Mock(spec=(""), return_value=header)

        side_effects = [HTTPError("http://foo.bar", code, None, None, None) if code else DEFAULT for code in http_error_codes] if http_error_codes else None

        h.__open__ = Mock(spec=(""),
                          return_value=response,
                          side_effect=side_effects)
        return h 
Example 8
Project: python-graphlayer   Author: mwilliamson   File: test_resolvers.py    BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_attr_uses_attr_name_to_resolve_field(self):
        User = g.ObjectType("User", fields=(
            g.field("name", type=g.String),
            g.field("email_address", type=g.String),
        ))

        object_builder = g.create_object_builder(User(
            g.key("n", User.fields.name()),
            g.key("e", User.fields. email_address()),
        ))

        object_builder.attr(User.fields.name, "name")
        object_builder.attr(User.fields.email_address, "email")

        result = object_builder(types.SimpleNamespace(name="Bob", email="[email protected]"))
        assert_that(result, has_attrs(
            n="Bob",
            e="[email protected]",
        )) 
Example 9
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: polar.py    MIT License 6 votes vote down vote up
def start_pan(self, x, y, button):
        angle = np.deg2rad(self.get_rlabel_position())
        mode = ''
        if button == 1:
            epsilon = np.pi / 45.0
            t, r = self.transData.inverted().transform_point((x, y))
            if angle - epsilon <= t <= angle + epsilon:
                mode = 'drag_r_labels'
        elif button == 3:
            mode = 'zoom'

        self._pan_start = types.SimpleNamespace(
            rmax=self.get_rmax(),
            trans=self.transData.frozen(),
            trans_inverse=self.transData.inverted().frozen(),
            r_label_angle=self.get_rlabel_position(),
            x=x,
            y=y,
            mode=mode) 
Example 10
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: _base.py    MIT License 6 votes vote down vote up
def start_pan(self, x, y, button):
        """
        Called when a pan operation has started.

        *x*, *y* are the mouse coordinates in display coords.
        button is the mouse button number:

        * 1: LEFT
        * 2: MIDDLE
        * 3: RIGHT

        .. note::

            Intended to be overridden by new projection types.

        """
        self._pan_start = types.SimpleNamespace(
            lim=self.viewLim.frozen(),
            trans=self.transData.frozen(),
            trans_inverse=self.transData.inverted().frozen(),
            bbox=self.bbox.frozen(),
            x=x,
            y=y) 
Example 11
Project: VLC-Scheduler   Author: EugeneDae   File: playlist.py    MIT License 6 votes vote down vote up
def prepare_source(self, source):
        prepared = types.SimpleNamespace(
            active=True,
            path=source['path'],
            shuffle=bool(source.get('shuffle', False)),
            recursive=bool(source.get('recursive', self._recursive)),
            item_play_duration=int(source.get('item_play_duration', 0)),
            play_every_minutes=int(source.get('play_every_minutes', 0)),
            start_time=None,
            end_time=None
        )
        
        if source.get('playing_time'):
            prepared.start_time, prepared.end_time = (
                datetime.datetime.strptime(i, '%H:%M').time() for i
                in utils.parse_time_interval(source['playing_time'])
            )
        
        return prepared 
Example 12
Project: voca   Author: python-voca   File: test_caster_adapter.py    GNU General Public License v3.0 6 votes vote down vote up
def test_patch_caster():

    namespace = types.SimpleNamespace(python=types.SimpleNamespace(x=1))

    mapping = {
        "castervoice.lib.utilities": {},
        "castervoice.lib.ccr": {},
        "castervoice.lib.ccr.python": {"python": namespace},
        "castervoice.lib.ccr.python.python": {
            "PythonNon": types.SimpleNamespace(mapping={"with": 1})
        },
    }
    finder = patching.make_finder(mapping)

    with patching.finder_patch(finder):
        # import castervoice.lib.ccr
        import castervoice.lib.ccr.python
        import castervoice.lib.ccr.python.python

        assert castervoice.lib.ccr.python.python.PythonNon.mapping["with"] == 1 
Example 13
Project: Python.Challenges   Author: elmar-hinz   File: challenge.py    MIT License 6 votes vote down vote up
def __init__(self):
        self.lines = []
        """A list of lines that will be filled by the method read()."""

        self.model = types.SimpleNamespace()
        """The imported data model.

        A flexible namespace object to take up any kind of data. In simple
        cases this may be completely overwritten, i.e by a list or dict.
        """
        self.result = types.SimpleNamespace()
        """The resulting data model.

        A flexible namespace object to take up any kind of data. In simple
        cases this may be completely overwritten, i.e by a list or dict.
        """

        self.output = ''
        """The output string.

        The string representation of the resulting model as expected by the
        grader.
        """ 
Example 14
Project: Python.Challenges   Author: elmar-hinz   File: test_challenge.py    MIT License 6 votes vote down vote up
def test_lines_to_edges(self):
        """Show lines_to_edges() works as expected."""
        self.challenge.lines = ['1->2', '2->3', '3->4']
        expect = [namespace(head=2, tail=1),
                  namespace(head=3, tail=2),
                  namespace(head=4, tail=3)]
        self.assertEqual(expect, self.challenge.lines_to_edges())
        expect = [namespace(head=3, tail=2)]
        self.assertEqual(expect, self.challenge.lines_to_edges(1,2))
        self.challenge.lines = ['1->2:22']
        expect = [namespace(head=2, tail=1, weight=22)]
        self.assertEqual(expect, self.challenge.lines_to_edges())
        self.challenge.lines = ['1->2, 3', '2->3']
        expect = [namespace(head='2', tail=1),
                  namespace(head='3', tail=1),
                  namespace(head=3, tail=2)]
        self.assertEqual(expect, self.challenge.lines_to_edges()) 
Example 15
Project: torf   Author: rndusr   File: conftest.py    GNU General Public License v3.0 6 votes vote down vote up
def singlefile_content(tmpdir_factory):
    random.seed(0)  # Make sure random file names and content are identical every time
    content_path = _mktempdir(tmpdir_factory)
    filepath = _generate_random_file(content_path, filename='sinģle fíle')
    random.seed()  # Re-enable randomness

    exp_pieces = b'\xc8\xfa\x0fV\x95\xecl\x97t\xb2v\x84S\x98{\x92[ \x13\xe5\x04\xef-\xb0;sF\xc2\x93W\xcf\xc6X\x14\x9b]_r\xfb\x80\'}\xe5\xc4\x05\xdct\xb5^\xe9\x7f0b|\xc9\xf1\x9d\xd7G\x06 ,l8m\x01\xbf2\xf6:\x03r-\x8d\x1f,\x8bk:\xad\xdbN\xa2V\x96/\[email protected]\xa5\x98\xf8\t3fU\x13;\x90\xc0F\xe3[\x15\xea\x8f\x92\xcdN:\xc1\x0fG\x9b\xeb\xd9\x93A\xca\xa7L\xd2\x9ef|\xddd\xd4\x94.f\xee\xea3\xa8\x04|\xe9h\xa7\xa1t\xa2\xb5\xb3*\x89\xf7\x14\xdf\x16M/\xc6\xa5\x85\xdaF\xca\xa7?\x9d\xe1zd\xc8\xe1\x1d\x1epC\x06+\xe1Q\x0fi\x9fv\x19\xa2(\xd0\x90\xb3\xb0\xcf\xa9\x1cy\xf0\x96\x17\n\x05\xa5*IZJ\x8c\xbb\x87\xdd\xed|d.\xf0\xb9\xfe\x00\xa6\nufY\x18\xe35\xee\xdf\xa6D\xed<\xc5W\x0fa\x80\xc6}\xdd\xf4\xbd\xc1:\xe3\xda\nj\xbag\x93\xd0\xdc\xbd\xb8\xfb\xc2\x99\x9a/&\x1d\xf3\xe9\xa3,\x9b>\'\xa5\xaa~\xabb\x81\x88\x80^\xddd\xc7\xea\x83n\x05%\x8f4\x8a\x82\xe2\xff[\xab\xa8\x92\x1f\xaarG\xc5\x00\xcae\x9e\x93\xc4\x9015\x02\xe7\x8a\xb1I\xa6\x16DF\x8a\x0b\xeb\[email protected]\th?WL\xe0Vf\xc9X>##?t\x08\xdf[\xac\x16\x7f\xe9\x1a\xc4\x11\x0c\xc9\xac?\xded\xed\xf5\x1b\xd0Qq\x90_\x88]\xbf\xb7\xbc\xf5\x8et4f<\x14\xb6\x98\xbb\xdd0H\x14\xfaZ\xc1\x07l3\xd6""l\[email protected]\xb7\x9c\xbc/h\xe9\xc0\x83\x0e\xfb\x91\x83\xdf\x1d+\xf6\xd1_\xb8\x04\xdd\xb8\x05\'\x1c\x1b\x94\x1cl\x9a_[An:\xcdw\xe8\xfb\xbf\xb9\x82olQ6<U\r\x9e0/\x89\xc6\xe4\x9cl<\xd5\xf9\xca\x96\x01\xd5\xc3\x1dk\x1b1\xc2X\xe9\x164\x9d\x05\x19\x85c\x0e\x847b\xdb[\xa8\x8e\xc1\x04,\x1c\xc2\x0e\x85`+3\xb1\xe6\xac&F\xb9\xf6\x0e\\\x1fS\xbd\xed\xc6l\x89\x18\x8eI?\x9aqR1&k\x14ce i\xb4;C\xfe\x1dh\xe4\xd3>\xa4\x15\x9f\xd2c#\x1b\x9a\xb6\x84\[email protected]\x89\xdd\x01\x18H\xbce\rK1aS\xd8\xb8\xffD\x9f\x89\xd4\xb59y7\xff\x8b\xc1\xc3\t\xdd\x9e\xa6\xa7\x02:\xa5\xea<\xb9\x95\xd7ePU~\xbc\x16\x9a\x0f\xb1h\xad4\xfa\x18yv\x95\x96\x0cRo\x88\xe6L\x08\xfd\x94gh\x92\'w\xb3\xd1BCqC\x12_\x1f\x92\xfc\xc6\xfd\t\xcd\xab\xe0\xbd\xcc\x06\xf9\xa7\xb1e\xa9\xbe\x0c\x8d\xfcI\x00\x0e\xd7\xbe\x0c&\xf2\xc5\xa5Yl\xf8\xc0\x8e.\x97\x0c\xd5zp~8\xc0g\xa6C\x16\xd0v\x1e\xa1\xa37\xceM[\xd6\x18\xc6\xa5\xc9\xbc\x11\x99\xc4\xe9\x0f9\xab\x98\x01\xaf\xe22\n_\x83\x9b\xdegG\xb4#\xd6\x17\xf1z4\x11v\xef\xcf!\x03\xdc\x14_\x9e;\'\xdckvHh\xd5x\xf48\xdaFa\xae\x02\xf0\x16| \xa3\x97\xe5\xed\xf6\x11$\xe4\xacb\xaf\x8a\x07fH\x96\x00\x00\x98\x87(\x97\xcd!\xff\xf8a\x02\xc4\xca\xff\xef\xe1P\x01_\x9b\x9b\x83:\x7f\xdd\x92\xfb\xe9\x94\xc3SEWh\x18\xb3\x9c\xd8\xf9M\x1d!\xd25\xcb'

    exp_metainfo = {'announce'      : 'http://localhost:123',
                    'created by'    : 'mktorrent 1.0',
                    'creation date' : 1513522263,
                    'info': {'name'         : os.path.basename(filepath),
                             'piece length' : 2**14,
                             'pieces'       : exp_pieces,
                             'length'       : os.path.getsize(filepath)}}

    exp_attrs = SimpleNamespace(path=str(filepath),
                                infohash='7febf5a5a6e6bac79df2eb4340a63009109fecd5',
                                infohash_base32=b'P7V7LJNG425MPHPS5NBUBJRQBEIJ73GV',
                                size=os.path.getsize(filepath),
                                pieces=math.ceil(os.path.getsize(filepath) / exp_metainfo['info']['piece length']))

    return SimpleNamespace(path=exp_attrs.path,
                           exp_metainfo=exp_metainfo,
                           exp_attrs=exp_attrs) 
Example 16
Project: calm   Author: cygwin   File: test_calm.py    MIT License 6 votes vote down vote up
def test_package_set(self):
        self.maxDiff = None

        args = types.SimpleNamespace()
        setattr(args, 'arch', 'x86')
        setattr(args, 'dryrun', False)
        setattr(args, 'force', True)
        setattr(args, 'inifile', 'testdata/inifile/setup.ini')
        setattr(args, 'pkglist', 'testdata/pkglist/cygwin-pkg-maint')
        setattr(args, 'rel_area', 'testdata/relarea')
        setattr(args, 'release', 'testing')
        setattr(args, 'setup_version', '4.321')

        packages = package.read_packages(args.rel_area, args.arch)
        package.delete(packages, 'x86/release/nonexistent', 'nosuchfile-1.0.0.tar.xz')
        self.assertEqual(package.validate_packages(args, packages), True)
        package.write_setup_ini(args, packages, args.arch)
        with open(args.inifile) as inifile:
            results = inifile.read()
            # fix the timestamp to match expected
            results = re.sub('setup-timestamp: .*', 'setup-timestamp: 1458221800', results, 1)
            results = re.sub('generated at .*', 'generated at 2016-03-17 13:36:40 GMT', results, 1)
            compare_with_expected_file(self, 'testdata/inifile', (results,), 'setup.ini')

        # XXX: delete a needed package, and check validate fails 
Example 17
Project: geo-br   Author: uol   File: test_sapp.py    GNU General Public License v3.0 6 votes vote down vote up
def test_cities(self):
        print ("running test_cities...")
        with gzip.open('data.json.gz', 'rb') as db:
            cities = json.load(db)
        
        states = set()
        errors, count = 0, 0
        for city in cities:
            c = SimpleNamespace(**city)
            states.add(c.uf)
            r = sapp._search(c.latitude, c.longitude)
            if r is None:
                errors += 1
            else:
                if r["found"]:
                    if c.nome_municipio == r["city"] and c.uf == r["state"]:
                        count += 1
                    else:
                        errors += 1
                else:
                    errors += 1
        
        self.assertTrue(errors==0)
        self.assertTrue(count==5540)
        self.assertTrue(len(states)==27) 
Example 18
Project: geo-br   Author: uol   File: test_sapp.py    GNU General Public License v3.0 6 votes vote down vote up
def test_capitals(self):
        print ("running test_capitals...")
        with gzip.open('capitais.json.gz', 'rb') as db:
            all_capitals = json.load(db)

        with gzip.open('data.json.gz', 'rb') as db:
            cities = json.load(db)
        
        cities = [x for x in cities if x['capital']]

        found = []
        for capital in all_capitals:
            c = SimpleNamespace(**capital)
            for city in cities:
                d = SimpleNamespace(**city)
                if({d.nome_municipio, d.uf, d.estado} & {c.capital, c.sigla, c.estado}):
                    found.append(capital)
                    break

        self.assertTrue(len(found)==27) 
Example 19
Project: unhuman-resources   Author: agajdosi   File: tracing.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(
        self,
        trace_config_ctx_factory: Type[SimpleNamespace]=SimpleNamespace
    ) -> None:
        self._on_request_start = Signal(self)  # type: _Signal
        self._on_request_chunk_sent = Signal(self)  # type: _Signal
        self._on_response_chunk_received = Signal(self)  # type: _Signal
        self._on_request_end = Signal(self)  # type: _Signal
        self._on_request_exception = Signal(self)  # type: _Signal
        self._on_request_redirect = Signal(self)  # type: _Signal
        self._on_connection_queued_start = Signal(self)  # type: _Signal
        self._on_connection_queued_end = Signal(self)  # type: _Signal
        self._on_connection_create_start = Signal(self)  # type: _Signal
        self._on_connection_create_end = Signal(self)  # type: _Signal
        self._on_connection_reuseconn = Signal(self)  # type: _Signal
        self._on_dns_resolvehost_start = Signal(self)  # type: _Signal
        self._on_dns_resolvehost_end = Signal(self)  # type: _Signal
        self._on_dns_cache_hit = Signal(self)  # type: _Signal
        self._on_dns_cache_miss = Signal(self)  # type: _Signal

        self._trace_config_ctx_factory = trace_config_ctx_factory  # type: Type[SimpleNamespace] # noqa 
Example 20
Project: unhuman-resources   Author: agajdosi   File: tracing.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(
        self,
        trace_config_ctx_factory: Type[SimpleNamespace]=SimpleNamespace
    ) -> None:
        self._on_request_start = Signal(self)  # type: _Signal
        self._on_request_chunk_sent = Signal(self)  # type: _Signal
        self._on_response_chunk_received = Signal(self)  # type: _Signal
        self._on_request_end = Signal(self)  # type: _Signal
        self._on_request_exception = Signal(self)  # type: _Signal
        self._on_request_redirect = Signal(self)  # type: _Signal
        self._on_connection_queued_start = Signal(self)  # type: _Signal
        self._on_connection_queued_end = Signal(self)  # type: _Signal
        self._on_connection_create_start = Signal(self)  # type: _Signal
        self._on_connection_create_end = Signal(self)  # type: _Signal
        self._on_connection_reuseconn = Signal(self)  # type: _Signal
        self._on_dns_resolvehost_start = Signal(self)  # type: _Signal
        self._on_dns_resolvehost_end = Signal(self)  # type: _Signal
        self._on_dns_cache_hit = Signal(self)  # type: _Signal
        self._on_dns_cache_miss = Signal(self)  # type: _Signal

        self._trace_config_ctx_factory = trace_config_ctx_factory  # type: Type[SimpleNamespace] # noqa 
Example 21
Project: serious-django-graphene   Author: serioeseGmbH   File: test_failable_mutation.py    MIT License 5 votes vote down vote up
def test_default_mutate_fails_without_perform_mutate(self):
        class MyFailableMutation(FailableMutation):
            some_result = graphene.Int()

        mut = MyFailableMutation()
        self.assertRaises(NotImplementedError, lambda *_: mut.mutate(SimpleNamespace())) 
Example 22
Project: serious-django-graphene   Author: serioeseGmbH   File: test_failable_mutation.py    MIT License 5 votes vote down vote up
def test_declared_exceptions_are_caught_others_are_not(self):
        class SomeException(BaseException):
            pass

        class MyFailableMutation(FailableMutation):
            some_result = graphene.Int()

            class Meta:
                caught_exceptions = [SomeException]

            @classmethod
            def perform_mutate(cls, info, value=None, *args, **kwargs):
                if value is None:
                    raise SomeException("oh no!")
                elif value is 69:
                    raise ValueError("nice")
                return cls(some_result=value)

        # Do not raise when expected exception occurs, but expect result.error to be present
        mut, raised = MyFailableMutation(), False
        try:
            result = mut.mutate(SimpleNamespace())
        except:
            raised = True
        self.assertFalse(raised)
        self.assertIsInstance(result.error, ExecutionError)

        # Do not raise when no exception occurs, and expect result.error to not be present
        mut, raised = MyFailableMutation(), False
        try:
            result = mut.mutate(SimpleNamespace(), value=100)
        except:
            raised = True
        self.assertFalse(raised)
        self.assertIsNone(result.error)

        # Raise when unexpected exception occurs
        mut = MyFailableMutation()
        self.assertRaises(ValueError, lambda *_: mut.mutate(SimpleNamespace(), value=69)) 
Example 23
Project: venvtools   Author: HeavenVolkoff   File: extended_env_builder.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def ensure_directories(self, env_dir: str) -> SimpleNamespace:
        context: SimpleNamespace = super().ensure_directories(env_dir)
        # disable default prompt format
        context.prompt = self.prompt

        return context 
Example 24
Project: pywren-ibm-cloud   Author: pywren   File: invoker.py    Apache License 2.0 5 votes vote down vote up
def run(self, job_description):
        """
        Run a job described in job_description
        """
        job = SimpleNamespace(**job_description)

        log_msg = ('ExecutorID {} | JobID {} - Starting function invocation: {}()  - Total: {} '
                   'activations'.format(job.executor_id, job.job_id, job.func_name, job.total_calls))
        logger.info(log_msg)

        self.total_calls = job.total_calls

        for i in range(self.workers):
            self.token_bucket_q.put('#')

        for i in range(job.total_calls):
            call_id = "{:05d}".format(i)
            self.pending_calls_q.put((job, call_id))
        self._start_job_status_checker(job)

        invokers = []
        for i in range(4):
            p = Process(target=self.run_process, args=())
            invokers.append(p)
            p.daemon = True
            p.start()

        for p in invokers:
            p.join() 
Example 25
Project: DeepQMC   Author: NLESC-JCER   File: solver_base.py    Apache License 2.0 5 votes vote down vote up
def resampling(self, ntherm=-1, resample=100, resample_from_last=True,
                   resample_every=1):
        '''Configure the resampling options.'''
        self.resample = SimpleNamespace()
        self.resample.ntherm = ntherm
        self.resample.resample = resample
        self.resample.resample_from_last = resample_from_last
        self.resample.resample_every = resample_every 
Example 26
Project: glin   Author: zaturox   File: app.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, led_count, hw_backend, port=6606):
        self.ctx = zmq.Context()
        self.led_count = led_count
        self.port = port

        self.loop = IOLoop.instance()
        self.caller = PeriodicCallback(self._on_next_frame, 1000/30)
        self.hw_communication = hw_backend
        self.hw_communication.connect()
        self.zmq_collector = GlinAppZmqCollector(self, self.ctx)
        self.zmq_publisher = GlinAppZmqPublisher(self, self.ctx)

        # server side configuration
        self.config = SimpleNamespace()
        self.config.max_fps = 60

        # current state (somehow client side configuration)
        self.state = SimpleNamespace()
        self.state.animationClasses = []
        self.state.activeSceneId = None
        self.state.activeAnimation = None
        self.state.scenes = {}
        self.state.brightness = 1.0
        self.state.sceneIdCtr = 0
        self.state.mainswitch = True
        self.state.target_fps = 0
        self.state.lastFrameSent = None 
Example 27
Project: glin   Author: zaturox   File: messages.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, frames):
        self.frames = frames
        self.results = types.SimpleNamespace() 
Example 28
Project: NiujiaoDebugger   Author: MrSrc   File: test_discovery.py    GNU General Public License v3.0 5 votes vote down vote up
def test_discovery_from_dotted_namespace_packages(self):
        loader = unittest.TestLoader()

        package = types.ModuleType('package')
        package.__path__ = ['/a', '/b']
        package.__spec__ = types.SimpleNamespace(
           loader=None,
           submodule_search_locations=['/a', '/b']
        )

        def _import(packagename, *args, **kwargs):
            sys.modules[packagename] = package
            return package

        _find_tests_args = []
        def _find_tests(start_dir, pattern, namespace=None):
            _find_tests_args.append((start_dir, pattern))
            return ['%s/tests' % start_dir]

        loader._find_tests = _find_tests
        loader.suiteClass = list

        with unittest.mock.patch('builtins.__import__', _import):
            # Since loader.discover() can modify sys.path, restore it when done.
            with support.DirsOnSysPath():
                # Make sure to remove 'package' from sys.modules when done.
                with test.test_importlib.util.uncache('package'):
                    suite = loader.discover('package')

        self.assertEqual(suite, ['/a/tests', '/b/tests']) 
Example 29
Project: NiujiaoDebugger   Author: MrSrc   File: test_types.py    GNU General Public License v3.0 5 votes vote down vote up
def test_unbound(self):
        ns1 = vars(types.SimpleNamespace())
        ns2 = vars(types.SimpleNamespace(x=1, y=2))

        self.assertEqual(ns1, {})
        self.assertEqual(ns2, {'y': 2, 'x': 1}) 
Example 30
Project: NiujiaoDebugger   Author: MrSrc   File: test_types.py    GNU General Public License v3.0 5 votes vote down vote up
def test_attrget(self):
        ns = types.SimpleNamespace(x=1, y=2, w=3)

        self.assertEqual(ns.x, 1)
        self.assertEqual(ns.y, 2)
        self.assertEqual(ns.w, 3)
        with self.assertRaises(AttributeError):
            ns.z 
Example 31
Project: NiujiaoDebugger   Author: MrSrc   File: test_types.py    GNU General Public License v3.0 5 votes vote down vote up
def test_attrset(self):
        ns1 = types.SimpleNamespace()
        ns2 = types.SimpleNamespace(x=1, y=2, w=3)
        ns1.a = 'spam'
        ns1.b = 'ham'
        ns2.z = 4
        ns2.theta = None

        self.assertEqual(ns1.__dict__, dict(a='spam', b='ham'))
        self.assertEqual(ns2.__dict__, dict(x=1, y=2, w=3, z=4, theta=None)) 
Example 32
Project: NiujiaoDebugger   Author: MrSrc   File: test_types.py    GNU General Public License v3.0 5 votes vote down vote up
def test_repr(self):
        ns1 = types.SimpleNamespace(x=1, y=2, w=3)
        ns2 = types.SimpleNamespace()
        ns2.x = "spam"
        ns2._y = 5
        name = "namespace"

        self.assertEqual(repr(ns1), "{name}(w=3, x=1, y=2)".format(name=name))
        self.assertEqual(repr(ns2), "{name}(_y=5, x='spam')".format(name=name)) 
Example 33
Project: NiujiaoDebugger   Author: MrSrc   File: test_types.py    GNU General Public License v3.0 5 votes vote down vote up
def test_equal(self):
        ns1 = types.SimpleNamespace(x=1)
        ns2 = types.SimpleNamespace()
        ns2.x = 1

        self.assertEqual(types.SimpleNamespace(), types.SimpleNamespace())
        self.assertEqual(ns1, ns2)
        self.assertNotEqual(ns2, types.SimpleNamespace()) 
Example 34
Project: NiujiaoDebugger   Author: MrSrc   File: test_types.py    GNU General Public License v3.0 5 votes vote down vote up
def test_recursive(self):
        ns1 = types.SimpleNamespace(c='cookie')
        ns2 = types.SimpleNamespace()
        ns3 = types.SimpleNamespace(x=1)
        ns1.spam = ns1
        ns2.spam = ns3
        ns3.spam = ns2

        self.assertEqual(ns1.spam, ns1)
        self.assertEqual(ns1.spam.spam, ns1)
        self.assertEqual(ns1.spam.spam, ns1.spam)
        self.assertEqual(ns2.spam, ns3)
        self.assertEqual(ns3.spam, ns2)
        self.assertEqual(ns2.spam.spam, ns2) 
Example 35
Project: NiujiaoDebugger   Author: MrSrc   File: test_types.py    GNU General Public License v3.0 5 votes vote down vote up
def test_recursive_repr(self):
        ns1 = types.SimpleNamespace(c='cookie')
        ns2 = types.SimpleNamespace()
        ns3 = types.SimpleNamespace(x=1)
        ns1.spam = ns1
        ns2.spam = ns3
        ns3.spam = ns2
        name = "namespace"
        repr1 = "{name}(c='cookie', spam={name}(...))".format(name=name)
        repr2 = "{name}(spam={name}(spam={name}(...), x=1))".format(name=name)

        self.assertEqual(repr(ns1), repr1)
        self.assertEqual(repr(ns2), repr2) 
Example 36
Project: NiujiaoDebugger   Author: MrSrc   File: test_types.py    GNU General Public License v3.0 5 votes vote down vote up
def test_as_dict(self):
        ns = types.SimpleNamespace(spam='spamspamspam')

        with self.assertRaises(TypeError):
            len(ns)
        with self.assertRaises(TypeError):
            iter(ns)
        with self.assertRaises(TypeError):
            'spam' in ns
        with self.assertRaises(TypeError):
            ns['spam'] 
Example 37
Project: NiujiaoDebugger   Author: MrSrc   File: test_types.py    GNU General Public License v3.0 5 votes vote down vote up
def test_subclass(self):
        class Spam(types.SimpleNamespace):
            pass

        spam = Spam(ham=8, eggs=9)

        self.assertIs(type(spam), Spam)
        self.assertEqual(vars(spam), {'ham': 8, 'eggs': 9}) 
Example 38
Project: NiujiaoDebugger   Author: MrSrc   File: test_types.py    GNU General Public License v3.0 5 votes vote down vote up
def test_pickle(self):
        ns = types.SimpleNamespace(breakfast="spam", lunch="spam")

        for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
            pname = "protocol {}".format(protocol)
            try:
                ns_pickled = pickle.dumps(ns, protocol)
            except TypeError as e:
                raise TypeError(pname) from e
            ns_roundtrip = pickle.loads(ns_pickled)

            self.assertEqual(ns, ns_roundtrip, pname) 
Example 39
Project: termpixels   Author: loganzartman   File: buffer_test.py    MIT License 5 votes vote down vote up
def test_blit_blittable():
    blittable = SimpleNamespace()
    blittable.blit_to = Mock()
    blittable.w = 1
    blittable.h = 1
    buffer = Buffer(1, 1)
    buffer.blit(blittable)
    assert blittable.blit_to.called 
Example 40
Project: lando-api   Author: mozilla-conduit   File: conftest.py    Mozilla Public License 2.0 5 votes vote down vote up
def auth0_mock(jwks, monkeypatch):
    mock_auth0 = MockAuth0()
    mock_userinfo_response = SimpleNamespace(
        status_code=200, json=lambda: mock_auth0.userinfo
    )
    monkeypatch.setattr(
        "landoapi.auth.fetch_auth0_userinfo", lambda token: mock_userinfo_response
    )
    return mock_auth0 
Example 41
Project: cimon_controller   Author: SchweizerischeBundesbahnen   File: test_apiserveroutput.py    Apache License 2.0 5 votes vote down vote up
def setUp(self):
        apiserveroutput.server = SimpleNamespace() # pretend there is an http server to avioid starting one
        set_shared_status({}) 
Example 42
Project: cimon_controller   Author: SchweizerischeBundesbahnen   File: test_energenieoutput.py    Apache License 2.0 5 votes vote down vote up
def create_ampel(self, colors=None):
        a = EnergenieBuildAmpel(colors=colors) if colors else EnergenieBuildAmpel()
        a.energenie = SimpleNamespace()
        a.energenie.switch = MagicMock(spec=(""))
        return a 
Example 43
Project: cimon_controller   Author: SchweizerischeBundesbahnen   File: test_cimon.py    Apache License 2.0 5 votes vote down vote up
def test_stop_calls_close(self):
        c = Cimon(outputs = (self.__mock_output__(close_method=True), self.__mock_output__(), self.__mock_output__(close_method=True)))
        c.rescheduler = SimpleNamespace()
        c.rescheduler.stop = MagicMock(spec=(""))
        c.stop()
        c.outputs[0].close.assert_called_once_with()
        c.outputs[2].close.assert_called_once_with() 
Example 44
Project: cimon_controller   Author: SchweizerischeBundesbahnen   File: test_cimon.py    Apache License 2.0 5 votes vote down vote up
def __mock_collector__(self, type, status):
        collector = SimpleNamespace()
        collector.type = type
        collector.collect = MagicMock(spec=(""), return_value = status)
        return collector 
Example 45
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: backend_pdf.py    MIT License 5 votes vote down vote up
def dviFontName(self, dvifont):
        """
        Given a dvi font object, return a name suitable for Op.selectfont.
        This registers the font information in self.dviFontInfo if not yet
        registered.
        """

        dvi_info = self.dviFontInfo.get(dvifont.texname)
        if dvi_info is not None:
            return dvi_info.pdfname

        tex_font_map = dviread.PsfontsMap(dviread.find_tex_file('pdftex.map'))
        psfont = tex_font_map[dvifont.texname]
        if psfont.filename is None:
            raise ValueError(
                "No usable font file found for {} (TeX: {}); "
                "the font may lack a Type-1 version"
                .format(psfont.psname, dvifont.texname))

        pdfname = Name('F%d' % self.nextFont)
        self.nextFont += 1
        _log.debug('Assigning font %s = %s (dvi)', pdfname, dvifont.texname)
        self.dviFontInfo[dvifont.texname] = types.SimpleNamespace(
            dvifont=dvifont,
            pdfname=pdfname,
            fontfile=psfont.filename,
            basefont=psfont.psname,
            encodingfile=psfont.encoding,
            effects=psfont.effects)
        return pdfname 
Example 46
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: mathtext.py    MIT License 5 votes vote down vote up
def get_results(self, box, used_characters):
        ship(0, 0, box)
        svg_elements = types.SimpleNamespace(svg_glyphs=self.svg_glyphs,
                                             svg_rects=self.svg_rects)
        return (self.width,
                self.height + self.depth,
                self.depth,
                svg_elements,
                used_characters) 
Example 47
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: mathtext.py    MIT License 5 votes vote down vote up
def _get_info(self, fontname, font_class, sym, fontsize, dpi, math=True):
        key = fontname, font_class, sym, fontsize, dpi
        bunch = self.glyphd.get(key)
        if bunch is not None:
            return bunch

        font, num, symbol_name, fontsize, slanted = \
            self._get_glyph(fontname, font_class, sym, fontsize, math)

        font.set_size(fontsize, dpi)
        glyph = font.load_char(
            num,
            flags=self.mathtext_backend.get_hinting_type())

        xmin, ymin, xmax, ymax = [val/64.0 for val in glyph.bbox]
        offset = self._get_offset(font, glyph, fontsize, dpi)
        metrics = types.SimpleNamespace(
            advance = glyph.linearHoriAdvance/65536.0,
            height  = glyph.height/64.0,
            width   = glyph.width/64.0,
            xmin    = xmin,
            xmax    = xmax,
            ymin    = ymin+offset,
            ymax    = ymax+offset,
            # iceberg is the equivalent of TeX's "height"
            iceberg = glyph.horiBearingY/64.0 + offset,
            slanted = slanted
            )

        result = self.glyphd[key] = types.SimpleNamespace(
            font            = font,
            fontsize        = fontsize,
            postscript_name = font.postscript_name,
            metrics         = metrics,
            symbol_name     = symbol_name,
            num             = num,
            glyph           = glyph,
            offset          = offset
            )
        return result 
Example 48
Project: schemathesis   Author: kiwicom   File: test_callbacks.py    MIT License 5 votes vote down vote up
def test_validate_schema(value):
    with pytest.raises(click.UsageError):
        callbacks.validate_schema(SimpleNamespace(params={}), None, value) 
Example 49
Project: schemathesis   Author: kiwicom   File: test_callbacks.py    MIT License 5 votes vote down vote up
def test_validate_schema_path_without_base_url():
    with pytest.raises(click.UsageError):
        callbacks.validate_schema(SimpleNamespace(params={}), None, SIMPLE_PATH) 
Example 50
Project: toxn   Author: gaborbernat   File: base.py    MIT License 5 votes vote down vote up
def __init__(self,
                 _options: argparse.Namespace,
                 config_dict: ConfDict,
                 project_work_dir: Path,
                 name: str,
                 task: SimpleNamespace) -> None:
        self._project_work_dir = project_work_dir
        self._work_dir = project_work_dir / name
        self._name = name
        # generated by running
        self.venv: Optional[VEnv] = None  # virtualenv generation
        self._task = task

        super().__init__(_options, config_dict)