示例#1
0
def setup_links_instances(mocked_resolve_url, links_list, setup_user_instances,
                          uuids):
    User = get_user_model()
    assert User.objects.count() == 2

    users_links = {}

    all_users = User.objects.all().order_by('username')

    with open('/tmp/temptestfile.txt', 'w+') as temp_test_file:
        reference_date = datetime.strptime('2021-01-01 08:00:00',
                                           '%Y-%m-%d %H:%M:%S')
        for index, url in enumerate(links_list):
            is_even = index % 2 == 0
            user = all_users.first() if is_even else all_users.last()

            reference_date = reference_date + timedelta(days=3)
            frozen_timestamp = reference_date.strftime('%Y-%m-%d %H:%M:%S')
            with freeze_time(frozen_timestamp):
                new_url = Link(original_link=url, user=user)
                new_url.id = uuids[index]
                new_url.save()

            if str(user.id) not in users_links.keys():
                users_links[str(user.id)] = []

            serialized_url_dict = LinkSerializer(new_url).data

            temp_test_file.write(
                f'Adding link for username={user.username}: '
                f'{json.dumps(serialized_url_dict, cls=DjangoJSONEncoder)}\n')

            users_links[str(user.id)].append(serialized_url_dict)

    return users_links
示例#2
0
def test_set_name_from_url_when_name_empty(setup_user_instances):  # pylint: disable=unused-argument
    User = get_user_model()
    assert User.objects.count() == 2

    urls = (
        'https://johnlekberg.com/blog/2020-11-27-cli-pandoc.html',
        'https://github.com/andy-landy/traceback_with_variables#colors',
        'https://jon.bo/posts/digital-tools/',
        'https://danishpraka.sh/2020/02/23/journaling-in-vim.html',
        'https://danishpraka.sh/',
        'https://github.com/danishprakash/vimport',
    )

    for url in urls:
        new_url = Link(original_link=url, user=User.objects.first())
        new_url.save()

    names = [link.name for link in Link.objects.all()]

    expected_names = [
        'johnlekberg.com 2020-11-27-cli-pandoc.html',
        'github.com traceback_with_variables#colors',
        'jon.bo digital-tools',
        'danishpraka.sh journaling-in-vim.html',
        'danishpraka.sh',
        'github.com vimport',
    ]

    assert set(names) == set(expected_names)

    Link.objects.all().delete()
示例#3
0
def politician_link_add_view(request, unique_key):
    politician = get_object_or_404(Politician, unique_key=unique_key)
    url        = request.POST.get('url')
    error      = False

    if not url.startswith(('http://', 'https://')):
        url = 'http://%s' % url

    if '.' not in url:
        error = True

    if not error:
        l = Link(
            politician=politician,
            url=url
        )
        l.save()
        url = ''

    links      = (
        Link.objects.filter(politician=politician))

    return render(request, 'core/edit/links.html', {
        'links'      : links,
        'politician' : politician,
        'error'      : error,
        'input'      : url
    })
示例#4
0
def politician_link_add_view(request, unique_key):
    politician = get_object_or_404(Politician, unique_key=unique_key)
    link_type  = get_object_or_404(LinkType, id=request.POST.get('link_type'))
    url        = request.POST.get('url')
    error      = False

    if not url.startswith(('http://', 'https://')):
        url = 'http://%s' % url

    if '.' not in url:
        error = True

    if not error:
        l = Link(
            type=link_type,
            politician=politician,
            url=url
        )
        l.save()
        url = ''

    types      = LinkType.objects.all().order_by('name')
    links      = (
        Link.objects.filter(politician=politician).order_by('type__name'))

    return render(request, 'core/edit/links.html', {
        'links'      : links,
        'link_types' : types,
        'politician' : politician,
        'error'      : error,
        'input'      : url,
        'link_type'  : link_type,
    })
示例#5
0
def politician_link_add_view(request, unique_key):
    politician = get_object_or_404(Politician, unique_key=unique_key)
    link_type  = get_object_or_404(LinkType, id=request.POST.get('link_type'))
    url        = request.POST.get('url')
    error      = False

    if url.startswith(('http://', 'https://')) and '.' in url:
        l = Link(
            type=link_type,
            politician=politician,
            url=url
        )
        l.save()
        url = ''
    else:
        error = True

    types      = LinkType.objects.all().order_by('name')
    links      = Link.objects.filter(politician=politician).order_by('type__name')

    return render(request, 'core/edit/links.html', {
        'links'      : links,
        'link_types' : types,
        'politician' : politician,
        'error'      : error,
        'input'      : url,
        'link_type'  : link_type,
    })
def import_link(user: User, link: str):
    try:
        new_url = Link(original_link=link, user=user)
        new_url.save()
        message = f'Successfully saved link="{link}" (id="{new_url.id}")'
        logger.info(message)
    except Exception as ex:
        message = f'Exception trying to save link="{link}": {ex}'
        logger.error(message)
示例#7
0
    def test_delete_old_records(self):

        Link.delete_old_records(minutes=5)

        self.assertEqual(Link.objects.filter(id=1).exists(),
                         True,
                         msg='Deleted not old record.')
        self.assertEqual(Link.objects.filter(id=2).exists(),
                         False,
                         msg='Old record not deleted.')
示例#8
0
 def post(self, request):
     validate_resp = validate_data(self.request.data)
     if validate_resp.status_code is not 200:
         return validate_resp
     links = transform_data(validate_resp.data)
     for link in links:
         try:
             model = Link(link=link)
             model.save()
         except BaseException as e:
             return Response(data={'status': '{}'.format(e)},
                             status=status.HTTP_500_INTERNAL_SERVER_ERROR)
     return Response(data={'status': 'ok'}, status=status.HTTP_201_CREATED)
