Skip to content

Commit

Permalink
assignment7, integration and e2e for assignment7, feature, yml + int …
Browse files Browse the repository at this point in the history
…tests
  • Loading branch information
AvangardAA committed Oct 27, 2023
1 parent 70c3c20 commit 6518276
Show file tree
Hide file tree
Showing 5 changed files with 116 additions and 21 deletions.
8 changes: 7 additions & 1 deletion .github/workflows/check.yml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,12 @@ jobs:
- name: Run end-to-end tests
run: python tests/e2e/e2e_tests.py

- name: Run integration tests
- name: Run integration tests 4
run: python -m tests.integration.assignment4

- name: Run integration tests 5
run: python -m tests.integration.assignment5

- name: Run integration tests 7
run: python -m tests.integration.assignment7

9 changes: 7 additions & 2 deletions algo.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from functions.funcs import hist_data, user_hist_data, predict_users, predict_user, total_time_user, total_time_avg, \
gdprf, post_metrics, get_reports
from functions.utils import transform_metrics_list
from models import InputData

app = FastAPI()
Expand Down Expand Up @@ -62,12 +63,16 @@ async def post_report(report_name: str, data: InputData):
return await post_metrics(userIdstr,data,report_name)

@app.get("/api/report/")
async def get_report(report_name: str, ffrom: str, to: str):
async def get_report(report_name: str, ffrom: str, to: str, ver: int): #version 1-old, 2-global
if report_name is None or ffrom is None or to is None:
return {"err": "not enough data"}

return await get_reports(report_name, ffrom, to)
if ver == 1:
return await get_reports(report_name, ffrom, to)

elif ver == 2:
res = await get_reports(report_name, ffrom, to)
return transform_metrics_list(res)

@app.post('/api/user/forget')
async def forget_gdpr(userId: str):
Expand Down
28 changes: 27 additions & 1 deletion functions/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,4 +69,30 @@ def make_res_list(data, tsfrom, tsto):
except:
return {"err": "broken make"}

return reslist
return reslist

def transform_metrics_list(input_list):
transformed_list = []

for item in input_list:
user_id = item["userId"]
metrics = item["metrics"]
daily_average = None

for metric in metrics:
if "dailyAverage" in metric:
daily_average = metric["dailyAverage"]
break

if daily_average is not None:
user_entry = {
"userId": user_id,
"metrics": [
{
"dailyAverage": daily_average
}
]
}
transformed_list.append(user_entry)

return {"users": transformed_list}
62 changes: 53 additions & 9 deletions tests/e2e/e2e_tests.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import asyncio
import unittest
import json
import http.client
Expand All @@ -19,7 +20,7 @@ def test_total_time_endpoint(self):
self.assertEqual(response.status, 200)
self.assertEqual(json.loads(data), {"totalTime": []})

self.conn.request("GET", "/api/stats/user/total?userId=8b0b5db6-19d6-d777-575e-915c2a77959a")
self.conn.request("GET", "/api/stats/user/total?userId=2fba2529-c166-8574-2da2-eac544d82634")
response = self.conn.getresponse()
data = response.read().decode()
self.assertEqual(response.status, 200)
Expand All @@ -32,17 +33,17 @@ def test_total_time_avg_endpoint(self):
self.assertEqual(response.status, 200)
self.assertEqual(json.loads(data), {"dailyAverage": [], 'weeklyAverage': []})

self.conn.request("GET", "/api/stats/user/total/avg?userId=8b0b5db6-19d6-d777-575e-915c2a77959a")
self.conn.request("GET", "/api/stats/user/total/avg?userId=2fba2529-c166-8574-2da2-eac544d82634")
response = self.conn.getresponse()
data = response.read().decode()
self.assertEqual(response.status, 200)
self.assertTrue("dailyAverage" in json.loads(data))
self.assertTrue("weeklyAverage" in json.loads(data))

async def test_get_reports_307_then_200(self):
async def test_get_reports_307_then_200_then_fail(self):
async with httpx.AsyncClient() as client:
response = await client.get(
"http://127.0.0.1/api/report?report_name=dummy1&ffrom=2023-19-10-07:00&to=2023-23-10-07:00")
"http://127.0.0.1:8000/api/report?report_name=dummy1&ffrom=2023-19-10-07:00&to=2023-23-10-07:00&ver=1")

