github.com/containers/podman/v5@v5.1.0-rc1/test/apiv2/python/rest_api/fixtures/api_testcase.py (about)

     1  import json
     2  import subprocess
     3  import unittest
     4  
     5  import requests
     6  import sys
     7  import time
     8  
     9  from .podman import Podman
    10  
    11  
    12  class APITestCase(unittest.TestCase):
    13      PODMAN_URL = "http://localhost:8080"
    14      podman = None  # initialized podman configuration for tests
    15      service = None  # podman service instance
    16  
    17      @classmethod
    18      def setUpClass(cls):
    19          super().setUpClass()
    20  
    21          APITestCase.podman = Podman()
    22          APITestCase.service = APITestCase.podman.open(
    23              "system", "service", "tcp://localhost:8080", "--time=0"
    24          )
    25          # give the service some time to be ready...
    26          time.sleep(2)
    27  
    28          returncode = APITestCase.service.poll()
    29          if returncode is not None:
    30              raise subprocess.CalledProcessError(returncode, "podman system service")
    31  
    32          r = requests.post(
    33              APITestCase.uri("/images/pull?reference=quay.io%2Flibpod%2Falpine%3Alatest")
    34          )
    35          if r.status_code != 200:
    36              raise subprocess.CalledProcessError(
    37                  r.status_code, f"podman images pull quay.io/libpod/alpine:latest {r.text}"
    38              )
    39  
    40      @classmethod
    41      def tearDownClass(cls):
    42          APITestCase.service.terminate()
    43          stdout, stderr = APITestCase.service.communicate(timeout=0.5)
    44          if stdout:
    45              sys.stdout.write("\nService Stdout:\n" + stdout.decode("utf-8"))
    46          if stderr:
    47              sys.stderr.write("\nService Stderr:\n" + stderr.decode("utf-8"))
    48          return super().tearDownClass()
    49  
    50      def setUp(self):
    51          super().setUp()
    52          APITestCase.podman.run("run", "-d", "alpine", "top", check=True)
    53  
    54      def tearDown(self) -> None:
    55          APITestCase.podman.run("pod", "rm", "--all", "--force", check=True)
    56          APITestCase.podman.run("rm", "--all", "--force", check=True)
    57          super().tearDown()
    58  
    59      @property
    60      def podman_url(self):
    61          return "http://localhost:8080"
    62  
    63      @staticmethod
    64      def uri(path):
    65          return APITestCase.PODMAN_URL + "/v2.0.0/libpod" + path
    66  
    67      @staticmethod
    68      def compat_uri(path):
    69          return APITestCase.PODMAN_URL + "/v3.0.0/" + path
    70  
    71      def resolve_container(self, path):
    72          """Find 'first' container and return 'Id' formatted into given URI path."""
    73  
    74          try:
    75              r = requests.get(self.uri("/containers/json?all=true"))
    76              containers = r.json()
    77          except Exception as e:
    78              msg = f"Bad container response: {e}"
    79              if r is not None:
    80                  msg += ": " + r.text
    81              raise self.failureException(msg)
    82          return path.format(containers[0]["Id"])
    83  
    84      def assertContainerExists(self, member, msg=None):  # pylint: disable=invalid-name
    85          r = requests.get(self.uri(f"/containers/{member}/exists"))
    86          if r.status_code == 404:
    87              if msg is None:
    88                  msg = f"Container '{member}' does not exist."
    89              self.failureException(msg)
    90  
    91      def assertContainerNotExists(self, member, msg=None):  # pylint: disable=invalid-name
    92          r = requests.get(self.uri(f"/containers/{member}/exists"))
    93          if r.status_code == 204:
    94              if msg is None:
    95                  msg = f"Container '{member}' exists."
    96              self.failureException(msg)
    97  
    98      def assertId(self, content):  # pylint: disable=invalid-name
    99          objects = json.loads(content)
   100          try:
   101              if isinstance(objects, dict):
   102                  _ = objects["Id"]
   103              else:
   104                  for item in objects:
   105                      _ = item["Id"]
   106          except KeyError:
   107              self.failureException("Failed in find 'Id' in return value.")