Leeladhar9/Text-classification-API
0
1from fastapi.testclient import TestClient # type: ignore
2from main import app
3from main import TextInput
4from fastapi.encoders import jsonable_encoder # type: ignore
5from transformers import pipeline
6
7client = TestClient(app)
8
9# Test the welcome endpoint
10def test_welcome():
11 # Test the welcome endpoint
12 response = client.get("/")
13 assert response.status_code == 200
14 assert response.json() == "Welcome to our Text Classification API"
15
16# Test the sentiment analysis endpoint for positive sentiment
17def test_positive_sentiment():
18 with client:
19 # Define the request payload
20 # Initialize payload as a TextInput object
21 payload = TextInput(text="I love this product! It's amazing!")
22
23 # Convert TextInput object to JSON-serializable dictionary
24 payload_dict = jsonable_encoder(payload)
25
26 # Send a POST request to the sentiment analysis endpoint
27 response = client.post("/analyze/{text}", json=payload_dict)
28
29 # Assert that the response status code is 200 OK
30 assert response.status_code == 200
31
32 # Assert that the sentiment returned is positive
33 assert response.json()[0]['label'] == "positive"
34
35# Test the sentiment analysis endpoint for negative sentiment
36def test_negative_sentiment():
37 with client:
38 # Define the request payload
39 # Initialize payload as a TextInput object
40 payload = TextInput(text="I'm really disappointed with this service. It's terrible.")
41
42 # Convert TextInput object to JSON-serializable dictionary
43 payload_dict = jsonable_encoder(payload)
44
45 # Send a POST request to the sentiment analysis endpoint
46 response = client.post("/analyze/{text}", json=payload_dict)
47
48 # Assert that the response status code is 200 OK
49 assert response.status_code == 200
50
51 # Assert that the sentiment returned is positive
52 assert response.json()[0]['label'] == "negative"
53
54# Test the sentiment analysis endpoint for neutral sentiment
55def test_neutral_sentiment():
56 with client:
57 # Define the request payload
58 # Initialize payload as a TextInput object
59 payload = TextInput(text="This is a neutral statement.")
60
61 # Convert TextInput object to JSON-serializable dictionary
62 payload_dict = jsonable_encoder(payload)
63
64 # Send a POST request to the sentiment analysis endpoint
65 response = client.post("/analyze/{text}", json=payload_dict)
66
67 # Assert that the response status code is 200 OK
68 assert response.status_code == 200
69
70 # Assert that the sentiment returned is positive
71 assert response.json()[0]['label'] == "neutral"