def test_insert_upper_level_element(saved_structure_instance,
                                    structure_get_schema, attributes):
    '''clean up structure tables'''
    [_structure.delete_fm_db() for _structure in StructureModel.find()]
    '''fill structure table'''
    fill_structure()
    '''choose constants to work with structure'''
    _criterions = {
        'view_id': choice(global_constants.get_VIEWS_PKS),
        'locale_id': choice(global_constants.get_PKS)
    }
    _uplev_elem_index = 1
    _uplev_elem_items = {
        'type': 'hblock',
        'subtype': 'pix',
        'qnt': '3',
        'name': 'fancy name'
    }
    _first_user_id = randrange(128)
    '''update original structure to work with'''
    _updating_structure = StructureModel.find_by_ids(_criterions)
    _updating_structure.update({'attributes': attributes})
    '''insert upper level element'''
    _updating_structure.insert_element(_uplev_elem_index, _uplev_elem_items,
                                       _first_user_id)
def test_StructureModel_find_by_ids(client, create_test_content):
    lng = 'en'
    _content_details = create_test_content(locale=lng)
    _ids = {
        'view_id': _content_details.get('view_id'),
        'locale_id': _content_details.get('locale_id')
    }
    '''success'''
    _attributes = StructureModel.find_by_ids(ids=_ids).attributes
    for key in [
            item for item in _content_details.keys()
            if item not in ['view_id', 'locale_id']
    ]:
        _index = _content_details.get(key).get('upper_index')
        _contant_extract = {
            k: v
            for (k, v) in _content_details.get(key).items()
            if k not in ['upper_index', 'structure']
        }
        assert _attributes.get(str(_index).zfill(2)) == _contant_extract
    # print('\ntest_model_structure:\n test_StructureModel_find_by_ids',)
    # print('  _contant_extract ->', _contant_extract)
    '''fails'''
    '''wrong keys'''
    _wrong = '_wrong_key'
    _wrong_ids = {**_ids, _wrong: _content_details.get('view_id')}
    _wrong_ids.pop('view_id')
    with pytest.raises(InvalidRequestError) as e_info:
        StructureModel.find_by_ids(ids=_wrong_ids)
    assert str(e_info.value) ==\
        (f'Entity namespace for "structure" has no property "{_wrong}"')
    '''not found'''
    _wrong_ids = {**_ids, 'view_id': 'wrong'}
    assert StructureModel.find_by_ids(ids=_wrong_ids) is None
def test_change_element_qnt(saved_structure_instance, structure_get_schema,
                            attributes):
    '''clean up structure tables'''
    [_structure.delete_fm_db() for _structure in StructureModel.find()]
    '''Fill structure table'''
    fill_structure()
    '''Choose constants to work with structure'''
    _criterions = {
        'view_id': choice(global_constants.get_VIEWS_PKS),
        'locale_id': choice(global_constants.get_PKS)
    }
    _block_index = 1
    _qnt = attributes.get(str(_block_index).zfill(2)).get('qnt')
    _first_user_id = randrange(128)
    '''Update structure'''
    _updating_structure = StructureModel.find_by_ids(_criterions)
    _updating_structure.update({'attributes': attributes})
    _us_dumped = structure_get_schema.dump(_updating_structure)
    _element_qnt = _us_dumped.get('attributes').get(
        str(_block_index).zfill(2)).get('qnt')
    _user_id = _us_dumped.get('user_id')
    '''Expect it's updated as per available constants'''
    assert _element_qnt == _qnt
    assert _user_id == 0
    '''add element'''
    _updating_structure.change_element_qnt('inc', _block_index, _first_user_id)
    '''Get elements and check expectations'''
    _updated_structure = StructureModel.find_by_ids(_criterions)

    _us_dumped = structure_get_schema.dump(_updated_structure)
    _element_qnt = _us_dumped.get('attributes').get(
        str(_block_index).zfill(2)).get('qnt')
    _user_id = _us_dumped.get('user_id')
    '''Expect it's updated as per available constants'''
    assert _element_qnt == _qnt + 1
    assert _first_user_id == _user_id

    # print('\ntest_model_structure:\n test_add_element',
    #       '\n  _updated_structure ->',
    #       structure_get_schema.dump(_updated_structure),
    #       '\n  _element_qnt ->', _element_qnt)
    '''remove element'''
    _second_user_id = randrange(128)
    _updating_structure.change_element_qnt('dec', _block_index,
                                           _second_user_id)
    '''Get elements and check expectations'''
    _updated_structure = StructureModel.find_by_ids(_criterions)

    _us_dumped = structure_get_schema.dump(_updated_structure)
    _element_qnt = _us_dumped.get('attributes').get(
        str(_block_index).zfill(2)).get('qnt')
    _user_id = _us_dumped.get('user_id')
    '''Expect it's updated as per available constants'''
    assert _element_qnt == _qnt
    assert _second_user_id == _user_id
Exemplo n.º 4
0
 def load_fm_db(cls, identity: str = '', view_id: str = '',
                locale_id: str = '', load_name: bool = False
                ) -> Union[None, 'ContentElementsBlock']:
     '''here identity consisn of upper_index, type, subtype -
         01_type_subtype'''
     '''
     The method creates ContentElementsBlock instance based on info
         from db content table. Name is got from structure table.
         In case of structure table record for this page does not
         exist name would be empty.
     I do not check loaded elements validity due to productivity.
     '''
     _splitted_identity = identity.split('_')
     _elements = ContentModel.find_identity_like(
         searching_criterions={
             'view_id': view_id, 'locale_id': locale_id},
         identity_like=f'{identity}%')
     if len(_elements) == 0:
         return None
     instance = ContentElementsBlock(
         upper_index=int(_splitted_identity[0]),
         type=_splitted_identity[1],
         subtype=_splitted_identity[2],
         elements=[
             element.serialize() for element in _elements
         ])
     if load_name:
         _structure_instance = StructureModel.find_by_ids(
             ids={'view_id': view_id, 'locale_id': locale_id})
         if _structure_instance is not None:
             instance.name = _structure_instance.attributes.get(
                 str(instance.upper_index).zfill(2)).get('name')
     return instance
