Ejemplo n.º 1
0
    def test_generate_args_output(self):
        prefix = 'work4'

        # Generate a link that won't appear in the results (wrong prefix)
        Link.shorten(long_url='http://www.work4labs.com',
                     prefix='work4labs').save()
        # Generate the link that will be used in the output
        link = Link.shorten(long_url='http://www.work4labs.com',
                            prefix=prefix).save()

        header_row = 'hash,long_url,nb_of_clicks'
        first_row = '%s,%s,0' % (link.hash, link.long_url)

        with io.BytesIO() as stdout, io.BytesIO() as stderr:
            management.call_command('urlstats',
                                    prefix,
                                    stdout=stdout,
                                    stderr=stderr)

            stdout.seek(0)
            stderr.seek(0)

            self.assertEqual(stderr.read(), '')
            self.assertEqual(stdout.read(),
                             '%s\r\n%s\r\n' % (header_row, first_row))
Ejemplo n.º 2
0
    def test_shorten_multiple(self):
        # Generate a couple of links that we should *not* fall on
        Link.shorten("http://www.work4labs.com/", prefix="foobarblah")
        Link.shorten("http://www.work4labs.com/", prefix="fooba")

        link1 = Link.shorten("http://www.work4labs.com/", prefix="foobar")
        self.assertIn("foobar/", link1.hash)
Ejemplo n.º 3
0
    def test_find_for_p_and_l_u(self):
        prefix = "ole"
        long_url = "http://www.work4labs.com/"

        Link.shorten(long_url, prefix=prefix)

        self.assertEqual(
            Link.find_for_prefix_and_long_url(prefix, long_url).explain()["cursor"], "BtreeCursor long_url_hashed"
        )
Ejemplo n.º 4
0
    def shorten_twice(self, **kwargs):
        kwargs["long_url"] = "http://www.work4labs.com/"

        # statsd.histogram should only be created at creation
        with patch("django_short_urls.models.statsd") as mock_statsd:
            link1 = Link.shorten(**kwargs)
            mock_statsd.histogram.assert_called_once()
            link2 = Link.shorten(**kwargs)
            mock_statsd.histogram.assert_called_once()

        self.assertEqual(link1.hash, link2.hash)
Ejemplo n.º 5
0
    def find_for_prefix(self, prefix):
        # First check that there are no links for this prefix
        self.assertEqual(len(Link.find_for_prefix(prefix)), 0)

        # Create a link with this prefix and another with another prefix
        true_link = Link.shorten("http://www.work4labs.com/", prefix=prefix)

        # other link
        Link.shorten("http://www.work4labs.com/", prefix="other_%s" % prefix)

        # We should only find the true link
        links = Link.find_for_prefix(prefix)

        self.assertEqual(len(links), 1)
        self.assertEqual(links.first().hash, true_link.hash)
Ejemplo n.º 6
0
    def setUp(self):
        self.setting_backup = settings.SITE_READ_ONLY

        settings.SITE_READ_ONLY = True

        self.factory = RequestFactory()

        self.path = 'test42'
        self.link = Link.shorten('http://www.work4.com/jobs', short_path=self.path)
Ejemplo n.º 7
0
    def test_generate_args_output(self, mock_statsd):  # pylint: disable=unused-argument
        prefix = 'work4'

        # Generate a link that won't appear in the results (wrong prefix)
        Link.shorten(long_url='http://www.work4labs.com', prefix='work4labs').save()
        # Generate the link that will be used in the output
        link = Link.shorten(long_url='http://www.work4labs.com', prefix=prefix).save()

        header_row = 'hash,long_url,nb_of_clicks'
        first_row = '%s,%s,0' % (link.hash, link.long_url)

        with io.BytesIO() as stdout, io.BytesIO() as stderr:
            management.call_command('urlstats', prefix, stdout=stdout, stderr=stderr)

            stdout.seek(0)
            stderr.seek(0)

            self.assertEqual(stderr.read(), '')
            self.assertEqual(stdout.read(), '%s\r\n%s\r\n' % (header_row, first_row))
Ejemplo n.º 8
0
    def setUp(self):
        self.setting_backup = settings.SITE_READ_ONLY

        settings.SITE_READ_ONLY = True

        self.factory = RequestFactory()

        self.path = 'test42'
        self.link = Link.shorten('http://www.work4.com/jobs',
                                 short_path=self.path)
