def process_response(self, request, response): if response.status_code < 400 and settings.REQUEST_ONLY_ERRORS: return response allow = patterns(True, *settings.REQUEST_ALLOW_PATHS) if not allow.resolve(request.path[1:]): return response ignore = patterns(False, *settings.REQUEST_IGNORE_PATHS) if ignore.resolve(request.path[1:]): return response if request.is_ajax() and settings.REQUEST_IGNORE_AJAX: return response if request.META.get('REMOTE_ADDR') in settings.REQUEST_IGNORE_IP: return response if getattr(request, 'user', False): if request.user.username in settings.REQUEST_IGNORE_USERNAME: return response r = Request() r.from_http_request(request, response) return response
class GetAllLibrariesAdminTest(TestCase): _is_staff = True def setUp(self): user = User.objects.create_user( email='*****@*****.**', password='******', is_staff=self._is_staff, ) user.save() library = Library.get_test_library('Library') sample = Sample.get_test_sample('Sample') library.save() sample.save() self.request = Request(user=user) self.request.save() self.request.libraries.add(library) self.request.samples.add(sample) def test_get_all(self): self.client.login(email='*****@*****.**', password='******') response = self.client.get(reverse('library.get_all')) self.assertEqual(response.status_code, 200) self.assertNotEqual(response.content, b'[]') def test_wrong_http_method(self): self.client.login(email='*****@*****.**', password='******') response = self.client.post(reverse('library.get_all')) self.assertEqual(response.status_code, 200) self.assertEqual(response.content, b'[]')
def process_response(self, request, response): if request.method.lower() not in settings.REQUEST_VALID_METHOD_NAMES: return response if response.status_code < 400 and settings.REQUEST_ONLY_ERRORS: return response ignore = patterns(False, *settings.REQUEST_IGNORE_PATHS) if ignore.resolve(request.path[1:]): return response if request.is_ajax() and settings.REQUEST_IGNORE_AJAX: return response if request.META.get('REMOTE_ADDR') in settings.REQUEST_IGNORE_IP: return response ignore = patterns(False, *settings.REQUEST_IGNORE_USER_AGENTS) if ignore.resolve(request.META.get('HTTP_USER_AGENT', '')): return response if getattr(request, 'user', False): if request.user.username in settings.REQUEST_IGNORE_USERNAME: return response r = Request() r.from_http_request(request, response) return response
class PoolInfo(TestCase): def setUp(self): user = User.objects.create_user(email='*****@*****.**', password='******') pool = Pool(name='_Foo', user=user) pool.save() library_1 = Library.get_test_library('Library1') library_2 = Library.get_test_library('Library2') library_1.save() library_2.save() sample_1 = Sample.get_test_sample('Sample1') sample_2 = Sample.get_test_sample('Sample2') sample_1.save() sample_2.save() pool.libraries.add(library_1) pool.samples.add(sample_1) self.request = Request(user=user) self.request.save() self.request.libraries.add(*[library_1, library_2]) self.request.samples.add(*[sample_1, sample_2]) def test_pool_info(self): self.client.login(email='*****@*****.**', password='******') response = self.client.get(reverse('pool_info'), {'pool_id': 1}) self.assertNotEqual(response.content, b'[]') self.assertEqual(response.status_code, 200)
def process_response(self, request, response): if request.method.lower() not in settings.VALID_METHOD_NAMES: return response if response.status_code < 400 and settings.ONLY_ERRORS: return response ignore = patterns(False, *settings.IGNORE_PATHS) if ignore.resolve(request.path[1:]): return response if request.is_ajax() and settings.IGNORE_AJAX: return response if request.META.get('REMOTE_ADDR') in settings.IGNORE_IP: return response ignore = patterns(False, *settings.IGNORE_USER_AGENTS) if ignore.resolve(request.META.get('HTTP_USER_AGENT', '')): return response if getattr(request, 'user', False): if request.user.username in settings.IGNORE_USERNAME: return response r = Request() r.from_http_request(request, response) return response
def test_from_http_request_not_commit(self): http_request = HttpRequest() http_request.method = 'GET' request = Request() request.from_http_request(http_request, commit=False) self.assertIsNone(request.id)
def test_from_http_request_with_user(self): http_request = self.factory.get('/') http_request.user = get_user_model().objects.create(username='******') request = Request() request.from_http_request(http_request, commit=False) self.assertEqual(request.user.id, http_request.user.id)
def process_response(self, request, response): if request.method.lower() not in settings.REQUEST_VALID_METHOD_NAMES: return response if response.status_code < 400 and settings.REQUEST_ONLY_ERRORS: return response ignore = patterns(False, *settings.REQUEST_IGNORE_PATHS) if ignore.resolve(request.path[1:]): return response if request.is_ajax() and settings.REQUEST_IGNORE_AJAX: return response if get_remote_addr(request) in settings.REQUEST_IGNORE_IP: return response if getattr(request, 'user', False): if request.user.username in settings.REQUEST_IGNORE_USERNAME: return response r = Request() r.from_http_request(request, response) return response
def setUpClass(cls): super(GraphsTestCase, cls).setUpClass() cls.factory = RequestFactory() Request(path="/admin/", ip="127.0.0.1").save() Request(path="/admin/", ip="127.0.0.1").save() Request(path="/admin/login/", ip="127.0.0.1").save() staff_user = User.objects.create_user(username="******", password="******") staff_user.is_staff = True staff_user.save() cls.staff_user = staff_user cls.coordinator = EditorFactory(user__email="*****@*****.**").user coordinators = get_coordinators() coordinators.user_set.add(cls.coordinator) user = UserFactory() cls.user = user cls.partner = PartnerFactory() cls.app = ApplicationFactory(partner=cls.partner) cls.app.status = Application.APPROVED cls.app.save() cls.dashboard_url = reverse("dashboard")
def test_from_http_request_with_user(self): http_request = HttpRequest() http_request.method = 'GET' http_request.user = get_user_model().objects.create(username='******') request = Request() request.from_http_request(http_request, commit=False) self.assertEqual(request.user.id, http_request.user.id)
def test_from_http_request_with_user(self): http_request = HttpRequest() http_request.method = 'GET' http_request.user = User.objects.create(username='******') request = Request() request.from_http_request(http_request) self.assertEqual(request.user.id, http_request.user.id)
def setUp(self): self.user = self.create_user('*****@*****.**', 'foo-foo') self.client.login(email='*****@*****.**', password='******') self.sample = create_sample(self._get_random_name()) self.request = Request(user=self.user) self.request.save() self.request.samples.add(self.sample)
def test_from_http_request_redirection(self): http_request = HttpRequest() http_request.method = 'GET' http_response = HttpResponse(status=301) http_response['Location'] = '/foo' request = Request() request.from_http_request(http_request, http_response) self.assertEqual(request.redirect, '/foo')
def test_from_http_request_redirection(self): http_request = self.factory.get('/') http_response = HttpResponse(status=301) http_response['Location'] = '/foo' request = Request() request.from_http_request(http_request, http_response, commit=False) self.assertEqual(request.redirect, '/foo')
def test_from_http_request_redirection(self): http_request = HttpRequest() http_request.method = 'GET' http_response = HttpResponse(status=301) http_response['Location'] = '/foo' request = Request() request.from_http_request(http_request, http_response, commit=False) self.assertEqual(request.redirect, '/foo')
def test_from_http_request_with_user(self): http_request = HttpRequest() http_request.method = 'GET' http_request.user = User.objects.create(username='******') http_request.META['REMOTE_ADDR'] = '32.64.128.16' request = Request() request.from_http_request(http_request) self.assertEqual(request.user.id, http_request.user.id)
def setUp(self): user = User.objects.create_user( email='*****@*****.**', password='******', is_staff=True, ) user.save() self.request = Request(user=user) self.request.save()
def test_browser_detection_with_no_path(self): request = Request( user_agent= 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:43.0) Gecko/20100101 Firefox/43.0' ) self.assertEqual(request.browser, 'Firefox') request = Request( user_agent= 'Mozilla/5.0 (compatible; MSIE 9.0; America Online Browser 1.1; Windows NT 5.0)' ) self.assertEqual(request.browser, 'AOL')
def test_from_http_request_redirection(self): http_request = HttpRequest() http_request.method = 'GET' http_request.META['HTTP_USER_AGENT'] = 'test user agent' http_request.META['REMOTE_ADDR'] = '32.64.128.16' http_response = HttpResponse(status=301) http_response['Location'] = '/foo' request = Request() request.from_http_request(http_request, http_response) self.assertEqual(request.redirect, '/foo')
def create_interview(request): positions = PositionAll.objects.all() existing_order = get_user_pending_order(request) cart_amount = '' if existing_order!=0: cart_amount = existing_order.items.all().count() else: return redirect(reverse('candidate_cart:order_summary')) if request.method == 'POST': request_id = generate_request_id() request_title = request.POST.get('request_title') date_interview = request.POST.get('date_interview') note_interview = request.POST.get('note_interview') request_position_id = request.POST.get('request_position') request_position_other = request.POST.get('request_position_other_name') print(request_position_id,"||||||||||",request_position_other) request_position = get_object_or_404(PositionAll, position_id=request_position_id) user_profile = get_object_or_404(Profile, user=request.user) user_order = Order.objects.get(owner=user_profile, is_ordered=False) status = get_object_or_404(Status, status_id='1') request_type = get_object_or_404(RequestType, request_type_id='2') existing_order = get_user_pending_order(request) if existing_order!=0: request_interview = RequestInterview(order = user_order,date_interview = date_interview,note_interview =note_interview) request_interview.save() request_detail = Request(request_id=request_id,request_type=request_type,request_interview=request_interview,request_title=request_title,request_position=request_position,request_position_other=request_position_other,owner=user_profile,status=status) request_detail.save() # context = { # 'order': existing_order, # 'Cart_amount': cart_amount, # } # # return render(request, 'create-interview.html', context) return redirect(reverse('candidate_cart:update_interview', kwargs={ 'order_id': user_order.ref_code }) ) context = { 'Positions' : positions, 'order': existing_order, 'Cart_amount': cart_amount, } return render(request, 'create-interview.html', context)
def setUpClass(cls): super(GraphsTestCase, cls).setUpClass() cls.factory = RequestFactory() Request(path='/admin/', ip='127.0.0.1').save() Request(path='/admin/', ip='127.0.0.1').save() Request(path='/admin/login/', ip='127.0.0.1').save() user = User.objects.create_user(username='******', password='******') user.is_staff = True user.save() cls.staff_user = user
def create_library_preparation_obj(sample_name, user, sample_status): sample = create_sample(sample_name, status=sample_status) sample.save() request = Request(user=user) request.save() request.samples.add(sample) pool = create_pool(user) pool.samples.add(sample) return LibraryPreparation.objects.get(sample=sample)
def process_response(self, request, response): if response.status_code < 400 and settings.REQUEST_ONLY_ERRORS: return response ignore = patterns(False, *settings.REQUEST_IGNORE_PATHS) if ignore.resolve(request.path[1:]): return response if request.is_ajax() and settings.REQUEST_IGNORE_AJAX: return response if request.META.get('REMOTE_ADDR') in settings.REQUEST_IGNORE_IP: return response if getattr(request, 'user', False): if request.user.username in settings.REQUEST_IGNORE_USERNAME: return response if not getattr(request, 'session', None): return response r = Request() now = datetime.datetime.now() path = request.path if path[len(path)-1] != '/': path = path + '/' if path in settings.REQUEST_ALWAYS_INSERT_FROM_URLS: try: request.session['last_request_log'] = now except: pass r.from_http_request(request, response, commit=False) record_request(r) return response try: last_log = request.session['last_request_log'] if settings.REQUEST_USER_TRACKING_LOGAGAIN_DELAY: last_log_limit = last_log + \ settings.REQUEST_USER_TRACKING_LOGAGAIN_DELAY if now < last_log_limit : return response except KeyError: pass request.session['last_request_log'] = now r.from_http_request(request, response, commit=False) record_request(r) return response
def test_from_http_request(self): http_request = HttpRequest() http_request.method = 'PATCH' http_request.path = '/kylef' http_request.META['REMOTE_ADDR'] = '32.64.128.16' http_response = HttpResponse(status=204) request = Request() request.from_http_request(http_request, http_response, commit=False) self.assertEqual(request.path, '/kylef') self.assertEqual(request.method, 'PATCH') self.assertEqual(request.ip, '32.64.128.16') self.assertEqual(request.response, 204)
def process_response(self, request, response): if request.is_ajax() and settings.REQUEST_IGNORE_AJAX: return response if request.META.get('REMOTE_ADDR') in settings.REQUEST_IGNORE_IP: return response if getattr(request, 'user', False): if request.user.username in settings.REQUEST_IGNORE_USERNAME: return response r = Request() r.from_http_request(request, response) return response
def setUp(self): user = self.create_user() self.create_user('*****@*****.**', 'test', False) # non-staff user # Submission completed self.library1 = create_library(self._get_random_name(), status=1) self.sample1 = create_sample(self._get_random_name(), status=1) self.sample2 = create_sample(self._get_random_name(), status=1) # Failed library self.library2 = create_library(self._get_random_name(), status=-1) self.request = Request(user=user) self.request.save() self.request.libraries.add(*[self.library1, self.library2]) self.request.samples.add(*[self.sample1, self.sample2])
class GetAllLibraries(TestCase): def setUp(self): user = User.objects.create_user( email='*****@*****.**', password='******', is_staff=True, ) user.save() self.request = Request(user=user) self.request.save() def test_get_all(self): self.client.login(email='*****@*****.**', password='******') library = Library.get_test_library('Library1') library.status = 1 library.save() sample = Sample.get_test_sample('Sample1') sample.status = 1 sample.save() self.request.libraries.add(library) self.request.samples.add(sample) response = self.client.get(reverse('library.get_all'), { 'quality_check': 'true' }) self.assertEqual(response.status_code, 200) self.assertNotEqual(response.content, b'[]') def test_get_all_empty(self): self.client.login(email='*****@*****.**', password='******') library = Library.get_test_library('Library2') library.save() sample = Sample.get_test_sample('Sample2') sample.save() self.request.libraries.add(library) self.request.samples.add(sample) response = self.client.get(reverse('library.get_all'), { 'quality_check': 'true' }) self.assertEqual(response.status_code, 200) self.assertEqual(response.content, b'[]')
class GetAllLibraries(TestCase): def setUp(self): user = User.objects.create_user( email='*****@*****.**', password='******', is_staff=True, ) user.save() self.request = Request(user=user) self.request.save() def test_get_all(self): self.client.login(email='*****@*****.**', password='******') library = Library.get_test_library('Library1') library.status = 1 library.save() sample = Sample.get_test_sample('Sample1') sample.status = 1 sample.save() self.request.libraries.add(library) self.request.samples.add(sample) response = self.client.get(reverse('library.get_all'), {'quality_check': 'true'}) self.assertEqual(response.status_code, 200) self.assertNotEqual(response.content, b'[]') def test_get_all_empty(self): self.client.login(email='*****@*****.**', password='******') library = Library.get_test_library('Library2') library.save() sample = Sample.get_test_sample('Sample2') sample.save() self.request.libraries.add(library) self.request.samples.add(sample) response = self.client.get(reverse('library.get_all'), {'quality_check': 'true'}) self.assertEqual(response.status_code, 200) self.assertEqual(response.content, b'[]')
def create_pooling_object(user, save=True, add_library=False, add_sample=False, sample_failed=False): library = None sample = None if add_library: library = create_library(get_random_name(), 2) if add_sample: sample = create_sample(get_random_name(), 2) pool = create_pool(user) request = Request(user=user) request.save() if library: request.libraries.add(library) pool.libraries.add(library) pooling_object = Pooling.objects.get(library=library) if sample: request.samples.add(sample) pool.samples.add(sample) # Update the sample instance because after being added to the pool, # it was modified sample = sample.__class__.objects.get(pk=sample.pk) if sample_failed: sample.status = -1 # failed quality check sample.save() pooling_object = sample else: sample.status = 3 # passed quality check sample.save() pooling_object = Pooling.objects.get(sample=sample) if save: pooling_object.save() return pooling_object
def setUp(self): user = User.objects.create_user( email='*****@*****.**', password='******', is_staff=self._is_staff, ) user.save() library = Library.get_test_library('Library') sample = Sample.get_test_sample('Sample') library.save() sample.save() self.request = Request(user=user) self.request.save() self.request.libraries.add(library) self.request.samples.add(sample)
def test_multiple_sample_contains_invalid(self): """ Ensure get multiple samples containing invalid ids behaves correctly. """ sample = create_sample(get_random_name()) request = Request(user=self.user) request.save() request.samples.add(sample) response = self.client.get(reverse('samples-list'), { 'request_id': request.pk, 'ids': json.dumps([sample.pk, 'blah']) }) data = response.json() self.assertEqual(response.status_code, 400) self.assertFalse(data['success']) self.assertEqual(data['message'], 'Invalid payload.')
def test_from_http_request(self): http_request = HttpRequest() http_request.method = 'PATCH' http_request.path = '/kylef' http_request.META['REMOTE_ADDR'] = '32.64.128.16' http_request.META['HTTP_USER_AGENT'] = 'test user agent' http_request.META['HTTP_REFERER'] = 'https://fuller.li/' http_response = HttpResponse(status=204) request = Request() request.from_http_request(http_request, http_response, commit=False) self.assertEqual(request.path, '/kylef') self.assertEqual(request.method, 'PATCH') self.assertEqual(request.ip, '32.64.128.16') self.assertEqual(request.response, 204) self.assertEqual(request.user_agent, 'test user agent') self.assertEqual(request.referer, 'https://fuller.li/')
def test_from_http_request(self): http_request = self.factory.patch( '/kylef', REMOTE_ADDR='32.64.128.16', HTTP_USER_AGENT='test user agent', HTTP_REFERER='https://fuller.li/', ) http_response = HttpResponse(status=204) request = Request() request.from_http_request(http_request, http_response, commit=False) self.assertEqual(request.path, '/kylef') self.assertEqual(request.method, 'PATCH') self.assertEqual(request.ip, '32.64.128.16') self.assertEqual(request.response, 204) self.assertEqual(request.user_agent, 'test user agent') self.assertEqual(request.referer, 'https://fuller.li/')
class TestLibrarySampleTree(BaseTestCase): """ Tests for the libraries and samples tree. """ def setUp(self): user = self.create_user('*****@*****.**', 'foo-foo') self.client.login(email='*****@*****.**', password='******') library = create_library(self._get_random_name()) sample = create_sample(self._get_random_name()) self.request = Request(user=user) self.request.save() self.request.libraries.add(library) self.request.samples.add(sample) def test_libraries_and_samples_list(self): """ Ensure get all libraries and samples works correctly. """ response = self.client.get(reverse('libraries-and-samples-list')) data = response.json()['children'][0] self.assertEqual(response.status_code, 200) self.assertIn(self.request.name, data['name'])
def test_multiple_samples(self): """ Ensure get multiple samples behaves correctly. """ sample1 = create_sample(get_random_name()) sample2 = create_sample(get_random_name()) sample3 = create_sample(get_random_name()) request = Request(user=self.user) request.save() request.samples.add(*[sample1.pk, sample2.pk, sample3.pk]) response = self.client.get(reverse('samples-list'), { 'request_id': request.pk, 'ids': json.dumps([sample1.pk, sample2.pk]) }) data = response.json() self.assertEqual(response.status_code, 200) self.assertTrue(data['success']) samples = [x['name'] for x in data['data']] self.assertIn(sample1.name, samples) self.assertIn(sample2.name, samples) self.assertNotIn(sample3.name, samples)
def index(request, lang): data = {'lang': lang} if lang not in LANGUAGES: return render_to_response('client/404.html', {'data': data}, RequestContext(request)) contact_info = ContactInfo.objects.all() if contact_info: data['contact_info'] = contact_info[0] comments = Comment.objects.filter(deleted=False).order_by('-date') data['comments'] = comments order = '' if lang == 'es': order = 'spanish_name' elif lang == 'en': order = 'english_name' elif lang == 'de': order = 'german_name' elif lang == 'pt': order = 'portuguese_name' elif lang == 'fr': order = 'french_name' services_list = Service.objects.filter(deleted=False).order_by(order) data['services'] = services_list if request.method == 'POST': if 'btn_comment' in request.POST: content = request.POST['text_comment'] comment = Comment(content=content) comment.save() return HttpResponseRedirect('/services/' + lang) elif 'btn_suggestion' in request.POST: content = request.POST['text_suggestion'] suggestion = Suggestion(content=content) suggestion.save() return HttpResponseRedirect('/services/' + lang) elif 'btn_request' in request.POST: content = request.POST['request'] contact_info = request.POST['contact_info'] req = Request(content=content, contact_info=contact_info) req.save() return HttpResponseRedirect('/services/' + lang) return render_to_response('client/main/index.html', {'data': data}, RequestContext(request))
def setUp(self): user = User.objects.create_user(email='*****@*****.**', password='******') pool = Pool(name='_Foo', user=user) pool.save() library_1 = Library.get_test_library('Library1') library_2 = Library.get_test_library('Library2') library_1.save() library_2.save() sample_1 = Sample.get_test_sample('Sample1') sample_2 = Sample.get_test_sample('Sample2') sample_1.save() sample_2.save() pool.libraries.add(library_1) pool.samples.add(sample_1) self.request = Request(user=user) self.request.save() self.request.libraries.add(*[library_1, library_2]) self.request.samples.add(*[sample_1, sample_2])
def test_multiple_libraries(self): """ Ensure get multiple libraries behaves correctly. """ library1 = create_library(get_random_name()) library2 = create_library(get_random_name()) library3 = create_library(get_random_name()) request = Request(user=self.user) request.save() request.libraries.add(*[library1.pk, library2.pk, library3.pk]) response = self.client.get( reverse('libraries-list'), { 'request_id': request.pk, 'ids': json.dumps([library1.pk, library2.pk]) }) data = response.json() self.assertEqual(response.status_code, 200) self.assertTrue(data['success']) libraries = [x['name'] for x in data['data']] self.assertIn(library1.name, libraries) self.assertIn(library2.name, libraries) self.assertNotIn(library3.name, libraries)
def setUpClass(cls): super(GraphsTestCase, cls).setUpClass() cls.factory = RequestFactory() Request(path='/admin/', ip='127.0.0.1').save() Request(path='/admin/', ip='127.0.0.1').save() Request(path='/admin/login/', ip='127.0.0.1').save() staff_user = User.objects.create_user(username='******', password='******') staff_user.is_staff = True staff_user.save() cls.staff_user = staff_user user = UserFactory() cls.user = user cls.partner = PartnerFactory() cls.app = ApplicationFactory(partner=cls.partner) cls.app.status = Application.APPROVED cls.app.save() cls.dashboard_url = reverse('dashboard')
def process_response(self, request, response): if request.method.lower() not in settings.REQUEST_VALID_METHOD_NAMES: return response if response.status_code < 400 and settings.REQUEST_ONLY_ERRORS: return response if self.exceptions.resolve(request.path): return response if request.is_ajax() and settings.REQUEST_IGNORE_AJAX: return response if request.META.get('REMOTE_ADDR') in settings.REQUEST_IGNORE_IP: return response if getattr(request, 'user', False): if request.user.username in settings.REQUEST_IGNORE_USERNAME: return response Request.create_from_http_request(request, response) return response
def create_test_client_and_request(self): client = Client(name="client A") data = [ Request(title=f'title {index+1}', description=f'description {index+1}', client_id=1, priority=index + 1, target_date=date(2018, 11, 6), product=product) for index, product in enumerate(ProductEnum) ] data.append(client) db.session.add_all(data) db.session.commit()
def services(request, lang): contact_info = ContactInfo.objects.all() comments = Comment.objects.filter(deleted=False).order_by('-date') data = {'lang': lang, 'comments': comments} if contact_info: data['contact_info'] = contact_info[0] if lang not in LANGUAGES: return render_to_response('client/404.html', {'data': data}, RequestContext(request)) order = '' if lang == 'es': order = 'spanish_name' elif lang == 'en': order = 'english_name' elif lang == 'de': order = 'german_name' elif lang == 'pt': order = 'portuguese_name' elif lang == 'fr': order = 'french_name' if 'service' in request.GET: id = request.GET['service'] error = False for x in range(0, len(str(id))): if not str(id)[x].isdigit(): error = True break if not error: services_list = Service.objects.filter(deleted=False, id=int(id)).order_by(order) if not services_list: return render_to_response('client/404.html', {'data': data}, RequestContext(request)) images = Image.objects.filter(deleted=False, service=services_list[0]) if images: position = random.randrange(0, images.count()) data['image'] = images[position] data['selected'] = True data['service'] = id else: return render_to_response('client/404.html', {'data': data}, RequestContext(request)) else: services_list = Service.objects.filter(deleted=False).order_by(order) images = Image.objects.filter(deleted=False) if images: position = random.randrange(0, images.count()) data['image'] = images[position] data['services'] = services_list data['images'] = images if request.method == 'POST': if 'btn_comment' in request.POST: content = request.POST['text_comment'] comment = Comment(content=content) comment.save() return HttpResponseRedirect('/services/' + lang) elif 'btn_suggestion' in request.POST: content = request.POST['text_suggestion'] suggestion = Suggestion(content=content) suggestion.save() return HttpResponseRedirect('/services/' + lang) elif 'btn_request' in request.POST: content = request.POST['request'] contact_info = request.POST['contact_info'] req = Request(content=content, contact_info=contact_info) req.save() return HttpResponseRedirect('/services/' + lang) return render_to_response('client/services/index.html', {'data': data}, RequestContext(request))
def test_unicode(self): request = Request(method='PATCH', path='/', response=204) request.time = datetime.now() self.assertEqual(unicode(request), '[{}] PATCH / 204'.format(request.time))
def test_save(self): request = Request(ip='1.2.3.4') request.save()
def test_str_conversion(self): request = Request(method='PATCH', path='/', response=204) request.time = datetime.now() self.assertEqual(str(request), '[{}] PATCH / 204'.format(request.time))
def tool_detail(request, id): if not is_user_logged_in(session=request.session): return redirect(reverse('sign_in')) if 'is_shared_zone' not in request.session: return redirect(reverse('shared_zone:index')) if request.method == 'GET': try: tool = Tool.objects.get(id=id, enabled=1) pickup_times = User.objects.filter(pk=tool.owner.id).values_list('pickup_days', 'pickup_times') pickup_times = list(pickup_times)[0] if pickup_times[0] is None or pickup_times[1] is None: pickup_times = None if tool.is_shared_from_home(): pickup_address = tool.owner.get_address() else: pickup_address = SharedZone.objects.get(zipcode=tool.owner.zipcode).address may_leave_comment = False if Request.objects.filter(borrower=request.session["cool_user"], tool=id, status=Request.RETURNED, may_leave_comment=True).count() > 0: may_leave_comment = True context = { 'pickup_address': pickup_address, 'tool': tool, 'borrow': True, 'pickup_times': pickup_times, 'id': id, 'may_leave_comment': may_leave_comment } if "format" in request.GET and request.GET["format"] == "json": data = serializers.serialize("json", [tool]) if pickup_times: pu_times = { 'days': pickup_times[0], 'hours': pickup_times[1], } else: pu_times = None response = {'statusCode': 200, 'message': 'OK', 'data': data, 'media': settings.MEDIA_URL, 'pickup_times': pu_times, 'pickup_address': pickup_address} return JsonResponse(response) except Tool.DoesNotExist: context = { "not_found": 'The item you requested does not exist', 'borrow': True, 'id': id } if "format" in request.GET and request.GET["format"] == "json": response = {'statusCode': 404, 'message': 'The item you requested does not exist'} return JsonResponse(response) except Exception as e: print(e) if request.method == 'POST': try: tool = Tool.objects.get(pk=id, enabled=1) borrower = User.objects.get(pk=request.session["cool_user"], enabled=1) tool_request = Request(tool=tool, lender=tool.owner, borrower=borrower, zipcode=borrower.zipcode, shared_from=tool.shared_from) success_message = "The tool has been requested successfully! Please wait for owner's approval." if tool.shared_from == Tool.SHED: tool_request.comment = "Borrowing request approved!" success_message = "Borrowing request approved!" tool_request.status = Request.APPROVED tool.status = Tool.BORROWED tool.save() try: request.session['notification_s'] += 1 except KeyError: request.session['notification_s'] = 1 try: optional = "Please return the tool as soon as you finish using it. Remind the shed coordinator to mark the tool as returned." send_email('request_action.txt', 'request_action.html', {'tool_name': tool_request.tool.name, 'request_status': tool_request.get_status_choices(), 'message': tool_request.comment, 'optional': optional}, "Borrowing Request Information", tool_request.borrower.email) except Exception as e: print(e) tool_request.save() if tool_request.tool.shared_from == Tool.HOME: try: notification = Notification.objects.get(user=tool.owner) except Notification.DoesNotExist: notification = Notification(user=tool.owner) notification.save() notification.increment_received() notification.save() try: send_email('borrowing_request.txt', 'borrowing_request.html', {'borrower': tool_request.borrower.__str__(), 'tool': tool_request.tool.name}, "Borrowing Request Information", tool_request.lender.email) except Exception as e: print(e) context = { 'tool': tool, 'borrow': True, 'message': success_message, 'id': id } if "format" in request.POST and request.POST["format"] == "json": response = {'statusCode': 200, 'message': success_message} return JsonResponse(response) except Tool.DoesNotExist: context = { "not_found": 'The item you requested does not exist', 'borrow': True, 'id': id } if "format" in request.POST and request.POST["format"] == "json": response = {'statusCode': 404, 'message': 'The item you requested does not exist'} return JsonResponse(response) except Exception as e: print(e) context = { 'tool': tool, 'borrow': True, 'id': id } return render(request, 'tool_listing/tool_detail.html', context)
def test_save_not_log_ip(self): request = Request(ip='1.2.3.4') request.save() self.assertEqual(settings.IP_DUMMY, request.ip)
def test_save_anonymous_ip(self): request = Request(ip='1.2.3.4') request.save() self.assertTrue(request.ip.endswith('.1'))
def test_save_not_log_user(self): user = get_user_model().objects.create(username='******') request = Request(ip='1.2.3.4', user=user) request.save() self.assertIsNone(request.user)