Exemplo n.º 5
0
def test_PageView_load_fm_db(client, view_name, locale, elements):
    '''clean up content table'''
    [_structure.delete_fm_db() for _structure in StructureModel.find()]
    [_content.delete_fm_db() for _content in ContentModel.find()]

    _user_id = randrange(128)
    _view_name = view_name()
    _locale = locale()
    _elements = elements()
    _page_view = PageView(view_name=_view_name,
                          locale=_locale,
                          elements=_elements)
    _page_view.save_to_db(user_id=_user_id)
    '''success'''
    _page_view_fm_db = PageView.load_fm_db(ids={
        'view_id': _view_name,
        'locale_id': _locale
    })
    assert _page_view_fm_db.view_name == _page_view.view_name
    assert _page_view_fm_db.locale == _page_view.locale
    assert len(_page_view_fm_db.elements) == len(_page_view.elements)
    for i, element in enumerate(_page_view.elements):
        _type = type(element)
        assert isinstance(_page_view_fm_db.elements[i], _type)
        assert _page_view_fm_db.elements[i].name == element.name
        if isinstance(element, ContentElementsBlock):
            assert len(_page_view_fm_db.elements[i].elements)\
                == len(element.elements)
    '''fails'''
    _wrong = 'wrong'
    _fm_db = PageView.load_fm_db({'view_id': _wrong, 'locale_id': locale})
    assert _fm_db is None
def test_StructureModel_remove_element_cls(saved_structure_instance,
                                           structure_get_schema, attributes):
    '''Clean up'''
    StructureModel.query.delete()
    '''Create structures with empty attribure, it should be 10 of them.'''
    _global_view_keys = global_constants.get_VIEWS_PKS
    _global_locales_keys = global_constants.get_PKS
    _structure_gens = [
        saved_structure_instance({
            'view_id': _view_key,
            'locale_id': _locale_key,
            # 'attributes': attributes
        }) for _view_key in _global_view_keys
        for _locale_key in _global_locales_keys
    ]
    [next(_structure_gen) for _structure_gen in _structure_gens]
    '''choose one of the structure'''
    _criterions = {
        'view_id': choice(_global_view_keys),
        'locale_id': choice(_global_locales_keys)
    }

    _instance = StructureModel.find_by_ids(_criterions)
    _instance.update({'attributes': attributes})
    # _index = randrange(len(attributes))
    # _element_structure = StructureModel.get_element_cls(
    #     _criterions, _index)
    '''Clean up'''
    [next(_structure_gen) for _structure_gen in _structure_gens]
Exemplo n.º 7
0
 def save_to_db_structure(self,
                          view_id: str = '',
                          locale_id: str = '',
                          user_id: int = 0) -> Union[None, str]:
     '''get existing structure record'''
     _structure_instance = StructureModel.find_by_ids(ids={
         'view_id': view_id,
         'locale_id': locale_id
     })
     '''no such structure records'''
     if _structure_instance is None:
         _structure_instance = structure_schema.load(
             {
                 'view_id': view_id,
                 'locale_id': locale_id,
                 'user_id': user_id,
                 'attributes': self.serialize_to_structure
             },
             session=dbs_global.session)
         return _structure_instance.save_to_db()
     else:
         _structure_attributes = {**_structure_instance.attributes}
     key = str(self.upper_index).zfill(2)
     _structure_attributes[key] = self.serialize_to_structure.get(key)
     # print('\nContentElementsSimple:\n save_to_db',
     #       '\n  _structure_instance ->', _structure_instance)
     return _structure_instance.update({
         'attributes': _structure_attributes,
         'user_id': user_id
     })
Exemplo n.º 8
0
 def load_fm_db(cls,
                identity: str = '',
                view_id: str = '',
                locale_id: str = '',
                load_name: bool = False) -> 'ContentElementsSimple':
     '''
     The method creates ContentElementsSimple instance based on info
         from db content table. The method should be called by
         PageView instance.
     I do not check loaded elements validity due to productivity.
     '''
     content_model = ContentModel.find_by_identity_view_locale(
         identity=identity, view_id=view_id, locale_id=locale_id)
     if content_model is None:
         return None
     _info = content_model.identity.split('_')
     _value = {
         'title': content_model.title,
         'content': content_model.content
     }
     instance = ContentElementsSimple(upper_index=int(_info[0]),
                                      type=_info[1],
                                      element=_value)
     if load_name:
         _structure_instance = StructureModel.find_by_ids(
             ids={
                 'view_id': view_id,
                 'locale_id': locale_id
             })
         if _structure_instance is not None:
             instance.name = _structure_instance.attributes.get(
                 str(instance.upper_index).zfill(2)).get('name')
     return instance
def test_StructureModel_find(client, create_test_content):
    lng_00 = 'en'
    lng_01 = 'ru'
    create_test_content(locale=lng_00)
    create_test_content(locale=lng_01, clean=False)
    _found = StructureModel.find()
    assert isinstance(_found, List)
    assert len(_found) == 2
    _found = StructureModel.find(searching_criterions={'user_id': 0})
    assert len(_found) == 2
    _found = StructureModel.find(searching_criterions={'user_id': 1})
    assert len(_found) == 0
    _found = StructureModel.find(searching_criterions={
        'user_id': 0,
        'locale_id': 'en'
    })
    assert len(_found) == 1
def test_StructureModel_get_element_both(client, create_test_content):
    lng_00 = 'en'
    lng_01 = 'ru'
    _content_details_00 = create_test_content(locale=lng_00, user_id=1)
    create_test_content(locale=lng_01, clean=False)
    _block_01 = _content_details_00.get('block_00')
    _simple_00 = _content_details_00.get('simple_00')
    _ids = {
        'view_id': _content_details_00.get('view_id'),
        'locale_id': _content_details_00.get('locale_id'),
    }
    _found = StructureModel.find_by_ids(ids=_ids)
    _upper_index = _block_01.get('upper_index')
    _element = _found.get_element(upper_index=_upper_index)
    assert _element ==\
        _block_01.get('structure').get(str(_upper_index).zfill(2))
    _upper_index = _simple_00.get('upper_index')
    _element = StructureModel.get_element_cls(ids=_ids,
                                              upper_index=_upper_index)
    assert _element ==\
        _simple_00.get('structure').get(str(_upper_index).zfill(2))
