Beispiel #1
0
def parse_raml(loaded_raml, config):
    """
    Parse loaded RAML file into RAML/Python objects.

    :param RAMLDict loaded_raml: OrderedDict of loaded RAML file
    :returns: :py:class:`.raml.RootNode` object.
    :raises: :py:class:`.errors.InvalidRAMLError` when RAML file is invalid
    """

    validate = str(_get(config, "validate")).lower() == 'true'

    # Postpone validating the root node until the end; otherwise,
    # we end up with duplicate validation exceptions.
    attr.set_run_validators(False)
    root = create_root(loaded_raml, config)
    attr.set_run_validators(validate)

    root.security_schemes = create_sec_schemes(root.raml_obj, root)
    root.traits = create_traits(root.raml_obj, root)
    root.resource_types = create_resource_types(root.raml_obj, root)
    root.resources = create_resources(root.raml_obj, [], root,
                                      parent=None)

    if validate:
        attr.validate(root)  # need to validate again for root node

        if root.errors:
            raise InvalidRAMLError(root.errors)

    return root
Beispiel #2
0
def build_service(service):
    """Service with mocked session for build testing"""

    attr.set_run_validators(False)
    build_service = attr.evolve(service, session=MockBuilder())
    attr.set_run_validators(True)

    return build_service
Beispiel #3
0
def mutable_repo_service(service, built_package):
    """Service with mocked session for MutableRepo testing"""

    basic_state = MockMutableRepo()
    basic_state.content["build_tag"][built_package.name] = {built_package.nvr}

    attr.set_run_validators(False)
    mock_service = attr.evolve(service, session=basic_state)
    attr.set_run_validators(True)

    return mock_service
Beispiel #4
0
def parse_raml(loaded_raml, config):
    """
    Parse loaded RAML file into RAML/Python objects.

    :param RAMLDict loaded_raml: OrderedDict of loaded RAML file
    :returns: :py:class:`.raml.RootNode` object.
    """
    validate = str(config.get("validate")).lower() == 'true'
    attr.set_run_validators(validate)
    root = create_root(loaded_raml, config)
    root.security_schemes = create_sec_schemes(root.raml_obj, root)
    root.traits = create_traits(root.raml_obj, root)
    root.resource_types = create_resource_types(root.raml_obj, root)
    root.resources = create_resources(root.raml_obj, [], root, parent=None)
    if validate:
        attr.validate(root)  # need to validate again for root node
    return root
Beispiel #5
0
def parse_raml(loaded_raml, config):
    """
    Parse loaded RAML file into RAML/Python objects.

    :param RAMLDict loaded_raml: OrderedDict of loaded RAML file
    :returns: :py:class:`.raml.RootNode` object.
    """
    validate = str(config.get("validate")).lower() == 'true'
    attr.set_run_validators(validate)
    root = create_root(loaded_raml, config)
    root.security_schemes = create_sec_schemes(root.raml_obj, root)
    root.traits = create_traits(root.raml_obj, root)
    root.resource_types = create_resource_types(root.raml_obj, root)
    root.resources = create_resources(root.raml_obj, [], root,
                                      parent=None)
    if validate:
        attr.validate(root)  # need to validate again for root node
    return root
Beispiel #6
0
def run_iterator(config: SimulationConfig,
                 target_time: float) -> Iterator[Tuple[State, Status]]:
    """Initialize and advance a simulation to the target time.

    This method is a convenience method to automate running the
    methods above that will be sufficient for most use cases.  It
    will:
    1. Construct a new state object
    2. Initialize the state object (yielding the result)
    3. Advance the simulation by single time steps (yielding the result)
    4. Finalize the simulation (yielding the result)
    """
    attr.set_run_validators(config.getboolean('simulation', 'validate'))
    state = initialize(State.create(config))
    yield state, Status.initialize

    for state in advance(state, target_time):
        yield state, Status.time_step

    yield finalize(state), Status.finalize