Ejemplo n.º 9
0
def new(request):
    '''
    Create a new short url based on the POST parameters
    '''

    if 'login' in request.REQUEST and 'api_key' in request.REQUEST:
        login = request.REQUEST['login']
        api_key = request.REQUEST['api_key']

        user = User.objects(login=login, api_key=api_key).first()
    else:
        user = None

    if user is None:
        return response(status=HTTP_UNAUTHORIZED,
                        message="Invalid credentials.")

    params = {}

    if 'long_url' in request.REQUEST:
        params['long_url'] = request.REQUEST['long_url']

        (is_valid, error_message) = validate_url(params['long_url'])
    else:
        (is_valid, error_message) = (False, "Missing parameter: 'long_url'")

    if not is_valid:
        return response(status=HTTP_BAD_REQUEST, message=error_message)

    for key in ['short_path', 'prefix']:
        if key in request.REQUEST:
            params[key] = request.REQUEST[key]

            if '/' in params[key]:
                return response(status=HTTP_BAD_REQUEST,
                                message="%s may not contain a '/' character." %
                                key)

    try:
        link = Link.shorten(**params)

        getLogger('app').info('Successfully shortened %s into %s for user %s',
                              link.long_url, link.hash, login)
    except ShortPathConflict, err:
        del params['short_path'], params['long_url']

        if 'prefix' in params:
            del params['prefix']

        params['hash'] = err.link.hash

        return response(status=HTTP_CONFLICT, message=str(err), **params)
Ejemplo n.º 10
0
def new(request):
    '''
    Create a new short url based on the POST parameters
    '''

    if 'login' in request.REQUEST and 'api_key' in request.REQUEST:
        login = request.REQUEST['login']
        api_key = request.REQUEST['api_key']

        user = User.objects(login=login, api_key=api_key).first()
    else:
        user = None

    if user is None:
        return response(status=HTTP_UNAUTHORIZED, message="Invalid credentials.")

    params = {}

    if 'long_url' in request.REQUEST:
        params['long_url'] = request.REQUEST['long_url']

        (is_valid, error_message) = validate_url(params['long_url'])
    else:
        (is_valid, error_message) = (False, "Missing parameter: 'long_url'")

    if not is_valid:
        return response(status=HTTP_BAD_REQUEST, message=error_message)

    allow_slashes_in_prefix = 'allow_slashes_in_prefix' in request.REQUEST

    for key in ['short_path', 'prefix']:
        if key in request.REQUEST:
            params[key] = request.REQUEST[key]

            if '/' in params[key] and not (key == 'prefix' and allow_slashes_in_prefix):
                return response(
                    status=HTTP_BAD_REQUEST,
                    message="%s may not contain a '/' character." % key)

    try:
        link = Link.shorten(**params)

        getLogger('app').info('Successfully shortened %s into %s for user %s', link.long_url, link.hash, login)
    except ShortPathConflict, err:
        del params['short_path'], params['long_url']

        if 'prefix' in params:
            del params['prefix']

        params['hash'] = err.link.hash

        return response(status=HTTP_CONFLICT, message=str(err), **params)
Ejemplo n.º 11
0
def new(request):
    """Create a new short url based on the POST parameters"""
    long_url = request.GET.get('long_url')

    if long_url is None:
        is_valid, error_message = False, "Missing GET parameter: 'long_url'"
    else:
        is_valid, error_message = validate_url(long_url)

    if not is_valid:
        return pyw4c_response(status=HTTP_BAD_REQUEST, message=error_message)

    params = {}

    for key in ['short_path', 'prefix']:
        params[key] = request.GET.get(key)

        if key == 'prefix' and 'allow_slashes_in_prefix' in request.GET:
            continue

        if params[key] is not None and '/' in params[key]:
            return pyw4c_response(
                status=HTTP_BAD_REQUEST,
                message="%s may not contain a '/' character." % key)

    statsd.increment(
        'workforus.new',
        tags=['prefix:' + unicode(params['prefix']), 'is_secure:' + unicode(request.is_secure())])

    try:
        link = Link.shorten(long_url, **params)

        getLogger('app').info(
            'Successfully shortened %s into %s for user %s',
            link.long_url, link.hash, request.user.login)
    except ShortPathConflict, err:
        del params['short_path'], long_url
        del params['prefix']

        params['hash'] = err.hash

        return pyw4c_response(status=HTTP_CONFLICT, message=str(err), **params)
Ejemplo n.º 12
0
 def test_shorten_with_short_path(self):
     link = Link.shorten("http://www.work4labs.com/", short_path="FooBar")
     self.assertEqual(link.hash, "foobar")
Ejemplo n.º 13
0
    def test_shorten(self):
        link = Link.shorten("http://www.work4labs.com/")

        self.assertIn("work4labs", str(link))

        self.assertNotIn("/", link.hash)
Ejemplo n.º 14
0
    def test_prefix(self):
        self.assertEqual(Link.shorten(self.URL).prefix, "")

        prefix = "foo"
        self.assertEqual(Link.shorten(self.URL, prefix=prefix).prefix, prefix)
Ejemplo n.º 15
0
    def setUp(self):
        self.factory = RequestFactory()

        self.path = 'test42'
        self.link = Link.shorten('http://www.work4.com/jobs', short_path=self.path)
Ejemplo n.º 16
0
def _shorten(*args, **kwargs):
    with patch('django_short_urls.models.statsd') as mock_statsd:
        return Link.shorten(*args, **kwargs), mock_statsd