예제 #1
0
def test_add(init):
    cf = CalculatorComplex(init[0])
    assert (cf + init[1]) == CalculatorComplex(init[2])
    cf += init[1]
    assert cf == CalculatorComplex(init[2])
    cf = CalculatorComplex(init[1])
    assert (init[0] + cf) == CalculatorComplex(init[2])
예제 #2
0
def test_mult(init):
    cf = CalculatorComplex(init[0])
    assert (cf * init[1]) == CalculatorComplex(init[2])
    cf *= init[1]
    assert cf == CalculatorComplex(init[2])
    cf = CalculatorComplex(init[1])
    assert (init[0] * cf) == CalculatorComplex(init[2])
예제 #3
0
def test_str_init():
    cf = CalculatorComplex("start_value")
    assert cf.real.value == "start_value"
    assert cf.imag.value == 0
    cf2 = CalculatorComplex(cf)
    assert cf.real.value == "start_value"
    assert cf.imag.value == 0
예제 #4
0
def test_sub(init):
    cf = CalculatorComplex(init[0])
    assert (cf - init[1]) == CalculatorComplex(init[2])
    cf -= init[1]
    assert cf == CalculatorComplex(init[2])
    cf = CalculatorComplex(init[1])
    assert (init[0] - cf) == CalculatorComplex(init[2])
예제 #5
0
def test_div(init):
    cf = CalculatorComplex(init[0])
    assert (cf / init[1]) == CalculatorComplex(init[2])
    cf /= init[1]
    assert cf == CalculatorComplex(init[2])
    cf = CalculatorComplex(init[1])
    assert (init[0] / cf) == CalculatorComplex(init[2])
예제 #6
0
def test_init(start_value):
    cf = CalculatorComplex(start_value)
    assert cf.real.value == np.real(start_value)
    assert cf.imag.value == np.imag(start_value)
    cf2 = CalculatorComplex(cf)
    assert cf2.real.value == np.real(start_value)
    assert cf2.imag.value == np.imag(start_value)
예제 #7
0
def test_div_fail(init):
    cf = CalculatorComplex(init[0])
    with pytest.raises(ZeroDivisionError):
        (cf / init[1])
    with pytest.raises(ZeroDivisionError):
        cf /= init[1]
    with pytest.raises(ZeroDivisionError):
        cf = CalculatorComplex(init[1])
        (init[0] / cf)
예제 #8
0
    def __init__(
        self, key1=CalculatorFloat(1), key2=CalculatorComplex(1j)) -> None:
        """Initialize no_propagation_class_aware class

        Args:
            key1: documentation for key1
            key2: documentation for key2
        """
        self.key1 = CalculatorFloat(key1)
        self.key2 = CalculatorComplex(key2)
예제 #9
0
class simple_class_aware(object):

    _qonfig_defaults_dict = {
        'key1': {
            'doc': 'documentation for key1',
            'default': CalculatorFloat(1)
        },
        'key2': {
            'doc': 'documentation for key2',
            'default': CalculatorComplex(1j)
        },
    }

    def __init__(
        self, key1=CalculatorFloat(1), key2=CalculatorComplex(1j)) -> None:
        """Initialize simple_class_aware class

        Args:
            key1: documentation for key1
            key2: documentation for key2
        """
        self.key1 = CalculatorFloat(key1)
        self.key2 = CalculatorComplex(key2)

    @classmethod
    def from_qonfig(
            cls, config: Qonfig['simple_class_aware']) -> 'simple_class_aware':
        return cls(key1=config['key1'], key2=config['key2'])

    def to_qonfig(self) -> 'Qonfig[simple_class_aware]':
        config: Qonfig['simple_class_aware'] = Qonfig(self.__class__)
        config['key1'] = self.key1
        config['key2'] = self.key2
        return config
예제 #10
0
def complex_isclose(
    val: IntoCalculatorComplex,
    comparison: IntoCalculatorComplex,
) -> bool:
    """Complex is_close comparison of CalculatorComplexs handling real and imaginary parts.

    Args:
        val: complex value
        comparison: value that is compared to


    Returns:
        bool

    """
    value = CalculatorComplex(val)
    return value.isclose(comparison)
예제 #11
0
def test_simple_to_dict():
    config = Qonfig(simple_class_aware)
    simple_dict = {
        'qonfig_name': 'test_qonfig.simple_class_aware',
        'key1': CalculatorFloat(1),
        'key2': CalculatorComplex(1j)
    }
    assert simple_dict == config.to_dict()
예제 #12
0
def test_simple_aware_init():
    config = Qonfig(simple_class_aware)
    assert config['name'] == 'test_qonfig.simple_class_aware'
    assert config.qonfig_name == 'test_qonfig.simple_class_aware'
    assert config['key1'] == 1
    assert config['key2'] == 1j
    instance = config.to_instance()
    assert instance.key1 == 1
    assert instance.key2 == 1j
    instance.key1 = 2
    instance.key2 = CalculatorComplex(2j)
    config2 = instance.to_qonfig()
    assert config2['name'] == 'test_qonfig.simple_class_aware'
    assert config2.qonfig_name == 'test_qonfig.simple_class_aware'
    assert config2['key1'] == 2
    assert config2['key2'] == 2j
