Skip to content

Commit

Permalink
tests for create action, remove unused callback action
Browse files Browse the repository at this point in the history
  • Loading branch information
daveminer committed Aug 19, 2024
1 parent 509d34c commit 7791666
Show file tree
Hide file tree
Showing 8 changed files with 85 additions and 45 deletions.
5 changes: 0 additions & 5 deletions bert_serv/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,6 @@

urlpatterns = [
path('admin/', admin.site.urls),
path('callback/', include([
path('sentiment/', include([
path('new', views.SentimentCallback.as_view()),
])),
])),
path('sentiment/', include([
path('', views.SentimentList.as_view()),
path('<int:pk>/', views.SentimentDetail.as_view()),
Expand Down
15 changes: 15 additions & 0 deletions sentiment/test_helpers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import random
from sentiment.models import Sentiment

def create_sentiment(label, text, score=None, tags=None):
if score is None:
score = random.uniform(-1.0, 1.0) # Generate a random score between -1.0 and 1.0
if tags is None:
tags = [] # Set tags to an empty list if not provided

return Sentiment.objects.create(
label=label,
score=score,
tags=tags,
text=text
)
1 change: 0 additions & 1 deletion sentiment/views/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
from .callbackview import *
from .createview import *
from .detailview import *
from .listview import *
7 changes: 0 additions & 7 deletions sentiment/views/callbackview.py

This file was deleted.

19 changes: 4 additions & 15 deletions sentiment/views/createview.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from django.http import HttpResponse
from django.views.generic import View
from celery import chain, signature
from sentiment.tasks import run_sentiment, send_webhook
import json
import logging

Expand All @@ -18,11 +19,11 @@ def post(self, request, *args, **kwargs):

if callback_url:
chain(
signature("sentiment.tasks.run_sentiment", args=(content,), retries=3),
signature("sentiment.tasks.send_webhook", args=(callback_url,), retries=3)
run_sentiment.s(content).set(retries=3),
send_webhook.s(callback_url).set(retries=3),
).delay()
else:
signature("sentiment.tasks.run_sentiment", args=(content,)).delay()
run_sentiment.s(content).set(retries=3),

return HttpResponse(status=201)
except Exception as e:
Expand All @@ -35,15 +36,3 @@ def parse_request_body(request):
return json.loads(request.body)
except ValueError:
raise BadRequest("Could not parse request body as JSON.")


def process_item(item, callback_url):
content = [(item['article_id'], item['text'])]

if callback_url:
chain(
signature("sentiment.tasks.run_sentiment", args=(content, tags,)),
signature("sentiment.tasks.send_webhook", args=(callback_url,), retries=3)
).delay()
else:
signature("sentiment.tasks.run_sentiment", args=(content, tags,)).delay()
42 changes: 42 additions & 0 deletions sentiment/views/test_createview.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import json
import unittest
from unittest.mock import patch, MagicMock
from django.test import RequestFactory
from django.http import HttpResponse
from sentiment.views import SentimentCreate

class SentimentCreateTestCase(unittest.TestCase):
def setUp(self):
self.factory = RequestFactory()
self.view = SentimentCreate.as_view()

@patch('sentiment.tasks.run_sentiment.s')
@patch('sentiment.tasks.send_webhook.s')
def test_post_with_callback_url(self, mock_send_webhook, mock_run_sentiment):

request_body = json.dumps([
{'article_id': 1, 'tags': ['news'], 'text': 'Some content here'},
{'article_id': 2, 'tags': ['sports'], 'text': 'Another content'}
])
request = self.factory.post('/sentiment/new?callback_url=http://example.com/callback', request_body, content_type='application/json')
response = self.view(request)

self.assertEqual(response.status_code, 201)
mock_run_sentiment.assert_called_once_with(
[(1, ['news'], 'Some content here'), (2, ['sports'], 'Another content')]
)
mock_send_webhook.assert_called_once_with('http://example.com/callback')

@patch('sentiment.tasks.run_sentiment.s')
def test_post_without_callback_url(self, mock_run_sentiment):
request_body = json.dumps([
{'article_id': 1, 'tags': ['news'], 'text': 'Some content here'},
{'article_id': 2, 'tags': ['sports'], 'text': 'Another content'}
])
request = self.factory.post('/sentiment/new', request_body, content_type='application/json')
response = self.view(request)

self.assertEqual(response.status_code, 201)
mock_run_sentiment.assert_called_once_with(
[(1, ['news'], 'Some content here'), (2, ['sports'], 'Another content')]
)
20 changes: 20 additions & 0 deletions sentiment/views/test_detailview.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import json
import pytest
from django.test import Client
from sentiment.models import Sentiment
from sentiment.test_helpers import create_sentiment

@pytest.mark.django_db
def test_sentiment_detail_view(mocker):
client = Client()
sentiment = create_sentiment(label='test-label', text='test-text', tags=['test-tag'])

response = client.get(f"/sentiment/{sentiment.id}/", HTTP_ACCEPT='application/json')

assert response.status_code == 200

json_response = response.json()
assert json_response['label'] == 'test-label'
assert json_response['text'] == 'test-text'
assert json_response['tags'] == ['test-tag']
assert json_response['score'] < 1.0 and json_response['score'] > -1.0
21 changes: 4 additions & 17 deletions sentiment/views/test_listview.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
import json
import numpy
import pytest
import random
from django.test import Client, override_settings
from sentiment.models import Sentiment
from sentiment.test_helpers import create_sentiment

@pytest.mark.django_db
def test_get(mocker):
client = Client()
__create_sentiment(label='test-label', text='test-text-two', tags=['test-tag'])
__create_sentiment(label='test-label-two', text='test-text-two', tags=['test-tag', 'other-test-tag'])

create_sentiment(label='test-label', text='test-text-two', tags=['test-tag'])
create_sentiment(label='test-label-two', text='test-text-two', tags=['test-tag', 'other-test-tag'])

response = client.get("/sentiment/", {'tags': ['test-tag', 'another-tag'], 'period': 30}, HTTP_ACCEPT='application/json')

Expand All @@ -19,17 +20,3 @@ def test_get(mocker):
assert json[0]['label'] == 'test-label-two'
assert json[0]['score'] < 1.0 and json[0]['score'] > -1.0
assert json[1]['label'] == 'test-label'


def __create_sentiment(label, text, score=None, tags=None):
if score is None:
score = random.uniform(-1.0, 1.0) # Generate a random score between -1.0 and 1.0
if tags is None:
tags = [] # Set tags to an empty list if not provided

Sentiment.objects.create(
label=label,
score=score,
tags=tags,
text=text
)

0 comments on commit 7791666

Please sign in to comment.