Exemplo n.º 11
0
    def _method(values: Dict = {}):

        _values = {
            'view_id': values.get(
                'view_id', global_constants.get_VIEWS[0].get('view_id')),
            'locale_id': values.get(
                'locale_id', global_constants.get_LOCALES[0].get('id')),
            'created': values.get('created', datetime.now()),
            'user_id': values.get('user_id', randint(1, 128)),
            'attributes': values.get('attributes', {})
        }
        return StructureModel(**_values)
def test_update(saved_structure_instance, structure_get_schema, attributes):
    '''Clean up the structure table'''
    StructureModel.query.delete()
    '''Create structures, it should be 10 of them.'''
    _global_view_keys = global_constants.get_VIEWS_PKS
    _global_locales_keys = global_constants.get_PKS
    [{
        'view_id': _view_key,
        'locale_id': _locale_key
    } for _view_key in _global_view_keys
     for _locale_key in _global_locales_keys]
    _structure_gens = [
        saved_structure_instance({
            'view_id': _view_key,
            'locale_id': _locale_key
        }) for _view_key in _global_view_keys
        for _locale_key in _global_locales_keys
    ]
    [next(_structure_gen) for _structure_gen in _structure_gens]
    '''Choose random keys to update structure'''
    _criterions = {
        'view_id': choice(_global_view_keys),
        'locale_id': choice(_global_locales_keys)
    }
    _structure_for_update = StructureModel.find_by_ids(_criterions)
    assert structure_get_schema.dump(_structure_for_update).get(
        'updated') is None
    _attributes = {
        'key1': 'test_key1',
        'key2': 'test_key2',
        'key3': 'test_key3',
    }
    _structure_for_update.update({'attributes': _attributes})
    _updated_schema = StructureModel.find_by_ids(_criterions)
    assert structure_get_schema.dump(_structure_for_update).get(
        'updated') is not None
    assert structure_get_schema.dump(_updated_schema).get(
        'attributes') == _attributes
    '''Clean up'''
    [next(_structure_gen) for _structure_gen in _structure_gens]
def test_delete(saved_structure_instance, structure_get_schema, view_id,
                attributes):
    '''Clean up'''
    StructureModel.query.delete()
    '''Create structures, it should be 10 of them.'''
    _global_view_keys = global_constants.get_VIEWS_PKS
    _global_locales_keys = global_constants.get_PKS
    [{
        'view_id': _view_key,
        'locale_id': _locale_key
    } for _view_key in _global_view_keys
     for _locale_key in _global_locales_keys]
    _structure_gens = [
        saved_structure_instance({
            'view_id': _view_key,
            'locale_id': _locale_key,
            'attributes': {
                'view_id': _view_key,
                'locale_id': _locale_key
            }
        }) for _view_key in _global_view_keys
        for _locale_key in _global_locales_keys
    ]
    [next(_structure_gen) for _structure_gen in _structure_gens]
    '''Choose random keys to update structure'''
    _criterions = {
        'view_id': choice(_global_view_keys),
        'locale_id': choice(_global_locales_keys)
    }
    _structure_to_delete = StructureModel.find_by_ids(_criterions)

    _structure_to_delete.delete_fm_db()

    _deleted_structure = StructureModel.find_by_ids(_criterions)
    _left_stractures = StructureModel.find()
    assert _deleted_structure is None
    assert len(_left_stractures) == 9
    '''Clean up'''
    [next(_structure_gen) for _structure_gen in _structure_gens]
Exemplo n.º 14
0
def test_structure_list_success(client, user_instance, access_token, lng, qnt,
                                test_word):
    '''
    Right
    '''
    '''Fill structure table'''
    fill_structure()
    '''Admin in db'''
    # _admin = user_instance(values={'role_id': 'admin'})
    # _admin.save_to_db()
    # _access_token = access_token(_admin)

    _uuid = uuid4()
    sessions.setter(str(_uuid))
    _tech_token = create_access_token(_uuid, expires_delta=False)
    _headers = {
        'Authorization': f"Bearer {_tech_token}",
        'Content-Type': 'application/json',
        'Accept-Language': lng
    }
    _resp = client.get(url_for('structure_bp.structurelist'), headers=_headers)

    assert _resp.status_code == 200
    assert isinstance(_resp.json, Dict)
    assert isinstance(_resp.json.get('payload'), List)
    assert len(_resp.json.get('payload')) == qnt
    assert _resp.json.get('message').find(test_word) != -1
    if len(_resp.json.get('payload')) > 0:
        assert [
            structure.get('locale_id') == lng
            for structure in _resp.json.get('payload')
        ]
    print('\ntest_structure_list_success, _resp ->', _resp.status_code)
    # print('test_structure_list_success, _resp ->', _resp.json.get('payload')[0])
    # print('test_structure_list_success, _resp ->')
    # [print(structure) for structure in _resp.json.get('payload')]
    '''clean up users tables'''
    # if _admin is not None:
    #     _admin.delete_fm_db()
    '''clean up structure tables'''
    [_structure.delete_fm_db() for _structure in StructureModel.find()]
Exemplo n.º 15
0
def test_PageView_remove_vals(client, view_name, locale, simple_element,
                              block_element, elements):
    '''clean up tables'''
    [_content.delete_fm_db() for _content in ContentModel.find()]
    [_structure.delete_fm_db() for _structure in StructureModel.find()]
    _view_name = view_name()
    _locale = locale()
    _elements = elements()
    _page_view = PageView(view_name=_view_name,
                          locale=_locale,
                          elements=_elements)
    _length = len(_page_view.elements)
    _remove_position = randrange(_length)
    _element_in_page = dumps(_page_view.get_element_vals(_remove_position),
                             sort_keys=True)
    _removed_element = dumps(_page_view.remove_vals(_remove_position),
                             sort_keys=True)
    assert len(_page_view.elements) == _length - 1
    assert _removed_element == _element_in_page
    _last_element = _page_view.get_element_vals(_length - 2)
    assert _last_element.get('index') == len(_page_view.elements) - 1
    _page_view.save_to_db(user_id=randrange(128))
