Example #1
0
def test_slots_being_used():
    """
    The class is really using __slots__.
    """
    non_slot_instance = C1(x=1, y="test")
    slot_instance = C1Slots(x=1, y="test")

    assert "__dict__" not in dir(slot_instance)
    assert "__slots__" in dir(slot_instance)

    assert "__dict__" in dir(non_slot_instance)
    assert "__slots__" not in dir(non_slot_instance)

    assert set(["x", "y"]) == set(slot_instance.__slots__)

    if has_pympler:
        assert asizeof(slot_instance) < asizeof(non_slot_instance)

    non_slot_instance.t = "test"
    with pytest.raises(AttributeError):
        slot_instance.t = "test"

    assert 1 == non_slot_instance.method()
    assert 1 == slot_instance.method()

    assert attr.fields(C1Slots) == attr.fields(C1)
    assert attr.asdict(slot_instance) == attr.asdict(non_slot_instance)
    def test_list_pools_default_one(self):
        """
        Verify the JSON response from listing all load balancer pools.
        By default, all tenants have one load balancer pool.
        """
        response, response_json = self.successResultOf(
            self.json_request(b"GET", "/load_balancer_pools"))
        self.assertEqual(200, response.code)
        self.assertEqual([b'application/json'],
                         response.headers.getRawHeaders(b'content-type'))
        self.assertEqual(1, len(response_json))

        pool_json = response_json[0]
        # has the right JSON
        self.assertTrue(all(
            aa.name in pool_json
            for aa in attr.fields(LoadBalancerPool)
            if aa.name != "nodes"))
        # Generated values
        self.assertTrue(all(
            pool_json.get(aa.name)
            for aa in attr.fields(LoadBalancerPool)
            if aa.name not in ("nodes", "status_detail")))

        self.assertEqual(
            {
                "cloud_servers": 0,
                "external": 0,
                "total": 0
            },
            pool_json['node_counts'],
            "Pool should start off with no members.")
Example #3
0
def stats_to_list(stats, include_lists=None):
  """ Renders stats entity to a list. If include_lists is specified
  it will skip not included fields. Also it always skips any nested lists and
  dictionaries because they brings dynamically changing columns list **.

  Args:
    stats: An instance of stats entity.
    include_lists: An instance of IncludeLists.
  Returns:
    A list representing stats.
  """
  if include_lists:
    included = include_lists.get_included_attrs(stats.__class__)
  else:
    included = attr.fields(stats.__class__)
  result = []
  for att in included:
    if not att.metadata:
      value = getattr(stats, att.name)
      result.append(value)
    elif Meta.ENTITY in att.metadata:
      value = getattr(stats, att.name)
      if value is not MISSED:
        # Render nested stats entity
        result += stats_to_list(value, include_lists)
      else:
        # Render needed number of MISSED values
        stats_class = att.metadata[Meta.ENTITY]
        if include_lists:
          values_number = len(include_lists.get_included_attrs(stats_class))
        else:
          values_number = len(attr.fields(stats_class))
        result += [MISSED] * values_number
  return result
def union2(p: Union[Type[A], Type[B]]):
    attr.fields(p)
    attr.fields_dict(p)

    attr.asdict(<warning descr="'attr.asdict' method should be called on attrs instances">p</warning>)
    attr.astuple(<warning descr="'attr.astuple' method should be called on attrs instances">p</warning>)
    attr.assoc(<warning descr="'attr.assoc' method should be called on attrs instances">p</warning>)
    attr.evolve(<warning descr="'attr.evolve' method should be called on attrs instances">p</warning>)
def union1(p: Union[A, B]):
    attr.fields(<warning descr="'attr.fields' method should be called on attrs types">p</warning>)
    attr.fields_dict(<warning descr="'attr.fields_dict' method should be called on attrs types">p</warning>)

    attr.asdict(p)
    attr.astuple(p)
    attr.assoc(p)
    attr.evolve(p)
Example #6
0
 def test_splits(self):
     """
     Splits correctly.
     """
     assert (
         frozenset((int, str)),
         frozenset((fields(C).a,)),
     ) == _split_what((str, fields(C).a, int,))
def structural(p):
    print(len(p))
    attr.fields(p)
    attr.fields_dict(p)

    attr.asdict(p)
    attr.astuple(p)
    attr.assoc(p)
    attr.evolve(p)
