def post(self, request, *args, **kwargs): request_data = request.data.copy() request_data['timestamp'] = datetime.datetime.now() serializer = serializers.GuessSerializer(data=request_data) if serializer.is_valid(): request_status = status.HTTP_202_ACCEPTED tasks.create_guess.delay(request_data) data = serializer.data else: request_status = status.HTTP_400_BAD_REQUEST data = {'errors': ['Invalid request.']} return response.Response(data, status=request_status)
def test_invalid_guess_high(self): self.assertEqual(models.Guess.objects.count(), 0) data = { 'user_email': '*****@*****.**', 'keyword': 'fake_keyword', 'number': 1000, 'timestamp': datetime.datetime.now(), } s = serializers.GuessSerializer(data=data) self.assertFalse(s.is_valid()) self.assertIn('number', s.errors)
def test_valid_guess(self): self.assertEqual(models.Guess.objects.count(), 0) data = { 'user_email': '*****@*****.**', 'keyword': 'fake_keyword', 'number': 666, 'timestamp': datetime.datetime.now(), } s = serializers.GuessSerializer(data=data) self.assertTrue(s.is_valid()) s.save() self.assertEqual(models.Guess.objects.count(), 1)
def test_a_new_contest_start(self): contest = models.LuckyCallContest.objects.create( keyword='fake_keyword', ) data = { 'user_email': '*****@*****.**', 'keyword': 'fake_keyword', 'number': 666, 'timestamp': datetime.datetime.now(), } s = serializers.GuessSerializer(data=data) self.assertTrue(s.is_valid()) s.save() self.assertEqual(models.Guess.objects.count(), 1) guess = models.Guess.objects.first() self.assertEqual(guess.contest, contest) new_contest = models.LuckyCallContest.objects.create( keyword='another_keyword', ) data = { 'user_email': '*****@*****.**', 'keyword': 'another_keyword', 'number': 777, 'timestamp': datetime.datetime.now(), } s = serializers.GuessSerializer(data=data) self.assertTrue(s.is_valid()) s.save() self.assertEqual(models.Guess.objects.count(), 2) new_guess = models.Guess.objects.get(user_email='*****@*****.**') self.assertEqual(new_guess.contest, new_contest)
def test_a_contest_exist(self): contest = models.LuckyCallContest.objects.create( keyword='fake_keyword', ) data = { 'user_email': '*****@*****.**', 'keyword': 'fake_keyword', 'number': 666, 'timestamp': datetime.datetime.now(), } s = serializers.GuessSerializer(data=data) self.assertTrue(s.is_valid()) s.save() self.assertEqual(models.Guess.objects.count(), 1) guess = models.Guess.objects.first() self.assertEqual(guess.contest, contest)
def create_guess(data): serializer = serializers.GuessSerializer(data=data) if serializer.is_valid(): serializer.save() return 'OK' return 'KO'