Exemplo n.º 16
0
def test_PageView_save_to_db(client, view_name, locale, elements):
    '''clean up content table'''
    [_structure.delete_fm_db() for _structure in StructureModel.find()]
    [_content.delete_fm_db() for _content in ContentModel.find()]
    '''success'''
    _user_id = randrange(128)
    _view_name = view_name()
    _locale = locale()
    _elements = elements()
    _page_view = PageView(view_name=_view_name,
                          locale=_locale,
                          elements=_elements)
    _page_view.save_to_db(user_id=_user_id)
    # print('\ntest_page_view:\n test_PageView_save_to_db')
    # [print(
    #     '  _elements ->', element.upper_index) for element in _elements]
    for element in _page_view.elements:
        # print('  elements ->', element.__dict__)
        _identity = '_'.join([str(element.upper_index).zfill(2), element.type])
        if isinstance(element, ContentElementsBlock):
            _identity = '_'.join([_identity, element.subtype])
        # print('  _identity ->', _identity)
        element_fm_db = element.load_fm_db(identity=_identity,
                                           view_id=_view_name,
                                           locale_id=_locale)
        assert element.upper_index == element_fm_db.upper_index
        assert element.type == element_fm_db.type
        if isinstance(element, ContentElementsBlock):
            assert element.subtype == element_fm_db.subtype
            for j, item in enumerate(element.elements):
                assert item.value == element_fm_db.elements[j].value
                # print('  from_db ->', item.value)
                # print('  from_db ->', element_fm_db.elements[j].value)
        elif isinstance(element, ContentElementsSimple):
            assert element.element.value == element_fm_db.element.value
    '''failure'''
Exemplo n.º 17
0
    def _method(locale: str = '', size_00: int = 0, user_id: int = 0,
                clean: bool = True):
        '''clean up content tables if required'''
        if clean:
            [_structure.delete_fm_db()
             for _structure in StructureModel.find()]
            [_content.delete_fm_db() for _content in ContentModel.find()]

        '''choose testing constants'''
        _view_id = choice(global_constants.get_VIEWS_PKS)
        if locale == '':
            _locale_id = choice(global_constants.get_PKS)
        else:
            _locale_id = locale
        _upper_index_00 = randrange(100)
        _upper_index_01 = randrange(100)
        while _upper_index_01 == _upper_index_00:
            _upper_index_01 = randrange(100)
        _upper_index_02 = randrange(100)
        while _upper_index_02 == _upper_index_00\
                or _upper_index_02 == _upper_index_01:
            _upper_index_02 = randrange(100)
        _upper_index_03 = randrange(100)
        while _upper_index_03 == _upper_index_00\
                or _upper_index_03 == _upper_index_01\
                or _upper_index_03 == _upper_index_02:
            _upper_index_03 = randrange(100)

        if size_00 == 0:
            _size_00 = randrange(3, 7)
        else:
            _size_00 = size_00
        _size_01 = randrange(2, 5)
        _type_00 = choice(ContentElementsBlock._types)
        _type_01 = choice([item for item in ContentElementsBlock._types
                           if item != _type_00])
        _type_02 = choice(ContentElementsSimple._types)
        _type_03 = choice([item for item in ContentElementsSimple._types
                           if item != _type_02])
        _subtype_00 = choice(ContentElementsBlock._subtypes)
        _subtype_01 = choice(
            [item for item in ContentElementsBlock._subtypes
             if item != _subtype_00])
        _name_00 = f'name of {_type_00}'
        _name_01 = f'name of {_type_01}'
        _name_02 = f'name of {_type_02}'
        _name_03 = f'name of {_type_03}'

        _elements_dict_00 = elements_dict(_size_00)
        _elements_dict_01 = elements_dict(_size_01)
        _element_00 = element(0)
        _element_01 = element(1)

        _block_instance_00 = ContentElementsBlock(
            upper_index=_upper_index_00,
            type=_type_00, subtype=_subtype_00,
            name=_name_00, elements=_elements_dict_00)
        _block_instance_00.save_to_db_content(
            view_id=_view_id, locale_id=_locale_id, user_id=user_id,
            save_structure=True)
        _block_instance_01 = ContentElementsBlock(
            upper_index=_upper_index_01,
            type=_type_01, subtype=_subtype_01,
            name=_name_01, elements=_elements_dict_01)
        _block_instance_01.save_to_db_content(
            view_id=_view_id, locale_id=_locale_id, user_id=user_id,
            save_structure=True)
        _simple_instance_00 = ContentElementsSimple(
            upper_index=_upper_index_02, type=_type_02,
            name=_name_02, element=_element_00)
        _simple_instance_00.save_to_db_content(
            view_id=_view_id, locale_id=_locale_id, user_id=user_id,
            save_structure=True)
        _simple_instance_01 = ContentElementsSimple(
            upper_index=_upper_index_03, type=_type_03,
            name=_name_03, element=_element_01)
        _simple_instance_01.save_to_db_content(
            view_id=_view_id, locale_id=_locale_id, user_id=user_id,
            save_structure=True)

        _structure_block_00 = _block_instance_00.serialize_to_structure
        _structure_block_01 = _block_instance_01.serialize_to_structure
        _structure_simple_00 = _simple_instance_00.serialize_to_structure
        _structure_simple_01 = _simple_instance_01.serialize_to_structure
        # print('\ntest_api_contents_handling:\n create_test_content',
        #       '\n  _structure_simple_00 ->', _structure_simple_00,
        #       '\n  _structure_simple_01 ->', _structure_simple_01,
        #       )
        return {
            'view_id': _view_id,
            'locale_id': _locale_id,
            'block_00': {
                'upper_index': _upper_index_00,
                'type': _type_00,
                'subtype': _subtype_00,
                'name': _name_00,
                'qnt': _structure_block_00.get(
                    str(_upper_index_00).zfill(2)).get('qnt'),
                'structure': _structure_block_00
            },
            'block_01': {
                'upper_index': _upper_index_01,
                'type': _type_01,
                'subtype': _subtype_01,
                'name': _name_01,
                'qnt': _structure_block_01.get(
                    str(_upper_index_01).zfill(2)).get('qnt'),
                'structure': _structure_block_01
            },
            'simple_00': {
                'upper_index': _upper_index_02,
                'type': _type_02,
                'name': _name_02,
                'structure': _structure_simple_00
            },
            'simple_01': {
                'upper_index': _upper_index_03,
                'type': _type_03,
                'name': _name_03,
                'structure': _structure_simple_01
            }
        }
