class TestStatsView(TestCase): def setUp(self): self.url = Url(long_url='https://www.youtube.com/watch?v=bnVUHWCynig', session=Session(pk=self.client.session.session_key)) url2 = Url(long_url='https://www.youtube.com/watch?v=cSLAO7zxS2M', session=Session(pk=self.client.session.session_key)) self.url.save() url2.save() self.stats = [ Statistics(ip_address='0.0.0.0', time=datetime.now(), referer='0.0.0.0', url=self.url), Statistics(ip_address='172.16.0.0', time=datetime.now(), url=self.url), Statistics(ip_address='172.16.0.0', time=datetime.now(), url=url2) ] for stat in self.stats: stat.save() def test_get(self): resp = self.client.get('/stats/{}'.format(self.url.id)) data = json.loads(resp.content) data = list(serializers.deserialize('json', data)) self.assertEqual(len(data), 2)
class TestUrlRootView(TestCase): def setUp(self): self.url = Url(long_url='https://www.youtube.com/watch?v=bnVUHWCynig', session=Session(pk=self.client.session.session_key)) self.url.save() def test_valid_redirect(self): resp = self.client.get('/{}/'.format(self.url.url_hash)) self.assertEqual(resp.url, self.url.long_url)
def post(self, request): form = UrlForm(request.POST) if form.is_valid(): long_url = form.cleaned_data['long_url'] session = Session.objects.get(pk=request.session.session_key) url = Url(long_url=long_url, session=session) url.save() return HttpResponseRedirect(self.request.path_info) return HttpResponse(status=400)
class TestUrlModel(TestCase): def setUp(self): engine = import_module(settings.SESSION_ENGINE) store = engine.SessionStore() store.save() self.url = Url(long_url='https://www.youtube.com/watch?v=cSLAO7zxS2M', session=Session(pk=store.session_key)) self.url.save() def test_hash_url_was_saved(self): self.assertNotEqual(self.url.url_hash, None)
def create_url(): json = request.get_json() try: data = UrlSchema().load(json) except ValidationError as e: return jsonify(error="validation failed", fields=e.messages), 422 if data.get("short_url"): if Url.exists(short_url=data["short_url"]): return jsonify(error="duplicate url"), 422 url = Url(**data) url.short_url = data.get("short_url") db.session.add(url) db.session.commit() return jsonify(UrlSchema().dump(url))
def delete(url_id): url = Url.get(url_id) if not url: return jsonify(error="object not found"), 404 db.session.delete(url) db.session.commit() return jsonify(url.id), 200
def setUp(self): engine = import_module(settings.SESSION_ENGINE) self.store = engine.SessionStore() self.store.save() self.user1_urls = [ Url(long_url='https://www.youtube.com/watch?v=cSLAO7zxS2M', session=Session(pk=self.client.session.session_key)), Url(long_url='https://www.youtube.com/watch?v=bnVUHWCynig', session=Session(pk=self.client.session.session_key)) ] self.user2_url = Url( long_url='https://www.youtube.com/watch?v=TRRfi3yOT8g', session=Session(pk=self.store.session_key)) for url in self.user1_urls: url.save() self.user2_url.save()
def read(url_id): url = Url.get(url_id) if not url: return jsonify(error="object not found"), 404 # TODO: Move to celery worker # url.visits += 1 # db.session.commit() return jsonify(UrlSchema().dump(url))
class TestUrlView(TestCase): def setUp(self): engine = import_module(settings.SESSION_ENGINE) self.store = engine.SessionStore() self.store.save() self.user1_urls = [ Url(long_url='https://www.youtube.com/watch?v=cSLAO7zxS2M', session=Session(pk=self.client.session.session_key)), Url(long_url='https://www.youtube.com/watch?v=bnVUHWCynig', session=Session(pk=self.client.session.session_key)) ] self.user2_url = Url( long_url='https://www.youtube.com/watch?v=TRRfi3yOT8g', session=Session(pk=self.store.session_key)) for url in self.user1_urls: url.save() self.user2_url.save() def test_different_users(self): resp = self.client.get(reverse('url_view')) self.assertEqual(len(resp.context['urls']), 2) def test_valid_response(self): resp = self.client.get(reverse('url_view')) self.assertEqual(resp.status_code, 200) self.assertTrue('urls' in resp.context) self.assertEqual(resp.context['root'], 'http://127.0.0.1:8000/') self.assertTrue(self.user1_urls[0] in resp.context['urls']) def test_post_success(self): data = { "long_url": 'https://www.youtube.com/watch?v=bnVUHWCynig&list=RDbnVUHWCynig&start_radio=1', "session": Session(pk=self.client.session.session_key) } resp = self.client.post(reverse('url_view'), data) self.assertEqual(resp.status_code, 302) def test_post_failure(self): data = { "long_url": 'not_an_url', "session": Session(pk=self.client.session.session_key) } resp = self.client.post(reverse('url_view'), data) self.assertEqual(resp.status_code, 400)
def create_shorturl(request, secret): """Creates a short url.""" if (not hasattr(settings, 'URLSHORTENER_SECRET') or secret != settings.URLSHORTENER_SECRET): return HttpResponseForbidden() url = request.GET.get('u') or '' if not url.startswith('http'): url = 'http://%s' % url validate = URLValidator(verify_exists=True) try: validate(url) except ValidationError: return HttpResponseBadRequest() try: url_obj = Url.objects.get(url=url) except Url.DoesNotExist: url_obj = Url(url=url) url_obj.save() return HttpResponse(get_link(url_obj.shortid, request))
def get_qr_code(url_id): """Generates QR Code for the given url_id, if request parameter direct is set to 'true', then generates QR directly for desired url, otherwise, uses shortcuts.redirect """ url = Url.get(url_id) if not url: return jsonify(error="object not found"), 404 if request.args.get("direct") == "true": data = url.long_url else: data = url_for('shortcuts.redirect_short_url', short_url=url.short_url, _external=True) qr = generate_qr_code(data) response = make_response(send_file(qr, mimetype="image/png")) # response.headers['Content-Transfer-Encoding'] = 'base64' return response
def setUp(self): self.url = Url(long_url='https://www.youtube.com/watch?v=bnVUHWCynig', session=Session(pk=self.client.session.session_key)) url2 = Url(long_url='https://www.youtube.com/watch?v=cSLAO7zxS2M', session=Session(pk=self.client.session.session_key)) self.url.save() url2.save() self.stats = [ Statistics(ip_address='0.0.0.0', time=datetime.now(), referer='0.0.0.0', url=self.url), Statistics(ip_address='172.16.0.0', time=datetime.now(), url=self.url), Statistics(ip_address='172.16.0.0', time=datetime.now(), url=url2) ] for stat in self.stats: stat.save()
def setUp(self): engine = import_module(settings.SESSION_ENGINE) store = engine.SessionStore() store.save() self.url = Url(long_url='https://www.youtube.com/watch?v=cSLAO7zxS2M', session=Session(pk=store.session_key)) self.url.save()
def setUp(self): self.url = Url(long_url='https://www.youtube.com/watch?v=bnVUHWCynig', session=Session(pk=self.client.session.session_key)) self.url.save()
def example_url(): url = Url() url.long_url = "https://www.google.com/" url.short_url = None return url
def _list(): urls = Url.query().order_by(desc("created")) return jsonify(urls=UrlSchema().dump(urls, many=True))
def remove_expired_urls(): logger.info("Deleting outdated urls") Url.query().filter(Url.expires_at <= datetime.utcnow()).delete() db.session.commit()
def increment_url_visits(short_url): url = Url.query(short_url=short_url).first() logger.info(f"Increasing visits on {url.id}") url.visits += 1 db.session.commit()