Example #8
0
 def insert(self, connection):
     """
     Commit a connection to the database
     :param sakia.data.entities.Connection connection: the connection to commit
     """
     connection_tuple = attr.astuple(connection, filter=attr.filters.exclude(attr.fields(Connection).password,
                                                                             attr.fields(Connection).salt))
     values = ",".join(['?'] * len(connection_tuple))
     self._conn.execute("INSERT INTO connections VALUES ({0})".format(values), connection_tuple)
Example #9
0
    def test_typing_annotations(self):
        """
        Sets the `Attribute.type` attr from typing annotations.
        """
        @attr.s
        class C:
            x: typing.List[int] = attr.ib()
            y = attr.ib(type=typing.Optional[str])

        assert typing.List[int] is attr.fields(C).x.type
        assert typing.Optional[str] is attr.fields(C).y.type
Example #10
0
    def test_basic_annotations(self):
        """
        Sets the `Attribute.type` attr from basic type annotations.
        """
        @attr.s
        class C:
            x: int = attr.ib()
            y = attr.ib(type=str)
            z = attr.ib()

        assert int is attr.fields(C).x.type
        assert str is attr.fields(C).y.type
        assert None is attr.fields(C).z.type
Example #11
0
    async def _async_save(self) -> None:
        """Save data."""
        if self._user_settings is None:
            return

        await self._user_store.async_save({STORAGE_USERS: {
            user_id: attr.asdict(
                notify_setting, filter=attr.filters.exclude(
                    attr.fields(NotifySetting).secret,
                    attr.fields(NotifySetting).counter,
                ))
            for user_id, notify_setting
            in self._user_settings.items()
        }})
    def create_widgets(self):
        """Creates all widgets in main window"""

        # Entry widgets

        self.labels = []
        self.entry_widgets = []

        for setting in attr.fields(PwmSettings):
            self.labels.append(tk.Label(self, justify="left",
                                        text=setting.metadata["guitext"]))

            widget = self.type2widget[setting.type](self)
            widget.set(self.settings[setting.name])
            self.entry_widgets.append(widget)

        # Buttons

        self.generate_button = tk.Button(self, text="Generate",
                                         command=self.generate)
        self.load_button = tk.Button(self, text="Load", command=self.load)
        self.save_button = tk.Button(self, text="Save", command=self.save)
        self.passwd_label = tk.Label(self, justify="left", text="Password")
        self.listbox_label = tk.Label(self, justify="left", text="Settings")
        self.listbox = tk.Listbox(self)
        self.listbox .bind('<<ListboxSelect>>', self.on_listbox)
        self.listbox.insert("end", "default")
        self.listbox.select_set(0)
        self.new_setting_button = tk.Button(self, text="+",
                                            command=self.new_setting)
        self.delete_setting_button = tk.Button(self, text="-",
                                               command=self.del_setting)

        self.passwd_text = tk.Entry(self, fg="blue")
Example #13
0
 def update(self, blockchain):
     """
     Update an existing blockchain in the database
     :param sakia.data.entities.Blockchain blockchain: the blockchain to update
     """
     updated_fields = attr.astuple(blockchain, filter=attr.filters.exclude(
         attr.fields(Blockchain).parameters, *BlockchainsRepo._primary_keys))
     where_fields = attr.astuple(blockchain, filter=attr.filters.include(*BlockchainsRepo._primary_keys))
     self._conn.execute("""UPDATE blockchains SET
                       current_buid=?,
                       current_members_count=?,
                       current_mass=?,
                       median_time=?,
                       last_mass=?,
                       last_members_count=?,
                       last_ud=?,
                       last_ud_base=?,
                       last_ud_time=?,
                       previous_mass=?,
                       previous_members_count=?,
                       previous_ud=?,
                       previous_ud_base=?,
                       previous_ud_time=?
                        WHERE
                       currency=?""",
                        updated_fields + where_fields)
Example #14
0
 def test_change(self, C, data):
     """
     Changes work.
     """
     # Take the first attribute, and change it.
     assume(fields(C))  # Skip classes with no attributes.
     field_names = [a.name for a in fields(C)]
     original = C()
     chosen_names = data.draw(st.sets(st.sampled_from(field_names)))
     # We pay special attention to private attributes, they should behave
     # like in `__init__`.
     change_dict = {name.replace('_', ''): data.draw(st.integers())
                    for name in chosen_names}
     changed = evolve(original, **change_dict)
     for name in chosen_names:
         assert getattr(changed, name) == change_dict[name.replace('_', '')]