Exemplo n.º 18
0
def test_PageView_move_element(client, view_name, locale, simple_element,
                               block_element, elements):
    '''it works I don't like to test success movements'''
    '''clean up tables'''
    [_content.delete_fm_db() for _content in ContentModel.find()]
    [_structure.delete_fm_db() for _structure in StructureModel.find()]
    _view_name = view_name()
    _locale = locale()
    _ids = {'view_id': _view_name, 'locale_id': _locale}
    _elements = elements()
    _page_view = PageView(view_name=_view_name,
                          locale=_locale,
                          elements=_elements)
    _page_view.save_to_db(user_id=1)
    _length = len(_page_view.elements)
    '''success'''
    '''moving up'''
    # _index = 1
    _index = randrange(1, _length)
    _direction = 'up'
    _moving_element = _page_view.get_element_vals(_index)
    _moving_element.pop('index')
    _moving_element_json = dumps(_moving_element, sort_keys=True)

    _shifting_element = _page_view.get_element_vals(_index - 1)
    _shifting_element.pop('index')
    _shifting_element_json = dumps(_shifting_element, sort_keys=True)

    _page_view.move_element(_index, _direction)
    _page_view.save_to_db(user_id=2)
    _loaded_view = PageView.load_fm_db(ids=_ids)

    _moved_element = _loaded_view.get_element_vals(_index - 1)
    _moved_element.pop('index')
    _moved_element_json = dumps(_moved_element, sort_keys=True)

    _shifted_element = _loaded_view.get_element_vals(_index)
    _shifted_element.pop('index')
    _shifted_element_json = dumps(_shifted_element, sort_keys=True)
    assert _moved_element_json == _moving_element_json
    assert _shifted_element_json == _shifting_element_json
    # print('\ntest_page_view:\n test_PageView_move_element')
    # [print(dumps(element.serialize_to_content, indent=4))
    #  for element in _loaded_view.elements]
    '''moving down'''
    _index = randrange(0, _length - 1)
    _direction = 'down'
    _moving_element = _page_view.get_element_vals(_index)
    _moving_element.pop('index')
    _moving_element_json = dumps(_moving_element, sort_keys=True)

    _shifting_element = _page_view.get_element_vals(_index + 1)
    _shifting_element.pop('index')
    _shifting_element_json = dumps(_shifting_element, sort_keys=True)

    _page_view.move_element(_index, _direction)

    _moved_element = _page_view.get_element_vals(_index + 1)
    _moved_element.pop('index')
    _moved_element_json = dumps(_moved_element, sort_keys=True)

    _shifted_element = _page_view.get_element_vals(_index)
    _shifted_element.pop('index')
    _shifted_element_json = dumps(_shifted_element, sort_keys=True)
    assert _moved_element_json == _moving_element_json
    assert _shifted_element_json == _shifting_element_json
    '''fails'''
    '''wrong combination index - direction'''
    _direction = 'up'
    _index = 0
    with pytest.raises(WrongIndexError) as e_info:
        _page_view.move_element(_index, _direction)
    assert str(e_info.value).find('-1') != -1

    _direction = 'down'
    _index = _length - 1
    with pytest.raises(WrongIndexError) as e_info:
        _page_view.move_element(_index, _direction)
    assert str(e_info.value).find('4') != -1
    '''wrong direction'''
    _direction = 'f**k'
    with pytest.raises(WrongDirection) as e_info:
        _page_view.move_element(_index, _direction)
    assert str(e_info.value).find(_direction) != -1
Exemplo n.º 19
0
def test_ContentElementsBlock_save_to_db_content_structure(
        client, element, elements_dict):
    '''clean up content table'''
    [_structure.delete_fm_db() for _structure in StructureModel.find()]
    [_content.delete_fm_db() for _content in ContentModel.find()]
    '''create testing consants'''
    _view_id = choice(global_constants.get_VIEWS_PKS)
    _locale_id = choice(global_constants.get_PKS)
    _upper_index = randrange(100)
    _user_id = randrange(128)
    _size = 10
    # _size = randrange(3, 20)
    _type = choice(ContentElementsBlock._types)
    _subtype = choice(ContentElementsBlock._subtypes)
    _name = f'name of {_type}'
    _elements_dict = elements_dict(_size)
    '''create ContentElementsBlock instance'''
    _block_instance = ContentElementsBlock(upper_index=_upper_index,
                                           type=_type,
                                           subtype=_subtype,
                                           name=_name,
                                           elements=_elements_dict)
    assert len(_block_instance.elements) == _size
    '''save it to db'''
    _block_instance.save_to_db_content(view_id=_view_id,
                                       locale_id=_locale_id,
                                       user_id=_user_id,
                                       save_structure=True)
    '''load insance having PKs and check it adequate to source'''
    _loaded_instance = ContentElementsBlock.load_fm_db(identity='_'.join(
        [str(_upper_index).zfill(2), _type, _subtype]),
                                                       view_id=_view_id,
                                                       locale_id=_locale_id,
                                                       load_name=True)
    assert _loaded_instance.upper_index == _upper_index
    assert _loaded_instance.type == _type
    assert _loaded_instance.subtype == _subtype
    assert _loaded_instance.name == _name
    for i, element in enumerate(_loaded_instance.elements):
        assert element.value == _elements_dict[i]
    # print('\ntest_content_elements_block:',
    #       '\n test_ContentElementsBlock_save_to_db_content',
    #       '\n  _loaded_instance ->', _loaded_instance)
    '''get records directly from content table'''
    _identity_like = '_'.join([str(_upper_index).zfill(2), _type, _subtype])
    _content_model_instance = ContentModel.find_identity_like(
        searching_criterions={
            'view_id': _view_id,
            'locale_id': _locale_id
        },
        identity_like=f"{_identity_like}%",
    )
    assert len(_content_model_instance) == _size
    for i, element in enumerate(_content_model_instance):
        _element_dict = content_get_schema.dump(element)
        assert _element_dict == {
            'identity': '_'.join([_identity_like,
                                  str(i).zfill(3)]),
            'view_id': _view_id,
            'locale_id': _locale_id,
            'user_id': _user_id,
            **_elements_dict[i]
        }
    '''get record from structure table, check it'''
    _structure_dict = StructureModel.find_by_ids({
        'view_id': _view_id,
        'locale_id': _locale_id
    }).get_element(_upper_index)
    assert _structure_dict == {
        'type': _type,
        'subtype': _subtype,
        'qnt': _size,
        'name': f'name of {_type}'
    }
    '''correct loaded ContentElementsBlock instance and reduce element
        quantity'''
    _block_instance.remove(randrange(len(_block_instance.elements)))
    _block_instance.remove(randrange(len(_block_instance.elements)))
    _index = randrange(len(_block_instance.elements))
    _new_title = f"corrected title for element No '{_index}'"
    _new_element = {
        **_block_instance.get_element(index=_index).value, 'title': _new_title
    }
    _block_instance.set_element(index=_index, value=_new_element)
    '''save it to db'''
    _block_instance.save_to_db_content(view_id=_view_id,
                                       locale_id=_locale_id,
                                       user_id=_user_id,
                                       save_structure=True)
    '''load new instance and check it adequate to changes'''
    _corrected_model_instance = ContentModel.find_identity_like(
        searching_criterions={
            'view_id': _view_id,
            'locale_id': _locale_id
        },
        identity_like=f"{_identity_like}%",
    )
    assert len(_corrected_model_instance) == _size - 2
    assert _corrected_model_instance[_index].serialize().get('title')\
        == _new_title
    '''get record from structure table, check it'''
    _structure_dict = StructureModel.find_by_ids({
        'view_id': _view_id,
        'locale_id': _locale_id
    }).get_element(_upper_index)
    assert _structure_dict == {
        'type': _type,
        'subtype': _subtype,
        'qnt': _size - 2,
        'name': f'name of {_type}'
    }
