test_python_fastapi.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import os
  2. import time
  3. from tests.package.test_python import TestPythonPackageBase
  4. class TestPythonPy3Fastapi(TestPythonPackageBase):
  5. """Test fastapi, uvicorn and pydantic2.
  6. fastapi needs an asgi server to run. Since we select uvicorn as
  7. asgi server here, uvicorn is tested as well.
  8. pydantic is an major dependency of fastapi so it is implicitly
  9. tested here as well.
  10. """
  11. __test__ = True
  12. config = \
  13. """
  14. BR2_arm=y
  15. BR2_cortex_a9=y
  16. BR2_ARM_ENABLE_NEON=y
  17. BR2_ARM_ENABLE_VFP=y
  18. BR2_TOOLCHAIN_EXTERNAL=y
  19. BR2_PACKAGE_PYTHON3=y
  20. BR2_PACKAGE_PYTHON_FASTAPI=y
  21. BR2_PACKAGE_PYTHON_UVICORN=y
  22. BR2_TARGET_ROOTFS_CPIO=y
  23. # BR2_TARGET_ROOTFS_TAR is not set
  24. """
  25. sample_scripts = ["tests/package/sample_python_fastapi.py"]
  26. timeout = 60
  27. def test_run(self):
  28. self.login()
  29. self.check_sample_scripts_exist()
  30. cmd = "uvicorn sample_python_fastapi:app > /dev/null 2>&1 &"
  31. _, exit_code = self.emulator.run(cmd, timeout=self.timeout)
  32. # Give enough time for the uvicorn server to start up
  33. for attempt in range(30):
  34. time.sleep(1)
  35. cmd = "wget -q -O - http://127.0.0.1:8000/"
  36. output, exit_code = self.emulator.run(cmd, timeout=self.timeout)
  37. if exit_code == 0:
  38. self.assertEqual(output[0], '{"message":"Hello World"}')
  39. break
  40. else:
  41. self.assertTrue(False, "Timeout while waiting for fastapi server")
  42. def login(self):
  43. cpio_file = os.path.join(self.builddir, "images", "rootfs.cpio")
  44. self.emulator.boot(arch="armv7",
  45. kernel="builtin",
  46. options=["-initrd", cpio_file])
  47. self.emulator.login()