2

我试图为我的视图制作测试用例,现在我将使用包含用户图像的用户凭据发送多部分请求。我使用 MultipartWriter,但是,当我尝试阅读部分时,我得到的部分是无。我确定我的测试用例写错了。
感谢您的帮助,并为我糟糕的英语感到抱歉。

我的测试用例:

async def test_users_post(app):
    with open('user_photo.jpg', 'rb') as file:
        user_data = dict(
            name='Test1',
            password='Password',
            grand=True,
            description='Blank',
            email='test@test.ru',
            file=file
        )
        with MultipartWriter() as mpwriter:
            mpwriter.append_form([(key, value) for key, value in user_data.items()])
            response = await app['client'].post('/users', data=mpwriter)
            assert response.status == 201

起始视线:

    async def post(self):
    reader = await self.request.multipart()

    async with self.request.app['db'].acquire() as conn:
        data = {}
        while True:
            field = await reader.next()
            print(field) # field is None here
            if not field:
                # If not fields were read
4

1 回答 1

2

好的,我找到了不需要多部分编写器的方法。现在我使用 aiohttp.FormData 来打包用户凭据。

async def test_users_post(app):
    form = aiohttp.FormData()
    user_data = dict(
        name='Test1',
        password='Password',
        description='Blank',
        email='test@test.ru',
    )
    for key, value in user_data.items():
        form.add_field(key, value)
    form.add_field('photo', open('user_photo.jpg', 'rb'))
    response = await app['client'].post('/users', data=form)
    assert response.status == 201
于 2020-05-28T12:43:14.593 回答