Exemplo n.º 20
0
def test_ContentElementsBlock_move(client, view_name, locale, element,
                                   elements_dict):
    '''clean up content table'''
    [_structure.delete_fm_db() for _structure in StructureModel.find()]
    [_content.delete_fm_db() for _content in ContentModel.find()]
    '''object variables'''
    _view_name = view_name()
    _locale = locale()
    _upper_index = randrange(3, 20)
    # _size = 3
    _size = randrange(2, 10)
    _type = 'vblock'
    _subtype = 'txt'
    _name = f'name of {_type}'

    _elements_dict = elements_dict(_size)
    # _element = element(_size)
    _block_instance = ContentElementsBlock(upper_index=_upper_index,
                                           type=_type,
                                           subtype=_subtype,
                                           name=_name,
                                           elements=_elements_dict)
    assert len(_block_instance._elements) == _size
    _block_instance.save_to_db_content(view_id=_view_name,
                                       locale_id=_locale,
                                       user_id=randrange(128),
                                       save_structure=True)
    # _index = 1
    _index = randrange(_size - 1)
    '''fail'''
    '''wrong direction'''
    _wrong = 'f**k'
    with pytest.raises(WrongDirection) as e_info:
        _block_instance.move(index=_index, direction=_wrong)
    assert str(e_info.value).find(_wrong) != -1
    '''success, down'''
    _direction = 'down'
    _moving_element = _block_instance.get_element(_index)
    _replacing_element = _block_instance.get_element(_index + 1)
    _block_instance.move(index=_index, direction=_direction)
    _block_instance.save_to_db_content(view_id=_view_name,
                                       locale_id=_locale,
                                       user_id=randrange(128))
    _loaded_instance = ContentElementsBlock.load_fm_db(identity='_'.join(
        [str(_upper_index).zfill(2), _type, _subtype]),
                                                       view_id=_view_name,
                                                       locale_id=_locale,
                                                       load_name=True)
    _moved_element = _loaded_instance.get_element(_index + 1)
    _replaced_element = _loaded_instance.get_element(_index)
    assert _moving_element.value == _moved_element.value
    assert _replacing_element.value == _replaced_element.value
    '''success, up'''
    _index = randrange(1, _size)
    _direction = 'up'
    _moving_element = _block_instance.get_element(_index)
    _replacing_element = _block_instance.get_element(_index - 1)
    _block_instance.move(index=_index, direction=_direction)
    _block_instance.save_to_db_content(view_id=_view_name,
                                       locale_id=_locale,
                                       user_id=randrange(128))
    _loaded_instance = ContentElementsBlock.load_fm_db(identity='_'.join(
        [str(_upper_index).zfill(2), _type, _subtype]),
                                                       view_id=_view_name,
                                                       locale_id=_locale,
                                                       load_name=True)
    _moved_element = _loaded_instance.get_element(_index - 1)
    _replaced_element = _loaded_instance.get_element(_index)
    assert _moving_element.value == _moved_element.value
    assert _replacing_element.value == _replaced_element.value
    '''fail, wrong direction - index combination'''
    _index = 0
    _direction = 'up'
    with pytest.raises(WrongIndexError) as e_info:
        _block_instance.move(index=_index, direction=_direction)
    assert str(e_info.value).find(str(_index - 1))
    _index = len(_block_instance.elements) - 1
    _direction = 'down'
    with pytest.raises(WrongIndexError) as e_info:
        _block_instance.move(index=_index, direction=_direction)
    assert str(e_info.value).find(str(_index + 1))