Example #15
0
 def insert(self, contact):
     """
     Commit a contact to the database
     :param sakia.data.entities.Contact contact: the contact to commit
     """
     contacts_list = attr.astuple(contact, tuple_factory=list)
     contacts_list[3] = "\n".join([str(n) for n in contacts_list[3]])
     if contacts_list[-1] == -1:
         col_names = ",".join([a.name for a in attr.fields(Contact)[:-1]])
         contacts_list = contacts_list[:-1]
     else:
         col_names = ",".join([a.name for a in attr.fields(Contact)])
     values = ",".join(['?'] * len(contacts_list))
     cursor = self._conn.cursor()
     cursor.execute("INSERT INTO contacts ({:}) VALUES ({:})".format(col_names, values), contacts_list)
     contact.contact_id = cursor.lastrowid
Example #16
0
 def assert_proper_tuple_class(obj, obj_tuple):
     assert isinstance(obj_tuple, tuple_class)
     for index, field in enumerate(fields(obj.__class__)):
         field_val = getattr(obj, field.name)
         if has(field_val.__class__):
             # This field holds a class, recurse the assertions.
             assert_proper_tuple_class(field_val, obj_tuple[index])
Example #17
0
 def assert_proper_col_class(obj, obj_tuple):
     # Iterate over all attributes, and if they are lists or mappings
     # in the original, assert they are the same class in the dumped.
     for index, field in enumerate(fields(obj.__class__)):
         field_val = getattr(obj, field.name)
         if has(field_val.__class__):
             # This field holds a class, recurse the assertions.
             assert_proper_col_class(field_val, obj_tuple[index])
         elif isinstance(field_val, (list, tuple)):
             # This field holds a sequence of something.
             expected_type = type(obj_tuple[index])
             assert type(field_val) is expected_type  # noqa: E721
             for obj_e, obj_tuple_e in zip(field_val, obj_tuple[index]):
                 if has(obj_e.__class__):
                     assert_proper_col_class(obj_e, obj_tuple_e)
         elif isinstance(field_val, dict):
             orig = field_val
             tupled = obj_tuple[index]
             assert type(orig) is type(tupled)  # noqa: E721
             for obj_e, obj_tuple_e in zip(orig.items(),
                                           tupled.items()):
                 if has(obj_e[0].__class__):  # Dict key
                     assert_proper_col_class(obj_e[0], obj_tuple_e[0])
                 if has(obj_e[1].__class__):  # Dict value
                     assert_proper_col_class(obj_e[1], obj_tuple_e[1])
Example #18
0
def get_stats_header(stats_class, include_lists=None, prefix=''):
  """ Renders a list containing names of fields. If include_lists is specified
  it will skip not included fields. Also it always skips any nested lists and
  dictionaries because they bring dynamically changing columns list **.
  Order of names in this header corresponds to values order in
  a list generated by stats_to_list.

  Args:
    stats_class: An @attr.s decorated class representing stats model.
    include_lists: An instance of IncludeLists.
    prefix: A string prefix to be prepended to column names.
  Returns:
    A list representing names of stats fields.
  """
  if include_lists:
    included = include_lists.get_included_attrs(stats_class)
  else:
    included = attr.fields(stats_class)
  result = []
  for att in included:
    if not att.metadata:
      result.append('{}{}'.format(prefix, att.name))
    else:
      nested_entity_class = att.metadata.get(Meta.ENTITY)
      if nested_entity_class:
        result += get_stats_header(nested_entity_class, include_lists,
                                   '{}{}.'.format(prefix, att.name))
  return result
Example #19
0
    def test_typing_annotations(self):
        """
        Sets the `Attribute.type` attr from typing annotations.
        """
        @attr.s
        class C:
            x: typing.List[int] = attr.ib()
            y = attr.ib(type=typing.Optional[str])

        assert typing.List[int] is attr.fields(C).x.type
        assert typing.Optional[str] is attr.fields(C).y.type
        assert C.__init__.__annotations__ == {
            'x': typing.List[int],
            'y': typing.Optional[str],
            'return': None,
        }
