Database testing #530
-
Hello, I really enjoy the ORM. I've got a problem with the database testing. I need to await some database calls in my tests, but it will require making my tests asynchronous. As I understand, piccolo test runner doesn't support that. Is there a way to force to run async queries in a sync way? I tried to make my test async using fastapi docs for async testing. Test runner outputs something like: |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 7 replies
-
Hi @Anton-Karpenko, I'm glad you're enjoying Piccolo. When testing async code, there are a few ways to go about it. If you use I see from the FastAPI docs that it recommends using the I tend to use # test_app.py
import pytest
from my_app.tables import MyTable
@pytest.mark.asyncio
async def test_foo():
rows = await MyTable.select()
assert len(rows) == 0 If you prefer using Python's builtin # test_app.py
from unittest import TestCase
import pytest
from piccolo.utils.sync import run_sync
from my_app.tables import MyTable
class TestFoo(TestCase):
def test_foo(self):
async def test():
rows = await MyTable.select()
self.assertEqual(len(rows), 0)
run_sync(test()) Does that help at all? |
Beta Was this translation helpful? Give feedback.
-
Probably, the issue was in some fixture. I removed all and readded one by one. It led to a situation where my tests were hanging infinity. Here the problem was that I tried to pass an integer value to an FK field and that the related model's id must be UUID instead of int. Anyway, thanks a lot for the help! |
Beta Was this translation helpful? Give feedback.
Hi @Anton-Karpenko, I'm glad you're enjoying Piccolo.
When testing async code, there are a few ways to go about it. If you use
piccolo tester run
it just calls Pytest under the hood.I see from the FastAPI docs that it recommends using the
pytest.mark.anyio
decorator. Is this what you're currently using?I tend to use
pytest-asyncio
instead, as I don't use Trio.If you prefer using Python's builtin
TestCase
, you can also do things like this: