def test_ContentElementsSimple_delete_fm_db(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)
    _type = 'header'
    _name = 'name'
    _value = value('db value')
    _element = value('element value')
    _identity = '_'.join([str(_upper_index).zfill(2), _type])

    '''creating record in db'''
    _record = content_schema.load({
        'identity': _identity,
        'view_id': _view_id, 'locale_id': _locale_id,
        'title': _value.get('title'), 'content': _value.get('content')
    }, session=dbs_global.session)
    _record.save_to_db()
    '''test it exists'''
    _found_db_instance = ContentModel.find_by_identity_view_locale(
        identity=_identity,
        view_id=_view_id, locale_id=_locale_id
    )
    assert _found_db_instance.identity\
        == _identity
    assert _found_db_instance.view_id == _view_id
    assert _found_db_instance.locale_id == _locale_id
    assert _found_db_instance.title == _value.get('title')
    assert _found_db_instance.content == _value.get('content')

    '''create element instance with same PKs and delete record with
        the element'''
    _element_instance = ContentElementsSimple(
        upper_index=_upper_index, type=_type,
        name=_name, element=_element)
    _element_instance.delete_fm_db(view_id=_view_id, locale_id=_locale_id)
    '''check there is nothing in db'''
    _found_db_instance = ContentModel.find_by_identity_view_locale(
        identity=_identity,
        view_id=_view_id, locale_id=_locale_id)
    assert _found_db_instance is None

    '''try to delete the instance once more'''
    with pytest.raises(RecordNotFoundError) as e_info:
        _element_instance.delete_fm_db(
            view_id=_view_id, locale_id=_locale_id)
    # assert str(e_info.value)\
    #     == (f"Record with identity '{_identity}', view id '{_view_id}' "
    #         f"and locale id '{_locale_id}' has not been found.")
    assert str(e_info.value).find(_identity) != -1
    assert str(e_info.value).find(_view_id) != -1
    assert str(e_info.value).find(_locale_id) != -1
def test_ContentElementsSimple_load_fm_db(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'''
    '''Create test constants'''
    _view_id = choice(global_constants.get_VIEWS_PKS)
    _locale_id = choice(global_constants.get_PKS)
    _record_id = '_'.join([
        str(randrange(99)).zfill(2),
        choice(ContentElementsSimple._types)])
    _value = value('simple element load fm db testing')
    '''Fill contents table'''
    _record = content_schema.load({
        'identity': _record_id, 'view_id': _view_id,
        'locale_id': _locale_id, 'title': _value.get('title'),
        'content': _value.get('content')
    }, session=dbs_global.session)
    _record.save_to_db()
    content_elements_simple = ContentElementsSimple.load_fm_db(
        identity=_record_id, view_id=_view_id, locale_id=_locale_id)
    assert content_elements_simple.upper_index\
        == int(_record_id.split('_')[0])
    assert content_elements_simple.type == _record_id.split('_')[1]
    _simple_json = json.dumps(
        content_elements_simple.element.value, sort_keys=True)
    # _value_json =
    assert _simple_json == json.dumps(_value, sort_keys=True)
def test_contents_post_success(
    client, content_api_resp,
    user_instance, access_token,
    lng, test_word, test_word_01
):
    '''Create instance and get proper confirmation'''
    _user = user_instance(values={'role_id': 'admin'})
    _user.save_to_db()  # to have user with this id
    _access_token = access_token(_user)
    # create content instance to confirm it works
    _headers = {'Authorization': f'Bearer {_access_token}',
                'Content-Type': 'application/json',
                'Accept-Language': lng}
    _lng_key = {'locale_id': lng}
    resp = content_api_resp(values=_lng_key, headers=_headers)
    assert resp.status_code == 201
    assert 'message' in resp.json.keys()
    assert 'payload' in resp.json.keys()
    assert resp.json.get('message').find(test_word) != -1
    assert resp.json.get('payload').get('locale_id') == lng
    # print('\ntest_content_post, code ->', resp.status_code)
    # print('test_content_post, json ->', resp.json.get('payload'))
    '''clean up'''
    '''user'''
    _user.delete_fm_db()
    '''content'''
    _search_json = {k: v for (k, v) in resp.json.get('payload').items()
                    if k in ['identity', 'view_id', 'locale_id']}
    _contents = ContentModel.find_by_identity_view_locale(**_search_json)
    if _contents:
        _contents.delete_fm_db()
示例#4
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
示例#5
0
def test_ContentElementsBlock_load_fm_db(client, element, elements_dict):
    '''clean up content tables'''
    # [_structure.delete_fm_db() for _structure in StructureModel.find()]
    [_content.delete_fm_db() for _content in ContentModel.find()]

    _view_id = choice(global_constants.get_VIEWS_PKS)
    _locale_id = choice(global_constants.get_PKS)
    _upper_index_00 = randrange(100)
    _upper_index_01 = randrange(100)
    while _upper_index_01 == _upper_index_00:
        _upper_index_01 = randrange(100)
    _size_00 = 3
    _size_01 = 5
    _type_00 = choice(ContentElementsBlock._types)
    _type_01 = choice(
        [item for item in ContentElementsBlock._types if item != _type_00])
    _subtype = choice(ContentElementsBlock._subtypes)
    _name_00 = f'name of {_type_00}'
    _name_01 = f'name of {_type_01}'

    _elements_dict_00 = elements_dict(_size_00)
    _block_instance_00 = ContentElementsBlock(upper_index=_upper_index_00,
                                              type=_type_00,
                                              subtype=_subtype,
                                              name=_name_00,
                                              elements=_elements_dict_00)
    assert len(_block_instance_00.elements) == _size_00
    for element in _block_instance_00.serialize_to_content:
        _content_record = content_schema.load(
            {
                **element, 'view_id': _view_id,
                'locale_id': _locale_id
            },
            session=dbs_global.session)
        _content_record.save_to_db()

    _elements_dict_01 = elements_dict(_size_01)
    _block_instance_01 = ContentElementsBlock(upper_index=_upper_index_01,
                                              type=_type_01,
                                              subtype=_subtype,
                                              name=_name_01,
                                              elements=_elements_dict_01)
    assert len(_block_instance_01.elements) == _size_01

    for element in _block_instance_01.serialize_to_content:
        _content_record = content_schema.load(
            {
                **element, 'view_id': _view_id,
                'locale_id': _locale_id
            },
            session=dbs_global.session)
        _content_record.save_to_db()
    '''testing'''
    _identity = '_'.join([str(_upper_index_00).zfill(2), _type_00, _subtype])
    loaded_block_instance = ContentElementsBlock.load_fm_db(
        identity=_identity, view_id=_view_id, locale_id=_locale_id)

    for i, instance in enumerate(loaded_block_instance.elements):
        assert instance.value == _elements_dict_00[i]
def test_contents_post_wrong_fk(client, content_api_resp,
                                lng, test_word, test_word_01,
                                user_instance, access_token):
    '''
    Operation with foreign key that are not in appropriate tables.
    '''
    _user = user_instance(values={'role_id': 'admin'})
    _user.save_to_db()  # to have user with this id
    _access_token = access_token(_user)
    '''create content instance to confirm it works'''
    _headers = {'Authorization': f'Bearer {_access_token}',
                'Content-Type': 'application/json',
                'Accept-Language': lng}
    resp = content_api_resp(headers=_headers)
    _search_json = {k: v for (k, v) in resp.json.get('payload').items()
                    if k in ['identity', 'view_id', 'locale_id']}

    assert resp.status_code == 201
    assert 'message' in resp.json.keys()
    assert 'payload' in resp.json.keys()
    assert isinstance(resp.json.get('payload'), Dict)
    assert resp.json.get('message').find(test_word) != -1
    assert resp.json.get('payload').get('locale_id') == lng

    _create_json = {k: v for(k, v) in resp.json.get('payload').items()
                    if k not in ['created', 'view']}

    '''Try to create instance breaching db's constrains:'''
    '''wrong locale_id'''
    _wrong_creating_json = _create_json.copy()
    # _wrong_creating_json['locale_id'] = 'not'
    _headers = {**_headers, 'Accept-Language': 'wrong'}
    resp = client.post(url_for('contents_bp.content'),
                       json=_wrong_creating_json,
                       headers=_headers)
    assert resp.status_code == 500
    assert 'payload' in resp.json.keys()
    assert isinstance(resp.json['payload'], str)

    '''wrong view_id'''
    _wrong_creating_json = _create_json.copy()
    _headers = {**_headers, 'Accept-Language': lng}
    _wrong_creating_json['view_id'] = 'not'
    resp = client.post(url_for('contents_bp.content'),
                       json=_wrong_creating_json, headers=_headers)
    assert resp.status_code == 500
    assert 'payload' in resp.json.keys()
    assert isinstance(resp.json['payload'], str)
    assert resp.json['message'].find(test_word_01) != -1
    assert resp.json['payload'].find('foreign key constraint fails') != -1

    '''Clean up user table'''
    _user.delete_fm_db()
    '''clean up contents'''
    _contents = ContentModel.find_by_identity_view_locale(**_search_json)
    if _contents:
        _contents.delete_fm_db()
 def _method(values: Dict = {}):
     # keys = content_ids.keys()
     lng = values.get(
         'locale_id', global_constants.get_LOCALES[0]['id'])
     _values = {
         'identity': values.get(
             'identity', random_text(qnt=2, underscore=True)),
         'view_id':
             values.get(
                 'view_id',
                 global_constants.get_VIEWS[0].get('view_id')),
         'locale_id': lng,
         'user_id': values.get('user_id', randint(1, 128)),
         'title': values.get('title', random_text(lng=lng, qnt=3)),
         'content': values.get('content', random_text(lng=lng, qnt=5)),
     }
     return ContentModel(**_values)
def test_contents_post_already_exists(
    client, content_api_resp,
    lng, test_word,
    user_instance, access_token
):
    _user = user_instance(values={'role_id': 'admin'})  # user admin
    _user.save_to_db()  # to have user with this id
    _access_token = access_token(_user)
    _headers = {'Authorization': f'Bearer {_access_token}',
                'Content-Type': 'application/json',
                'Accept-Language': lng}
    '''Create one instance'''
    resp = content_api_resp(values={'locale_id': lng}, headers=_headers)
    _search_json = {k: v for (k, v) in resp.json.get('payload').items()
                    if k in ['identity', 'view_id', 'locale_id']}
    assert resp.status_code == 201
    assert 'message' in resp.json.keys()
    assert 'payload' in resp.json.keys()
    assert isinstance(resp.json.get('payload'), Dict)
    assert resp.json.get('message').find(test_word) != -1

    '''Try to save other instance with same keys'''
    _create_json = {k: v for(k, v) in resp.json.get('payload').items()
                    if k not in ['created', 'view', 'locale']}
    resp = client.post(url_for('contents_bp.content'),
                       json=_create_json, headers=_headers)
    assert resp.status_code == 400
    assert 'message' in resp.json.keys()
    assert 'payload' not in resp.json.keys()
    assert resp.json.get('message').find(test_word) != -1

    '''clean up'''
    '''user'''
    _user.delete_fm_db()
    '''contents'''
    # print(_search_json)
    _contents = ContentModel.find_by_identity_view_locale(**_search_json)
    if _contents:
        _contents.delete_fm_db()
示例#9
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))
示例#10
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'''
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 _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
            }
        }
def test_contents_get(client, content_api_resp,
                      lng, test_word, test_word_01,
                      sessions, user_instance, access_token):
    '''user admin to create content instance'''
    _user = user_instance(values={'role_id': 'admin'})
    _user.save_to_db()
    _access_token = access_token(_user)

    '''Create instance'''
    _headers = {'Authorization': f'Bearer {_access_token}',
                'Content-Type': 'application/json',
                'Accept-Language': lng}
    _lng_key = {'locale_id': lng}
    resp = content_api_resp(values=_lng_key, headers=_headers)
    _search_json = {k: v for (k, v) in resp.json.get('payload').items()
                    if k in ['identity', 'view_id', 'locale_id']}
    assert resp.status_code == 201
    assert 'message' in resp.json.keys()
    assert 'payload' in resp.json.keys()
    assert resp.json.get('message').find(test_word) != -1
    assert resp.json.get('payload').get('locale_id') == lng

    '''Find data with normal set of keys having tech_token and sessions:'''
    _uuid = uuid4()
    sessions.setter(str(_uuid))
    _tech_token = create_access_token(_uuid, expires_delta=False)
    _original_json = resp.json.get('payload').copy()
    _key_json = {key: value for (key, value) in _original_json.items()
                 if key in ['view_id', 'identity']}
    _get_headers = {**_headers, 'Authorization': f'Bearer {_tech_token}'}
    resp = client.get(url_for('contents_bp.content', **_key_json), headers=_get_headers)

    '''Check found data has been identical:'''
    assert resp.status_code == 200
    assert 'message' in resp.json.keys()
    assert 'payload' in resp.json.keys()
    assert resp.json.get('message').find(test_word) != -1
    for key in _original_json.keys():
        assert _original_json.get(key) == resp.json.get('payload').get(key)

    '''Try to find data with wrong value (404):'''
    for key in _key_json.keys():
        _wrong_value_json = _key_json.copy()
        _wrong_value_json[key] += '_wrong'

        resp = client.get(url_for('contents_bp.content',
                                  **_wrong_value_json), headers=_get_headers)
        assert resp.status_code == 404
        assert 'payload' not in resp.json.keys()
        assert 'message' in resp.json.keys()
        assert resp.json.get('message').find(test_word) != -1
        assert resp.json.get('message').find(lng) != -1
    resp = client.get(
        url_for('contents_bp.content', **_key_json),
        headers={**_get_headers, 'Accept-Language': 'wrong'})
    assert resp.status_code == 404
    assert 'payload' not in resp.json.keys()
    assert 'message' in resp.json.keys()
    # print('\ntest_content_get, code ->', resp.status_code)
    # print('test_content_get, json ->', resp.json)

    '''Clean up user table'''
    _user.delete_fm_db()
    '''clean up contents'''
    _contents = ContentModel.find_by_identity_view_locale(**_search_json)
    if _contents:
        _contents.delete_fm_db()
示例#14
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
示例#15
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}'
    }
def test_content_put(client, content_api_resp,
                     lng, test_word, test_word_01,
                     user_instance, access_token):
    _admin = user_instance(values={'role_id': 'admin'})
    _admin.save_to_db()  # to have user with this id
    _access_token = access_token(_admin)
    _headers = {'Authorization': f'Bearer {_access_token}',
                'Content-Type': 'application/json',
                'Accept-Language': lng}
    '''Create data with normal set of keys:'''
    _lng_key = {'locale_id': lng}
    resp = content_api_resp(values=_lng_key, headers=_headers)
    _search_json = {k: v for (k, v) in resp.json.get('payload').items()
                    if k in ['identity', 'view_id', 'locale_id']}
    _original_json = {k: v for(k, v) in resp.json.get('payload').items() if k not in [
        'locale', 'created', 'updated', 'view']}
    _key_json = {key: value for (key, value) in _original_json.items() if key in [
        'identity', 'view_id']}
    _value_json = {key: value for (key, value) in _original_json.items() if key not in [
        'identity', 'view_id', 'locale_id', 'user_id']}
    assert resp.status_code == 201
    assert 'message' in resp.json.keys()
    assert 'payload' in resp.json.keys()
    assert resp.json.get('message').find(test_word) != -1
    assert resp.json.get('payload').get('locale_id') == lng

    '''Find and update data with normal set of keys:'''
    for key in _value_json.keys():
        # print(key)
        _corrected_data = _original_json.copy()
        # if isinstance(_corrected_data.get(key), int):
        #     print('\nfunctional, contents, put key ->', key)
        #     _corrected_data[key] = 0
        # elif isinstance(_corrected_data.get(key), str):
        _corrected_data[key] += ' - corrected'
        resp = client.put(url_for('contents_bp.content'),
                          json=_corrected_data, headers=_headers)
        assert resp.status_code == 200
        assert 'payload' in resp.json.keys()
        assert resp.json['payload'][key] == _corrected_data[key]
        assert resp.json.get('message').find(test_word) != -1
        assert resp.json.get('payload').get('locale_id') == lng
        # print('\nfunctional, contents, put code ->', resp.status_code)
        # print('functional, contents, put json ->', resp.json.get('payload').get(key))

    '''Try to find view with wrong value (404):'''
    for key in _key_json.keys():
        _wrong_key_value = _key_json.copy()
        _wrong_key_value[key] += '_wrong'
        resp = client.put(url_for('contents_bp.content'),
                          json=_wrong_key_value, headers=_headers)
        assert resp.status_code == 404
        assert 'payload' not in resp.json.keys()
        assert isinstance(resp.json, Dict)
        assert resp.json.get('message').find(test_word) != -1
        assert resp.json.get('message').find(lng) != -1
    resp = client.put(url_for('contents_bp.content'),
                      json=_key_json,
                      headers=({**_headers, 'Accept-Language': 'wrong'}))
    assert resp.status_code == 404
    assert 'payload' not in resp.json.keys()
    assert isinstance(resp.json, Dict)
    # assert resp.json.get('message').find(test_word) != -1
    # assert resp.json.get('message').find(lng) != -1
    # print('\nfunctional, contents, put code ->', resp.status_code)
    # print('functional, contents, put json ->', resp.json)

    '''Clean up user table'''
    _admin.delete_fm_db()
    '''clean up contents'''
    _contents = ContentModel.find_by_identity_view_locale(**_search_json)
    if _contents:
        _contents.delete_fm_db()
示例#17
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_content_delete(client, content_api_resp,
                        sessions, user_instance,
                        lng, test_word,
                        access_token):
    # lng = 'en'
    '''Create data with normal set of keys:'''
    _user = user_instance(values={'role_id': 'admin'})  # user not admin
    _user.save_to_db()  # to have user with this id
    _access_token = access_token(_user)
    _headers = {'Authorization': f'Bearer {_access_token}',
                'Content-Type': 'application/json',
                'Accept-Language': lng}

    resp = content_api_resp(values={'locale_id': lng}, headers=_headers)
    _search_json = {k: v for (k, v) in resp.json.get('payload').items()
                    if k in ['identity', 'view_id', 'locale_id']}
    _key_json = {k: v for (k, v) in resp.json.get('payload').items()
                 if k in ['identity', 'view_id']}
    #  if k in ['identity', 'view_id', 'locale_id']}

    '''Insure content is exist in db:'''
    _uuid = uuid4()
    sessions.setter(str(_uuid))
    _tech_token = create_access_token(_uuid, expires_delta=False)
    params = _key_json.copy()
    # params = {k: v for (k, v) in _key_json.items() if k not in ['locale_id']}
    _get_headers = {**_headers, 'Authorization': f'Bearer {_tech_token}'}

    resp = client.get(url_for('contents_bp.content', **params), headers=_get_headers)
    assert resp.status_code == 200
    assert 'payload' in resp.json.keys()
    assert isinstance(resp.json['payload'], Dict)
    assert resp.json.get('message').find(test_word) != -1

    '''Try to find view with wrong value (404):'''
    for key in _key_json.keys():
        _wrong_key_value = _key_json.copy()
        _wrong_key_value[key] += '_wrong'
        headers = {**_headers, 'Accept-Language': lng}
        resp = client.delete(url_for('contents_bp.content',
                                     **_wrong_key_value), headers=headers)
        assert resp.status_code == 404
        assert 'message' in resp.json.keys()
        assert 'payload' not in resp.json.keys()
        assert resp.json.get('message').find(test_word) != -1
    headers = {**_headers, 'Accept-Language': 'wrong'}
    # print('\ntest_content_delete, params ->', params, '\theaders ->', headers)
    resp = client.delete(url_for('contents_bp.content',
                                 **_key_json), headers=headers)
    assert resp.status_code == 404
    assert 'message' in resp.json.keys()
    assert 'payload' not in resp.json.keys()
    # assert resp.json.get('message').find(test_word) != -1

    '''delete view instance from db:'''
    resp = client.delete(url_for('contents_bp.content', **_key_json), headers=_headers)
    assert resp.status_code == 200
    assert 'message' in resp.json.keys()
    assert 'payload' not in resp.json.keys()
    assert resp.json.get('message').find(test_word) != -1

    '''try to delete already deleted instance'''
    resp = client.delete(url_for('contents_bp.content', **_key_json), headers=_headers)
    assert resp.status_code == 404
    assert 'message' in resp.json.keys()
    assert 'payload' not in resp.json.keys()
    assert resp.json.get('message').find(test_word) != -1

    '''Insure view is deleted in db:'''
    resp = client.get(url_for('contents_bp.content', **_key_json), headers=_get_headers)
    assert resp.status_code == 404
    assert 'message' in resp.json.keys()
    assert 'payload' not in resp.json.keys()
    assert resp.json.get('message').find(test_word) != -1
    # print('\ntest_content_delete, resp ->', resp.status_code)
    # print('test_content_delete, resp ->', resp.json)

    '''Clean up user table'''
    _user.delete_fm_db()
    '''clean up contents'''
    _contents = ContentModel.find_by_identity_view_locale(**_search_json)
    if _contents:
        _contents.delete_fm_db()
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