def test_UpperLevelHandling_patch(client, create_test_content, user_instance,
                                  access_token, view_name, locale, elements,
                                  lng, test_word_00, test_word_01,
                                  test_word_02, test_word_03, test_word_04,
                                  test_word_05):
    '''clean up tables'''
    [_content.delete_fm_db() for _content in ContentModel.find()]
    [_structure.delete_fm_db() for _structure in StructureModel.find()]
    '''create and save new contents in tables'''
    _view_name = view_name()
    _locale = lng
    _elements = elements()
    _page_view = PageView(view_name=_view_name,
                          locale=_locale,
                          elements=_elements)
    _page_view.save_to_db(user_id=randrange(128))
    # _index = 1
    '''Create user and admin'''
    _user = user_instance({'role_id': 'user'})
    _user.save_to_db()
    _admin = user_instance({'role_id': 'admin'})
    _admin.save_to_db()
    '''create tokens'''
    _admin_access_token = access_token(_admin)
    _user_access_token = access_token(_user)
    '''creating headers'''
    _admin_headers = {
        'Authorization': f'Bearer {_admin_access_token}',
        'Content-Type': 'application/json',
        'Accept-Language': _locale
    }
    _user_headers = {
        'Authorization': f'Bearer {_user_access_token}',
        'Content-Type': 'application/json',
        'Accept-Language': _locale
    }
    '''success'''
    '''remove random element'''
    _index = randrange(len(_elements) - 1)
    _identity = str(_index).zfill(2)
    _json = {'view_id': _view_name, 'identity': _identity}
    _resp = client.patch(url_for('contents_bp.upperlevelhandling'),
                         json=_json,
                         headers=_admin_headers)
    assert _resp.status_code == 200
    assert _resp.json.get('message').find(test_word_00) != -1
    '''failues'''
    '''No tokens'''
    _no_token_header = {
        k: v
        for (k, v) in _admin_headers.items() if k != 'Authorization'
    }
    _resp = client.patch(url_for('contents_bp.upperlevelhandling'),
                         json=_json,
                         headers=_no_token_header)
    assert _resp.status_code == 401
    assert _resp.json.get('description').find(test_word_01) != -1
    assert _resp.json.get('error') == 'authorization_required'
    '''Non admin'''
    _resp = client.patch(url_for('contents_bp.upperlevelhandling'),
                         json=_json,
                         headers=_user_headers)
    assert _resp.status_code == 401
    assert _resp.json.get('message').find(test_word_02) != -1
    '''No block identity'''
    _json_no_id = {k: v for (k, v) in _json.items() if k != 'identity'}
    _resp = client.patch(url_for('contents_bp.upperlevelhandling'),
                         json=_json_no_id,
                         headers=_admin_headers)
    assert _resp.status_code == 400
    assert _resp.json.get('message').find(test_word_03) != -1
    assert _resp.json.get('payload') == "'identity'"
    '''wrong identity'''
    '''first part is not integer'''
    _wrong_identity = 'f**k'
    _json = {'view_id': _view_name, 'identity': _wrong_identity}
    _resp = client.patch(url_for('contents_bp.upperlevelhandling'),
                         json=_json,
                         headers=_admin_headers)
    assert _resp.status_code == 400
    assert _resp.json == (
        f"invalid literal for int() with base 10: '{_wrong_identity}'")
    '''index out of range'''
    _wrong_identity = '-1'
    _json = {'view_id': _view_name, 'identity': _wrong_identity}
    _resp = client.patch(url_for('contents_bp.upperlevelhandling'),
                         json=_json,
                         headers=_admin_headers)
    assert _resp.status_code == 400
    assert _resp.json.get('message').find(test_word_03) != -1
    assert _resp.json.get('payload').find(_wrong_identity) != -1

    _wrong_identity = str(len(_page_view.elements))
    _json = {'view_id': _view_name, 'identity': _wrong_identity}
    _resp = client.patch(url_for('contents_bp.upperlevelhandling'),
                         json=_json,
                         headers=_admin_headers)
    assert _resp.status_code == 400
    assert _resp.json.get('message').find(test_word_03) != -1
    assert _resp.json.get('payload').find(_wrong_identity) != -1