Example #20
0
    def generate_image_url(self):
        """
        A URL to a clear image that can be embedded in HTML documents to track email open events.

        The query string of this URL is used to capture data about the email and visitor.
        """
        parameters = {}
        fields = attr.fields(self.__class__)
        for attribute in fields:
            value = getattr(self, attribute.name, None)
            if value is not None and 'param_name' in attribute.metadata:
                parameter_name = attribute.metadata['param_name']
                parameters[parameter_name] = str(value)

        tracking_id = self._get_tracking_id()
        if tracking_id is None:
            return None

        parameters['tid'] = tracking_id

        user_id_dimension = get_config_value_from_site_or_settings(
            "GOOGLE_ANALYTICS_USER_ID_CUSTOM_DIMENSION",
            site=self.site,
        )
        if user_id_dimension is not None and self.user_id is not None:
            parameter_name = 'cd{0}'.format(user_id_dimension)
            parameters[parameter_name] = self.user_id

        if self.course_id is not None and self.event_label is None:
            param_name = fields.event_label.metadata['param_name']
            parameters[param_name] = unicode(self.course_id)

        return u"https://www.google-analytics.com/collect?{params}".format(params=urlencode(parameters))
Example #21
0
    def test_change(self, C, data):
        """
        Changes work.
        """
        # Take the first attribute, and change it.
        assume(fields(C))  # Skip classes with no attributes.
        field_names = [a.name for a in fields(C)]
        original = C()
        chosen_names = data.draw(st.sets(st.sampled_from(field_names)))
        change_dict = {name: data.draw(st.integers())
                       for name in chosen_names}

        with pytest.deprecated_call():
            changed = assoc(original, **change_dict)

        for k, v in change_dict.items():
            assert getattr(changed, k) == v
Example #22
0
    def test_asdict_preserve_order(self, cls):
        """
        Field order should be preserved when dumping to OrderedDicts.
        """
        instance = cls()
        dict_instance = asdict(instance, dict_factory=OrderedDict)

        assert [a.name for a in fields(cls)] == list(dict_instance.keys())
Example #23
0
 def __str__(self):
     bits = []
     for a in attr.fields(self.__class__):
         value = getattr(self, a.name)
         if value is None:
             continue
         bits.append('{}={!r}'.format(a.name, value))
     return '\n'.join(bits)
    def update_widgets(self):
        """Updates widgets from current self.settings"""

        self.settings = self.settings_list.get_pwm_settings()

        for setting, widget in zip(attr.fields(PwmSettings),
                                   self.entry_widgets):
            widget.set(self.settings[setting.name])
 def is_information_complete(self) -> bool:
     """Return if all information is filled out."""
     want_dynamic_group = self.is_audio_group
     have_dynamic_group = self.is_dynamic_group is not None
     have_all_except_dynamic_group = all(
         attr.astuple(self, filter=attr.filters.exclude(
             attr.fields(ChromecastInfo).is_dynamic_group)))
     return (have_all_except_dynamic_group and
             (not want_dynamic_group or have_dynamic_group))
Example #26
0
    def test_basic_annotations(self):
        """
        Sets the `Attribute.type` attr from basic type annotations.
        """
        @attr.s
        class C:
            x: int = attr.ib()
            y = attr.ib(type=str)
            z = attr.ib()

        assert int is attr.fields(C).x.type
        assert str is attr.fields(C).y.type
        assert None is attr.fields(C).z.type
        assert C.__init__.__annotations__ == {
            'x': int,
            'y': str,
            'return': None,
        }
Example #27
0
 def test_pickle_object(self, cls, protocol):
     """
     Pickle object serialization works on all kinds of attrs classes.
     """
     if len(attr.fields(cls)) == 2:
         obj = cls(123, 456)
     else:
         obj = cls(123)
     assert repr(obj) == repr(pickle.loads(pickle.dumps(obj, protocol)))
Example #28
0
 def insert(self, blockchain):
     """
     Commit a blockchain to the database
     :param sakia.data.entities.Blockchain blockchain: the blockchain to commit
     """
     blockchain_tuple = attr.astuple(blockchain.parameters) \
                        + attr.astuple(blockchain, filter=attr.filters.exclude(attr.fields(Blockchain).parameters))
     values = ",".join(['?'] * len(blockchain_tuple))
     self._conn.execute("INSERT INTO blockchains VALUES ({0})".format(values), blockchain_tuple)
Example #29
0
    def test_factory_sugar(self):
        """
        Passing factory=f is syntactic sugar for passing default=Factory(f).
        """
        @attr.s
        class C(object):
            x = attr.ib(factory=list)

        assert Factory(list) == attr.fields(C).x.default
Example #30
0
def WriteStocksToCSV(fn, ticker_to_stocks):
    import csv
    with open(fn, 'w') as csvfile:
        csv_writer = csv.DictWriter(csvfile,
                                    fieldnames=[field.name for field in attr.fields(StockInfo)],
                                    delimiter=',')
        csv_writer.writeheader()
        for _, stock in ticker_to_stocks.items():
            csv_writer.writerow(attr.asdict(stock))