github.com/darrenli6/fabric-sdk-example@v0.0.0-20220109053535-94b13b56df8c/bddtests/steps/bdd_test_util.py (about)

     1  
     2  # Copyright IBM Corp. 2016 All Rights Reserved.
     3  #
     4  # Licensed under the Apache License, Version 2.0 (the "License");
     5  # you may not use this file except in compliance with the License.
     6  # You may obtain a copy of the License at
     7  #
     8  #      http://www.apache.org/licenses/LICENSE-2.0
     9  #
    10  # Unless required by applicable law or agreed to in writing, software
    11  # distributed under the License is distributed on an "AS IS" BASIS,
    12  # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  # See the License for the specific language governing permissions and
    14  # limitations under the License.
    15  #
    16  
    17  import os
    18  import re
    19  import subprocess
    20  
    21  def cli_call(arg_list, expect_success=True, env=os.environ.copy()):
    22      """Executes a CLI command in a subprocess and return the results.
    23  
    24      @param arg_list: a list command arguments
    25      @param expect_success: use False to return even if an error occurred when executing the command
    26      @return: (string, string, int) output message, error message, return code
    27      """
    28      # We need to run the cli command by actually calling the python command
    29      # the update-cli.py script has a #!/bin/python as the first line
    30      # which calls the system python, not the virtual env python we
    31      # setup for running the update-cli
    32      p = subprocess.Popen(arg_list, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env)
    33      output, error = p.communicate()
    34      if p.returncode != 0:
    35          if output is not None:
    36              print("Output:\n" + output)
    37          if error is not None:
    38              print("Error Message:\n" + error)
    39          if expect_success:
    40              raise subprocess.CalledProcessError(p.returncode, arg_list, output)
    41      return output, error, p.returncode
    42  
    43  class UserRegistration:
    44      def __init__(self, secretMsg, composeService):
    45          self.secretMsg = secretMsg
    46          self.composeService = composeService
    47          self.tags = {}
    48          self.lastResult = None
    49  
    50      def getUserName(self):
    51          return self.secretMsg['enrollId']
    52  
    53  # Registerses a user on a specific composeService
    54  def registerUser(context, secretMsg, composeService):
    55      userName = secretMsg['enrollId']
    56      if 'users' in context:
    57          pass
    58      else:
    59          context.users = {}
    60      if userName in context.users:
    61          raise Exception("User already registered: {0}".format(userName))
    62      context.users[userName] = UserRegistration(secretMsg, composeService)
    63  
    64  # Registerses a user on a specific composeService
    65  def getUserRegistration(context, enrollId):
    66      userRegistration = None
    67      if 'users' in context:
    68          pass
    69      else:
    70          context.users = {}
    71      if enrollId in context.users:
    72          userRegistration = context.users[enrollId]
    73      else:
    74          raise Exception("User has not been registered: {0}".format(enrollId))
    75      return userRegistration
    76  
    77  
    78  def ipFromContainerNamePart(namePart, containerDataList):
    79      """Returns the IPAddress based upon a name part of the full container name"""
    80      containerData = containerDataFromNamePart(namePart, containerDataList)
    81  
    82      if containerData == None:
    83          raise Exception("Could not find container with namePart = {0}".format(namePart))
    84  
    85      return containerData.ipAddress
    86  
    87  def getPortHostMapping(compose_container_data, compose_service_name, port, protocol='tcp'):
    88      """returns (host_ip, host_port)
    89      Returns the host IP address port and port that maps to a container's exposed port.
    90      If the port is not mapped, then the actual container IP address is returned.
    91      """
    92      container = containerDataFromNamePart(compose_service_name, compose_container_data)
    93      if container:
    94          port_protocol = '%s/%s' % (port, protocol)
    95          if port_protocol in container.ports:
    96              port_mapping = container.ports[port_protocol]
    97              host_ip = port_mapping[0]['HostIp']
    98              host_port = int(port_mapping[0]['HostPort'])
    99              return host_ip, host_port
   100          else:
   101              print('WARNING: Could not find port mapping for port {0}'.format(port_protocol))
   102              # TODO so we don't break existing docker-compose tests on Vagrant just yet
   103              print('WARNING: Returning the actual container IP address, which might not be routable from the host.')
   104              return container.ipAddress, port
   105      else:
   106          raise Exception("Could not find container for service '{0}'".format(compose_service_name))
   107  
   108  def fullNameFromContainerNamePart(namePart, containerDataList):
   109      containerData = containerDataFromNamePart(namePart, containerDataList)
   110  
   111      if containerData == None:
   112          raise Exception("Could not find container with namePart = {0}".format(namePart))
   113  
   114      return containerData.containerName
   115  
   116  def containerDataFromNamePart(namePart, containerDataList):
   117      for containerData in containerDataList:
   118          if containerData.composeService == namePart:
   119              return containerData
   120      raise Exception("composeService not found: {0}".format(namePart))
   121  
   122  def getContainerDataValuesFromContext(context, aliases, callback):
   123      """Returns the IPAddress based upon a name part of the full container name"""
   124      assert 'compose_containers' in context, "compose_containers not found in context"
   125      values = []
   126      for namePart in aliases:
   127          for containerData in context.compose_containers:
   128              if containerData.composeService == namePart:
   129                  values.append(callback(containerData))
   130                  break
   131      return values
   132  
   133  def start_background_process(context, program_name, arg_list):
   134      p = subprocess.Popen(arg_list, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
   135      setattr(context, program_name, p)