为什么测试结果会有所不同,并且从SQLite集成到PostgreSQL后没有通过?

问题描述 投票:0回答:1

我一直在开发没有Docker的项目,并且已经集成并确保一切正常,我已经运行了测试。令我震惊的是,几乎有一半的测试无法正常运行。他们中的大多数人正在测试详细的api视图。我将在下面发布代码。如果您能找到丢失或隐藏的东西,请告诉我们)

[这是示例项目]

models.py

class Book(models.Model):
    name = models.CharField(max_length=255)
    author = models.CharField(max_length=255)
    created_at = models.DateField(auto_now_add=True)

    def __str__(self):
        return self.name

serialisers.py

class BookSerializers(ModelSerializer):
    class Meta:
        model = Book
        fields = ('id', 'name', 'author')

views.py

class BookListApiView(ListAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializers
    permission_classes = [AllowAny, ]


class BookCreateApiView(CreateAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializers
    permission_classes = [AllowAny, ]


class BookRetrieveUpdateDeleteView(RetrieveUpdateDestroyAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializers
    permission_classes = [AllowAny, ]

tests.py

LIST_BOOK_API_URL = reverse('book:list')
CREATE_BOOK_API_URL = reverse('book:create')
DETAIL_BOOK_API_URL = reverse('book:detail', kwargs={'pk': 1})

class TestBookApiView(TestCase):
    def setUp(self):
        self.client = APIClient()

    def test_create_book_through_api(self):
        payload = {
            'name': 'this is book',
            'author': 'test author'
        }
        res = self.client.post(CREATE_BOOK_API_URL, payload)
        self.assertEqual(res.status_code, status.HTTP_201_CREATED)

    def test_listing_book_through_api(self):
        Book.objects.create(
            name='test',
            author='testing',
        )
        res = self.client.get(LIST_BOOK_API_URL)
        self.assertEqual(res.status_code, status.HTTP_200_OK)
        self.assertContains(res, 'test')

    def test_retreiving_book_through_api(self):
        Book.objects.create(
            name='test',
            author='testing',
        )
        res = self.client.get(DETAIL_BOOK_API_URL)
        print(DETAIL_BOOK_API_URL)
        self.assertEqual(res.status_code, status.HTTP_200_OK)

urls.py [用于图书应用]

app_name = 'book'

urlpatterns = [
    path('list/', BookListApiView.as_view(), name='list'),
    path('create/', BookCreateApiView.as_view(), name='create'),
    path('<int:pk>/', BookRetrieveUpdateDeleteView.as_view(), name='detail'),
]

urls.py [main]

urlpatterns = [
    path('admin/', admin.site.urls),
    path('book/', include('book.urls')),
]

测试结果

..F
======================================================================
FAIL: test_retreiving_book_through_api (book.tests.TestBookApiView)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/user/web/book/tests.py", line 39, in test_retreiving_book_through_api
    self.assertEqual(res.status_code, status.HTTP_200_OK)
AssertionError: 404 != 200

----------------------------------------------------------------------
Ran 3 tests in 0.040s

FAILED (failures=1)

我的Dockerfile

# the base image for the python that we are using for the project
FROM python:3.8.1-alpine

ENV PYHTONUNBUFFERED 1
ENV PYTHONDONTWRITEBYTECODE 1

# creating a folder.
RUN mkdir -p /home/user

ENV HOME=/home/user
ENV APP_HOME=/home/user/web

WORKDIR ${APP_HOME}

RUN mkdir ${APP_HOME}/staticfiles
RUN mkdir ${APP_HOME}/media

RUN apk update \
    && apk add postgresql-dev gcc python3-dev musl-dev

RUN apk add zlib zlib-dev jpeg-dev

RUN pip install --upgrade pip

COPY ./requirements.txt ${APP_HOME}/requirements.txt

RUN pip install -r requirements.txt
COPY entrypoint.sh ${APP_HOME}/entrypoint.sh

COPY . ${APP_HOME}

RUN adduser -D user
USER user

ENTRYPOINT [ "/home/user/web/entrypoint.sh" ]

我几乎100%确信已创建对象并且此功能正常运行。因为我已经在浏览器上对其进行了测试,所以效果很好。如果我检查它是否在没有Docker的情况下正常工作。请让见面者知道我通过测试所缺少的内容。

django docker django-rest-framework
1个回答
2
投票

您已经将DETAIL_BOOK_API_URL硬编码为使用ID 1,但是一本书可能没有此ID。您应该使用刚创建的书的ID

def test_retreiving_book_through_api(self):
    book = Book.objects.create(
        name='test',
        author='testing',
    )
    res = self.client.get(reverse('book:detail', kwargs={'pk': book.pk}))
    self.assertEqual(res.status_code, status.HTTP_200_OK)
© www.soinside.com 2019 - 2024. All rights reserved.