Beispiel #7
0
def run(target_time, config):
    """Run a simulation"""
    config = SimulationConfig(config)
    total = ceil(target_time / config.getfloat('simulation', 'time_step'))

    attr.set_run_validators(config.getboolean('simulation', 'validate'))

    def get_time(x):
        if x is None:
            return '0'
        return '%.2f' % x.time

    state = initialize(State.create(config))
    with click.progressbar(advance(state, target_time),
                           label='Running simulation',
                           length=total,
                           item_show_func=get_time) as bar:
        for state in bar:
            pass

    state.save('simulation-final.pkl')
Beispiel #8
0
    def test_validate_respects_run_validators_config(self):
        """
        If run validators is off, validate doesn't run them.
        """
        @attr.s(on_setattr=setters.validate)
        class C:
            x = attr.ib(validator=attr.validators.instance_of(int))

        c = C(1)

        attr.set_run_validators(False)

        c.x = "1"

        assert "1" == c.x

        attr.set_run_validators(True)

        with pytest.raises(TypeError) as ei:
            c.x = "1"

        assert ei.value.args[0].startswith("'x' must be <")
Beispiel #9
0
    def _apply_strategy(cls, data, strategy=list, key_factory=None):

        def for_each(items):
            return [i for i in items if i in data.key_map]

        def list_builder(fps):
            return [maybe_wrap_key(data.key_map[fp]) for fp in for_each(fps)]

        def dict_builder(fps):
            return {
                fp: maybe_wrap_key(data.key_map[fp]) for fp in for_each(fps)
            }

        def maybe_wrap_key(raw_key):
            return key_factory(**raw_key) if key_factory else raw_key

        build_strategy = {list: list_builder, dict: dict_builder}[strategy]
        fingerprints = cls._get_fingerprints(data)
        attr.set_run_validators(False)

        result = build_strategy(fingerprints)
        attr.set_run_validators(True)
        return result
Beispiel #10
0
@version: 1.0
@ __author__: kute 
@ __file__: test.py
@ __mtime__: 2016/10/21 16:48


1. 以 _ 开头的私有成员 需要声明在 有 default 值的成员之前
2. 类初始化可以使用  位置参数 或者 关键字参数
3. init = False 表示不允许初始化

"""

import attr

# 设置是否在运行时验证
attr.set_run_validators(True)


@attr.s
class PersonList(object):
    persons = attr.ib()
    id = attr.ib()
    num = attr.ib()


def valid_name(instance, attribute, value):
    # instance: 当前实例
    # attribute: 当前的成员名
    # value: 当前成员对应的值
    return True
Beispiel #11
0
 def __enter__(self) -> "NoAttrValidationContext":
     self.original_state = attr.get_run_validators()
     attr.set_run_validators(False)
     return self
Beispiel #12
0
def disable_attr_validation():
    attr.set_run_validators(False)
Beispiel #13
0
 def __exit__(self, *exc) -> None:
     assert self.original_state is not None
     attr.set_run_validators(self.original_state)
Beispiel #14
0
# ### Validate it!
# %%
Point(["1"], "ahoj")  # Fails on converter
Point(32, "ahoj")  # Fails on accepted range

# %% [markdown]
# ### Timeit!
# %%
%timeit p1 = Point("1", "ahoj")
p1 = Point("1", "ahoj")


# %% [markdown]
# ### Timeit without validation
# %%
attr.set_run_validators(False)
%timeit p2 = Point(1, "ahoj")
p2 = Point(1, "ahoj")


# %% [markdown]
# ## Slots
#
# - static amount of memory per instance with all the attributes
# - lower memory consumption
# - faster data access (depends on data type)

# %%
@attr.s(slots=True, auto_attribs=True)
class PointSlots:
    x: float = 0.
Beispiel #15
0
def set_input_validator(flag=False):
    attr.set_run_validators(flag)
Beispiel #16
0
def disable_validators():
    attr.set_run_validators(False)
Beispiel #17
0
def disabled_validators():
    attr.set_run_validators(False)
    yield
    attr.set_run_validators(True)