Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add tests using mocker to main.py #115

Closed
wants to merge 3 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions src/test_main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import pytest
from pytest_mock import MockerFixture
from main import Net, transform
from api import app
from fastapi.testclient import TestClient
from PIL import Image
import torch
import torch.nn as nn
import io

def test_net_init(mocker: MockerFixture):
mock_super_init = mocker.patch('torch.nn.Module.__init__')
net = Net()
mock_super_init.assert_called_once()

def test_net_forward(mocker: MockerFixture):
mock_input = mocker.patch('torch.Tensor')
mock_relu = mocker.patch('torch.nn.functional.relu')
mock_log_softmax = mocker.patch('torch.nn.functional.log_softmax')
net = Net()
net.forward(mock_input)
mock_relu.assert_any_call(net.fc1(mock_input.view(-1, 28 * 28)))
mock_relu.assert_any_call(net.fc2(mock_relu.return_value))
mock_log_softmax.assert_called_once_with(net.fc3(mock_relu.return_value), dim=1)

def test_predict(mocker: MockerFixture):
mock_file = mocker.patch('fastapi.UploadFile')
mock_image_open = mocker.patch('PIL.Image.open')
mock_image_open.return_value.convert.return_value = Image.new('L', (28, 28))
client = TestClient(app)
response = client.post("/predict/", files={"file": ("filename", io.BytesIO(), "image/png")})
pytest.assert_(response.status_code == 200, "Expected status code to be 200")
pytest.assert_('prediction' in response.json(), "Expected 'prediction' in response")
Loading