def test_UpperLevelHandling_post(client, create_test_content, user_instance,
                                 access_token, view_name, locale, elements,
                                 lng, test_word, test_word_01, test_word_02,
                                 test_word_03, test_word_04):
    '''clean up tables'''
    [_content.delete_fm_db() for _content in ContentModel.find()]
    [_structure.delete_fm_db() for _structure in StructureModel.find()]
    '''create and save new contents in tables'''
    _view_name = view_name()
    _locale = lng
    _elements = elements()
    _page_view = PageView(view_name=_view_name,
                          locale=_locale,
                          elements=_elements)
    _page_view.save_to_db(user_id=randrange(128))
    # _index = 1
    '''Create user and admin'''
    _user = user_instance({'role_id': 'user'})
    _user.save_to_db()
    _admin = user_instance({'role_id': 'admin'})
    _admin.save_to_db()
    '''create tokens'''
    _admin_access_token = access_token(_admin)
    _user_access_token = access_token(_user)
    '''creating headers'''
    _admin_headers = {
        'Authorization': f'Bearer {_admin_access_token}',
        'Content-Type': 'application/json',
        'Accept-Language': _locale
    }
    _user_headers = {
        'Authorization': f'Bearer {_user_access_token}',
        'Content-Type': 'application/json',
        'Accept-Language': _locale
    }
    '''success'''
    _direction = 'up'
    _index = randrange(1, len(_elements))
    _index_key = str(_index).zfill(2)
    _info_json = _elements[_index].serialize_to_structure
    _identity = '_'.join(
        [list(_info_json.keys())[0],
         _info_json.get(_index_key).get('type')])
    if isinstance(_page_view.elements[_index], ContentElementsBlock):
        _identity = '_'.join(
            [_identity, _info_json.get(_index_key).get('subtype')])
    _json = {
        'view_id': _view_name,
        'identity': _identity,
        'direction': _direction
    }
    _resp = client.post(url_for('contents_bp.upperlevelhandling'),
                        json=_json,
                        headers=_admin_headers)
    assert _resp.status_code == 200
    assert _resp.json.get('message').find(test_word) != -1
    '''down'''
    _direction = 'down'
    _index = randrange(len(_elements) - 1)
    _info_json = _elements[_index].serialize_to_structure
    _identity = '_'.join([
        list(_info_json.keys())[0],
        _info_json.get(str(_index).zfill(2)).get('type')
    ])
    if isinstance(_page_view.elements[_index], ContentElementsBlock):
        _identity = '_'.join(
            [_identity,
             _info_json.get(str(_index).zfill(2)).get('subtype')])
    _json = {
        'view_id': _view_name,
        'identity': _identity,
        'direction': _direction
    }
    _resp = client.post(url_for('contents_bp.upperlevelhandling'),
                        json=_json,
                        headers=_admin_headers)
    assert _resp.status_code == 200
    assert _resp.json.get('message').find(test_word) != -1
    '''failues'''
    '''No tokens'''
    _no_token_header = {
        k: v
        for (k, v) in _admin_headers.items() if k != 'Authorization'
    }
    _resp = client.post(url_for('contents_bp.upperlevelhandling'),
                        json=_json,
                        headers=_no_token_header)
    assert _resp.status_code == 401
    assert _resp.json.get('description').find(test_word_01) != -1
    '''Non admin'''
    _resp = client.post(url_for('contents_bp.upperlevelhandling'),
                        json=_json,
                        headers=_user_headers)
    assert _resp.status_code == 401
    assert _resp.json.get('message').find(test_word_02) != -1
    '''No block identity'''
    _json_no_id = {k: v for (k, v) in _json.items() if k != 'identity'}
    _resp = client.post(url_for('contents_bp.upperlevelhandling'),
                        json=_json_no_id,
                        headers=_admin_headers)
    assert _resp.status_code == 400
    assert _resp.json.get('message').find(test_word_03) != -1
    assert _resp.json.get('payload') == "'identity'"
    '''wrong direction - index combination'''
    _index = 0
    _direction = 'up'
    _index_key = str(_index).zfill(2)
    _info_json = _elements[_index].serialize_to_structure
    _identity = '_'.join([_index_key, _info_json.get(_index_key).get('type')])
    if isinstance(_page_view.elements[_index], ContentElementsBlock):
        _identity = '_'.join(
            [_identity, _info_json.get(_index_key).get('subtype')])
    _json_up = {
        'view_id': _view_name,
        'identity': _identity,
        'direction': _direction
    }
    _resp = client.post(url_for('contents_bp.upperlevelhandling'),
                        json=_json_up,
                        headers=_admin_headers)
    assert _resp.status_code == 400
    assert _resp.json.get('message').find(test_word_03) != -1
    assert _resp.json.get('payload').find(str(_index - 1)) != -1

    _index = len(_elements) - 1
    _direction = 'down'
    _index_key = str(_index).zfill(2)
    _info_json = _elements[_index].serialize_to_structure
    _identity = '_'.join([_index_key, _info_json.get(_index_key).get('type')])
    if isinstance(_page_view.elements[_index], ContentElementsBlock):
        _identity = '_'.join(
            [_identity, _info_json.get(_index_key).get('subtype')])
    _json_down = {
        'view_id': _view_name,
        'identity': _identity,
        'direction': _direction
    }
    _resp = client.post(url_for('contents_bp.upperlevelhandling'),
                        json=_json_down,
                        headers=_admin_headers)
    assert _resp.status_code == 400
    assert _resp.json.get('message').find(test_word_03) != -1
    assert _resp.json.get('payload').find(str(_index + 1)) != -1
    '''generate not found error'''
    _wrong_view_id = 'wrong'
    _wrong_view_id_json = {**_json, 'view_id': _wrong_view_id}
    _resp = client.post(url_for('contents_bp.upperlevelhandling'),
                        json=_wrong_view_id_json,
                        headers=_admin_headers)
    assert _resp.status_code == 404
    assert _resp.json.get('message').find(test_word_04) != -1
    assert _resp.json.get('message').find(_wrong_view_id) != -1
    '''clean up users'''
    if _user is not None:
        _user.delete_fm_db()
    if _admin is not None:
        _admin.delete_fm_db()
def test_ContentElementsSimple_save_to_db_content_structure(
        client, value):
    '''clean up structure and content tables'''
    [_structure.delete_fm_db() for _structure in StructureModel.find()]
    [_content.delete_fm_db() for _content in ContentModel.find()]
    '''init'''
    _view_id = choice(global_constants.get_VIEWS_PKS)
    _locale_id = choice(global_constants.get_PKS)
    _upper_index = randrange(100)
    _user_id = randrange(64)
    _type = 'header'
    _name = 'name'
    # _value = value('db value')
    _element = value('element value')

    '''creating element for testing'''
    _content_element = ContentElementsSimple(
        upper_index=_upper_index, type=_type,
        name=_name, element=_element)
    _content_element.save_to_db_content(
        view_id=_view_id, locale_id=_locale_id, user_id=_user_id,
        save_structure=True)
    '''testing useing load'''
    _loaded_instance = ContentElementsSimple.load_fm_db(
        identity={'_'.join([str(_upper_index).zfill(2), _type])},
        view_id=_view_id, locale_id=_locale_id, load_name=True)

    '''test loaded element'''
    assert _loaded_instance.upper_index == _upper_index
    assert _loaded_instance.type == _type
    assert _loaded_instance.name == _name
    assert _loaded_instance.element.value == _element

    '''testing records in tables'''
    _found_db_instance = ContentModel.find_by_identity_view_locale(
        identity='_'.join([str(_upper_index).zfill(2), _type]),
        view_id=_view_id, locale_id=_locale_id
    )
    assert _found_db_instance.identity\
        == '_'.join([str(_upper_index).zfill(2), _type])
    assert _found_db_instance.title == _element.get('title')
    assert _found_db_instance.content == _element.get('content')

    '''update db record with element instance, same PKs'''
    _element = value(marker='new value')
    _name = f'new {_name}'
    # _upper_index = randrange(50, 100)
    _user_id = randrange(64, 128)
    _new_instance = ContentElementsSimple(
        upper_index=_upper_index, type=_type,
        name=_name, element=_element)
    _new_instance.save_to_db_content(
        view_id=_view_id, locale_id=_locale_id,
        user_id=_user_id, save_structure=True)
    _found_identity = ContentElementsSimple.load_fm_db(
        identity='_'.join([str(_upper_index).zfill(2), _type]),
        view_id=_view_id,
        locale_id=_locale_id,
        load_name=True
    )
    assert _found_identity.upper_index == _upper_index
    assert _found_identity.type == _type
    # assert _found_identity.name == _name
    assert _found_identity.element.value == _element