예제 #13
0
def test_aware_init():
    config = Qonfig(class_aware)
    assert config['name'] == 'test_qonfig.class_aware'
    assert not config.is_valid
    assert not config.is_complete
    assert not config.meets_requirements
    assert config.violated_requirements == {
        'super_key1': "It is required that super_key1['key1'] is 3 "
    }
    config['key2'] = CalculatorComplex(10j)
    assert not config.is_valid
    assert config.is_complete
    assert config['super_key1']['key2'] == 10j
    # test propagation
    config['key1'] = 3
    assert config['super_key1']['key1'] == 3
    assert config.is_valid
예제 #14
0
def test_complex_arg(initial):
    arg = CalculatorComplex.from_pair(*initial[0]).arg()
    assert arg.isclose(initial[1])
예제 #15
0
def test_complex_isclose(initial):
    t = CalculatorComplex.from_pair(initial[0][0], initial[0][1]).isclose(
        CalculatorComplex.from_pair(initial[1][0], initial[1][1]))
    assert t == initial[2]
예제 #16
0
def test_failed_init():
    with pytest.raises(TypeError):
        cf = CalculatorComplex(dict())
예제 #17
0
def test_complex_conj(initial):
    t = CalculatorComplex.from_pair(*initial[0]).conj()
    assert t == CalculatorComplex.from_pair(*initial[1])
예제 #18
0
def test_from_pair(start_value):
    cf = CalculatorComplex.from_pair(*start_value)
    assert cf.real == CalculatorFloat(start_value[0])
    assert cf.imag == CalculatorFloat(start_value[1])
예제 #19
0
def test_complex_cast_fail():
    cc = CalculatorComplex.from_pair("a", "b")
    with pytest.raises(ValueError):
        assert complex(cc)
예제 #20
0
def test_complex_cast(initial):
    cc = CalculatorComplex(initial[0])
    assert complex(cc) == initial[1]
예제 #21
0
def test_complex_abs(initial):
    aabs = abs(CalculatorComplex.from_pair(*initial[0]))
    assert aabs.isclose(initial[1])
예제 #22
0
    def from_dict(cls, config_dictionary: dict) -> 'Qonfig[T]':
        r"""Load a (partial) Qonfig from a dictionary.

        Args:
            config_dictionary: Dictionary version of the config

        Returns:
            Qonfig[T]

        Raises:
            ImportError: Could not find class. Try importing corresponding module
        """
        # Process qonfig_name to import class of Qonfig and raise error
        # when import fails
        spl = config_dictionary['qonfig_name'].rsplit('.', 1)
        if len(spl) == 1:
            class_type = globals().get(spl[0], None)
            if class_type is None:
                error_msg = (
                    'Could not find class {}. Try importing corresponding module'
                    .format(spl[0]))
                raise ImportError(error_msg)
        elif len(spl) == 2:
            temporary_import = importlib.import_module(spl[0])
            class_type = getattr(temporary_import, spl[1], None)
            if class_type is None:
                error_msg = 'Could not import {}.'.format(spl)
                raise ImportError(error_msg)
        # Create new Qonfig for class
        return_config = cls(class_type)
        # Setting items in dict as items in Qonfig
        for key in [
                key for key in return_config.keys()
                if key in config_dictionary.keys()
        ]:
            # Code path when the value of config_dictionary[key] defines a Qonfig
            if (isinstance(config_dictionary[key], dict)
                    and 'qonfig_name' in config_dictionary[key].keys()):
                try:
                    return_config[key] = Qonfig.from_dict(
                        config_dictionary[key])
                except NotQonfigurableError:
                    return_config[key] = config_dictionary[key]
            elif (isinstance(config_dictionary[key], dict) and
                  config_dictionary[key].get('is_calculator_complex', False)):
                return_config[key] = CalculatorComplex.from_pair(
                    config_dictionary[key]['real'],
                    config_dictionary[key]['imag'])
            # Code path for list recursion if item is a list containing dicts
            # defining a Qonfig, create the Qonfigs in the list
            elif (isinstance(config_dictionary[key], list)
                  and any([(isinstance(d, dict) and
                            ('qonfig_name' in d.keys()))
                           for d in config_dictionary[key]])):
                config_list: List[Any] = list()
                for d in config_dictionary[key]:
                    if isinstance(d, dict) and ('qonfig_name' in d.keys()):
                        try:
                            config_list.append(Qonfig.from_dict(d))
                        except NotQonfigurableError:
                            config_list.append(d)
                    elif isinstance(d, dict) and d.get('is_calculator_complex',
                                                       False):
                        config_list.append(
                            CalculatorComplex.from_pair(d['real'], d['imag']))
                    else:
                        config_list.append(d)
                return_config[key] = config_list
            elif config_dictionary[key] == "<empty 'Empty'>":
                return_config[key] = empty
            else:
                return_config[key] = config_dictionary[key]
        return return_config