if response.status_code == 307:
location = response.headers.get("Location")
Expand All @@ -51,8 +52,7 @@ async def test_get_reports_307_then_200(self):
data = response.text

if response.status_code != 200:
# Handle non-200 responses, e.g., report not found
self.assertEqual(response.status_code, 404) # Update the status code as needed
self.assertEqual(response.status_code, 404)
else:
try:
parsed_data = json.loads(data)
Expand All @@ -62,13 +62,57 @@ async def test_get_reports_307_then_200(self):

async def test_get_reports_200(self):
async with httpx.AsyncClient() as client:

response = await client.get(
"http://127.0.0.1/api/report?report_name=dummy&ffrom=2023-19-10-07:00&to=2023-23-10-07:00")
"http://127.0.0.1:8000/api/report?report_name=dummy1&ffrom=2023-19-10-07:00&to=2023-23-10-07:00&ver=1")

if response.status_code == 307:
location = response.headers.get("Location")
response = await client.get(location)

data = response.text

self.assertEqual(response.status_code, 200)
self.assertTrue(len(data) == 2)
if response.status_code != 200:
self.assertEqual(response.status_code, 404)
else:
try:
parsed_data = json.loads(data)
self.assertIsInstance(parsed_data, dict)
self.assertTrue(len(parsed_data)==1)
except json.JSONDecodeError:
self.fail("Response is not valid JSON")

async def test_get_reports_V2_200(self):
async with httpx.AsyncClient() as client:
async with httpx.AsyncClient() as client:

response = await client.get(
"http://127.0.0.1:8000/api/report?report_name=dummy1&ffrom=2023-19-10-07:00&to=2023-23-10-07:00&ver=2")

if response.status_code == 307:
location = response.headers.get("Location")
response = await client.get(location)

data = response.text

if response.status_code != 200:
self.assertEqual(response.status_code, 404)
else:
try:
parsed_data = json.loads(data)
self.assertIsInstance(parsed_data, dict)
self.assertTrue(len(parsed_data) == 1)
except json.JSONDecodeError:
self.fail("Response is not valid JSON")

def test_start_get200_fail(self):
asyncio.run(self.test_get_reports_307_then_200_then_fail())

def test_start_get200(self):
asyncio.run(self.test_get_reports_200())

def test_start_get200V2(self):
asyncio.run(self.test_get_reports_V2_200())

if __name__ == '__main__':
unittest.main()
30 changes: 22 additions & 8 deletions tests/integration/assignment7.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,32 @@
from unittest.mock import patch
import asyncio

from functions.funcs import total_time_avg, total_time_user
from functions.funcs import get_reports
from functions.utils import transform_metrics_list


class TestIntegration(unittest.TestCase):
@patch('functions.funcs.fetch')
def test_total_time_user_not_empty(self, mock_fetch):
@patch('functions.funcs.get_reports')
def test_get_reports_metricsV2_OK(self, mock_get_reports):
async def async_test():
mock_fetch.return_value = {"total": 1, "data": [{"userId": "user", "lastSeenDate": "2023-10-19T10:47:29.2227007+00:00"}]}
blank_user = "user"
result = await total_time_user(blank_user)
mock_get_reports.return_value = [{"userId": "e13412b2-fe46-7149-6593-e47043f39c91","metrics": [{"dailyAverage": 29418.0},{"weeklyAverage": 205926.0},{"total": 88254.0},{"min": 0.0},{"max": 83874.0}]},{"userId": "e9de6dd1-84e5-9833-59de-8c51008de6a0","metrics": [{"dailyAverage": 17515.333333333332},{"weeklyAverage": 122607.33333333333},{"total": 52546.0},{"min": 0.0},{"max": 83874.0}]}]
res = transform_metrics_list(mock_get_reports.return_value)

self.assertIsInstance(res, dict)
self.assertTrue(len(res['users'])==2)

self.assertIsInstance(result, dict)
self.assertTrue(len(result['totalTime'])>0)
asyncio.run(async_test())

@patch('functions.funcs.get_reports')
def test_get_reports_metricsV2_NOT_OK(self, mock_get_reports):
async def async_test():
mock_get_reports.return_value = [{}]
try:
res = transform_metrics_list(mock_get_reports.return_value)
except KeyError as e:
self.assertEqual(str(e), "'userId'")
else:
self.fail("KeyError was not raised")

asyncio.run(async_test())

Expand Down

0 comments on commit 6518276

Please sign in to comment.