示例#9
0
    def test_creating_link_without_link_or_description_on_page(self):
        '''
        Creating a link without the link or descrption being part of the page.
        '''
        responses.add(responses.GET,
                      'http://example.com',
                      body='',
                      status=200,
                      content_type='text/html')

        l = Link(user=self.user, url='http://example.com')
        l.save()

        title = ''
        self.assertEquals(title, l.title)
        description = ''
        self.assertEquals(description, l.description)
示例#10
0
    def test_creating_link_with_404_url(self):
        '''
        Creating a link with URL that 404s
        '''
        responses.add(responses.GET,
                      'http://example.com',
                      body='',
                      status=404,
                      content_type='text/html')

        l = Link(user=self.user, url='http://example.com')
        l.save()

        title = ''
        self.assertEquals(title, l.title)
        description = ''
        self.assertEquals(description, l.description)
示例#11
0
    def test_creating_link_without_title_or_description(self):
        '''
        Test the creation of a Link without a title or description passed as an
        argument. Expect that the website has a description and title.
        '''
        body = '''
        <title>Example Title</title>
        <meta content="An example description" name="description">
        '''
        responses.add(responses.GET,
                      'http://example.com',
                      body=body,
                      status=200,
                      content_type='text/html')

        l = Link(user=self.user, url='http://example.com')
        l.save()

        title = 'Example Title'
        self.assertEquals(title, l.title)
        description = 'An example description'
        self.assertEquals(description, l.description)
示例#12
0
    def handle(self, *args, **kwargs):  # pylint: disable=unused-argument
        User = get_user_model()
        User.objects.count()

        user_data = {
            'username': '******',
            'password': '******',
            'email': '*****@*****.**',
        }
        new_user = User(**user_data)
        new_user.save()

        User.objects.all()
        tiago = User.objects.first()

        Link.objects.count()
        tiago_url = Link(name='autotest',
                         original_link='https://www.osnews.com',
                         user=tiago)
        tiago_url.save()

        must_have_values = ['shortened_hash', 'sanitized_link']

        success = True

        for value in must_have_values:
            if not getattr(tiago_url, value):
                self.stderr.write(
                    f'Missing value for {value}. '
                    f'The django signal was probably not called.')
                success = False

        if success:
            self.stdout.write(f'SUCCESS! Object properties={vars(tiago_url)}')

        # Cascadingly deletes the created user and all its Links,
        # including the one created here.
        User.objects.get(id=tiago.id).delete()
示例#13
0
 def get(self, request):
     validator = validate_filter(dict(self.request.GET))
     if validator.status_code is not 200:
         return validator
     qs = Link.filter_qs(validator.data)
     if len(qs) == 0:
         return Response(
             data={'status': 'Does not match query with yours parameters'},
             status=status.HTTP_204_NO_CONTENT)
     return Response(data={
         'domains': list(set([link.link for link in qs])),
         'status': 'ok'
     },
                     status=status.HTTP_200_OK)
示例#14
0
def register_link(request):
    if request.method == 'POST':
        url = request.POST['url']
        shorten = Link(url=url)
        shorten.save()
        shorten.shorten_url = (short_url.encode_url(shorten.id))
        shorten.save()

        full_path = "https://" + request.get_host() + "/" + shorten.shorten_url
        data = {
            'url_registered': full_path,
        }
        return JsonResponse(data, safe=False)
示例#15
0
 def handle(self, *args, **options):
     Link.delete_old_records()
示例#16
0
 def setUp(self):
     self.link = Link(url="http://www.globoesporte.globo.com/")
示例#17
0
class ShortenTest(TestCase):
    """
    ShortenTest - shorten view tests
    """
    def setUp(self):
        self.link = Link(url="http://www.globoesporte.globo.com/")

    def test_get(self):
        """
        AJAX POST /short should return 200
        """
        data = {'url': 'www.google.com'}
        kwargs = {'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'}

        resp = client.get(r('core:shorten'), data, **kwargs)

        self.assertEqual(200, resp.status_code)

    def test_url_shortened_valid_url(self):
        """
        Should not contain an `error` in the response
        """
        data = {'url': 'www.google.com'}
        kwargs = {'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'}

        resp = client.get(r('core:shorten'), data=data, **kwargs)

        o = json.loads(resp.content, encoding='utf8')

        self.assertNotIn('error', o)

    def test_url_shortened_invalid_url(self):
        """
        The url must be invalid
        """
        data = {'url': 'www.#$$%$#$.com'}
        kwargs = {'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'}

        resp = client.get(r('core:shorten'), data=data, **kwargs)

        o = json.loads(resp.content, encoding='utf8')

        self.assertIn('error', o)

    def test_url_shortened_url_required(self):
        """
        URL is required
        """
        data = {'url': ''}
        kwargs = {'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'}

        resp = client.get(r('core:shorten'), data=data, **kwargs)

        o = json.loads(resp.content, encoding='utf8')

        self.assertIn('error', o)

    def test_url_shortened_must_be_unique(self):
        """
        The url shortened must be an unique url, if the user to shorten the same url
        and it exists on database, must return it
        """
        self.link.save()

        url = {}
        url['shortened_url'] = '{0}{1}'.format(settings.BASE_URL, 1)

        data = {'url': 'www.globoesporte.globo.com'}
        kwargs = {'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'}

        resp = client.get(r('core:shorten'), data=data, **kwargs)

        o = json.loads(resp.content, encoding='utf8')

        self.assertDictContainsSubset(url, o)