python自动化测试之DDT数据驱动的实现代码

论坛 期权论坛 脚本     
niminba   2021-5-23 04:04   1292   0

时隔已久,再次冒烟,自动化测试工作仍在继续,自动化测试中的数据驱动技术尤为重要,不然咋去实现数据分离呢,对吧,这里就简单介绍下与传统unittest自动化测试框架匹配的DDT数据驱动技术。

话不多说,先撸一波源码,其实整体代码并不多

# -*- coding: utf-8 -*-
# This file is a part of DDT (https://github.com/txels/ddt)
# Copyright 2012-2015 Carles Barrobés and DDT contributors
# For the exact contribution history, see the git revision log.
# DDT is licensed under the MIT License, included in
# https://github.com/txels/ddt/blob/master/LICENSE.md
import inspect
import json
import os
import re
import codecs
from functools import wraps
try:
  import yaml
except ImportError: # pragma: no cover
  _have_yaml = False
else:
  _have_yaml = True
__version__ = '1.2.1'
# These attributes will not conflict with any real python attribute
# They are added to the decorated test method and processed later
# by the `ddt` class decorator.
DATA_ATTR = '%values'   # store the data the test must run with
FILE_ATTR = '%file_path'  # store the path to JSON file
UNPACK_ATTR = '%unpack'  # remember that we have to unpack values
index_len = 5       # default max length of case index
try:
  trivial_types = (type(None), bool, int, float, basestring)
except NameError:
  trivial_types = (type(None), bool, int, float, str)
def is_trivial(value):
  if isinstance(value, trivial_types):
    return True
  elif isinstance(value, (list, tuple)):
    return all(map(is_trivial, value))
  return False
def unpack(func):
  """
  Method decorator to add unpack feature.
  """
  setattr(func, UNPACK_ATTR, True)
  return func
def data(*values):
  """
  Method decorator to add to your test methods.
  Should be added to methods of instances of ``unittest.TestCase``.
  """
  global index_len
  index_len = len(str(len(values)))
  return idata(values)
def idata(iterable):
  """
  Method decorator to add to your test methods.
  Should be added to methods of instances of ``unittest.TestCase``.
  """
  def wrapper(func):
    setattr(func, DATA_ATTR, iterable)
    return func
  return wrapper
def file_data(value):
  """
  Method decorator to add to your test methods.
  Should be added to methods of instances of ``unittest.TestCase``.
  ``value`` should be a path relative to the directory of the file
  containing the decorated ``unittest.TestCase``. The file
  should contain JSON encoded data, that can either be a list or a
  dict.
  In case of a list, each value in the list will correspond to one
  test case, and the value will be concatenated to the test method
  name.
  In case of a dict, keys will be used as suffixes to the name of the
  test case, and values will be fed as test data.
  """
  def wrapper(func):
    setattr(func, FILE_ATTR, value)
    return func
  return wrapper
def mk_test_name(name, value, index=0):
  """
  Generate a new name for a test case.
  It will take the original test name and append an ordinal index and a
  string representation of the value, and convert the result into a valid
  python identifier by replacing extraneous characters with ``_``.
  We avoid doing str(value) if dealing with non-trivial values.
  The problem is possible different names with different runs, e.g.
  different order of dictionary keys (see PYTHONHASHSEED) or dealing
  with mock objects.
  Trivial scalar values are passed as is.
  A "trivial" value is a plain scalar, or a tuple or list consisting
  only of trivial values.
  """
  # Add zeros before index to keep order
  index = "{0:0{1}}".format(index + 1, index_len)
  if not is_trivial(value):
    return "{0}_{1}".format(name, index)
  try:
    value = str(value)
  except UnicodeEncodeError:
    # fallback for python2
    value = value.encode('ascii', 'backslashreplace')
  test_name = "{0}_{1}_{2}".format(name, index, value)
  return re.sub(r'\W|^(?=\d)', '_', test_name)
def feed_data(func, new_name, test_data_docstring, *args, **kwargs):
  """
  This internal method decorator feeds the test data item to the test.
  """
  @wraps(func)
  def wrapper(self):
    return func(self, *args, **kwargs)
  wrapper.__name__ = new_name
  wrapper.__wrapped__ = func
  # set docstring if exists
  if test_data_docstring is not None:
    wrapper.__doc__ = test_data_docstring
  else:
    # Try to call format on the docstring
    if func.__doc__:
      try:
        wrapper.__doc__ = func.__doc__.format(*args, **kwargs)
      except (IndexError, KeyError):
        # Maybe the user has added some of the formating strings
        # unintentionally in the docstring. Do not raise an exception
        # as it could be that user is not aware of the
        # formating feature.
        pass
  return wrapper
def add_test(cls, test_name, test_docstring, func, *args, **kwargs):
  """
  Add a test case to this class.
  The test will be based on an existing function but will give it a new
  name.
  """
  setattr(cls, test_name, feed_data(func, test_name, test_docstring,
      *args, **kwargs))
def process_file_data(cls, name, func, file_attr):
  """
  Process the parameter in the `file_data` decorator.
  """
  cls_path = os.path.abspath(inspect.getsourcefile(cls))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\[]H[[ydb]O]H[[ydbCB\[]
OOB]Bb;B[OH^X[Y\[Y[HZZ[Z[[^][KNKNMMLYL
M
YYXL[OH\NYY][NY[Z[N\]K\XX[\X^][NN]YX[
N\[NX[[]\\XX[^Z[[]\X[[Y\\X[]\X[XX[]]^\K]B!i9al9l9kjlyb9b. 9z$/y.d#gh/&.^89all9kjlyb9ayk{nm/c9k.#9_B[[OH.[B."`:/+%i)]!9c%bb9l9kjlyb9k. K9n#9&)"y`9n+b{i9i)"y.eye$y* ;l#&c#yi)8g*9i9.g.9')/c.+ OBi9/h:)h9"yn+b{(/k:/o{+#a!;,(,(
分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:1060120
帖子:212021
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP