github.com/AbhinandanKurakure/podman/v3@v3.4.10/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      def resolve_container(self, path):
    68          """Find 'first' container and return 'Id' formatted into given URI path."""
    69  
    70          try:
    71              r = requests.get(self.uri("/containers/json?all=true"))
    72              containers = r.json()
    73          except Exception as e:
    74              msg = f"Bad container response: {e}"
    75              if r is not None:
    76                  msg += ": " + r.text
    77              raise self.failureException(msg)
    78          return path.format(containers[0]["Id"])
    79  
    80      def assertContainerExists(self, member, msg=None):  # pylint: disable=invalid-name
    81          r = requests.get(self.uri(f"/containers/{member}/exists"))
    82          if r.status_code == 404:
    83              if msg is None:
    84                  msg = f"Container '{member}' does not exist."
    85              self.failureException(msg)
    86  
    87      def assertContainerNotExists(self, member, msg=None):  # pylint: disable=invalid-name
    88          r = requests.get(self.uri(f"/containers/{member}/exists"))
    89          if r.status_code == 204:
    90              if msg is None:
    91                  msg = f"Container '{member}' exists."
    92              self.failureException(msg)
    93  
    94      def assertId(self, content):  # pylint: disable=invalid-name
    95          objects = json.loads(content)
    96          try:
    97              if isinstance(objects, dict):
    98                  _ = objects["Id"]
    99              else:
   100                  for item in objects:
   101                      _ = item["Id"]
   102          except KeyError:
   103              self.failureException("Failed in find 'Id' in return value.")