INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
r""" Performs the predict step of the CKF. On return, self.x and
self.P contain the predicted state (x) and covariance (P).
Important: this MUST be called before update() is called for the first
time.
Parameters
----------
dt : double, optional
If specified... | def predict(self, dt=None, fx_args=()):
r""" Performs the predict step of the CKF. On return, self.x and
self.P contain the predicted state (x) and covariance (P).
Important: this MUST be called before update() is called for the first
time.
Parameters
----------
... |
Update the CKF with the given measurements. On return,
self.x and self.P contain the new mean and covariance of the filter.
Parameters
----------
z : numpy.array of shape (dim_z)
measurement vector
R : numpy.array((dim_z, dim_z)), optional
Measurement n... | def update(self, z, R=None, hx_args=()):
""" Update the CKF with the given measurements. On return,
self.x and self.P contain the new mean and covariance of the filter.
Parameters
----------
z : numpy.array of shape (dim_z)
measurement vector
R : numpy.arra... |
Add a new measurement (z) to the kalman filter. If z is None, nothing
is changed.
Parameters
----------
z : np.array
measurement for this update.
R : np.array, scalar, or None
Optionally provide R to override the measurement noise for this
o... | def update(self, z, R_inv=None):
"""
Add a new measurement (z) to the kalman filter. If z is None, nothing
is changed.
Parameters
----------
z : np.array
measurement for this update.
R : np.array, scalar, or None
Optionally provide R to ... |
Predict next position.
Parameters
----------
u : ndarray
Optional control vector. If non-zero, it is multiplied by B
to create the control input into the system. | def predict(self, u=0):
""" Predict next position.
Parameters
----------
u : ndarray
Optional control vector. If non-zero, it is multiplied by B
to create the control input into the system.
"""
# x = Fx + Bu
A = dot(self._F_inv.T, self.... |
Batch processes a sequences of measurements.
Parameters
----------
zs : list-like
list of measurements at each time step `self.dt` Missing
measurements must be represented by 'None'.
Rs : list-like, optional
optional list of values to use for the me... | def batch_filter(self, zs, Rs=None, update_first=False, saver=None):
""" Batch processes a sequences of measurements.
Parameters
----------
zs : list-like
list of measurements at each time step `self.dt` Missing
measurements must be represented by 'None'.
... |
State Transition matrix | def F(self, value):
"""State Transition matrix"""
self._F = value
self._F_inv = self.inv(self._F) |
computes 4th order Runge-Kutta for dy/dx.
Parameters
----------
y : scalar
Initial/current value for y
x : scalar
Initial/current value for x
dx : scalar
difference in x (e.g. the time step)
f : ufunc(y,x)
Callable function (y, x) that you supply to compute dy/d... | def runge_kutta4(y, x, dx, f):
"""computes 4th order Runge-Kutta for dy/dx.
Parameters
----------
y : scalar
Initial/current value for y
x : scalar
Initial/current value for x
dx : scalar
difference in x (e.g. the time step)
f : ufunc(y,x)
Callable function ... |
Generates a pretty printed NumPy array with an assignment. Optionally
transposes column vectors so they are drawn on one line. Strictly speaking
arr can be any time convertible by `str(arr)`, but the output may not
be what you want if the type of the variable is not a scalar or an
ndarray.
Examples... | def pretty_str(label, arr):
"""
Generates a pretty printed NumPy array with an assignment. Optionally
transposes column vectors so they are drawn on one line. Strictly speaking
arr can be any time convertible by `str(arr)`, but the output may not
be what you want if the type of the variable is not a... |
ensure z is a (dim_z, 1) shaped vector | def reshape_z(z, dim_z, ndim):
""" ensure z is a (dim_z, 1) shaped vector"""
z = np.atleast_2d(z)
if z.shape[1] == dim_z:
z = z.T
if z.shape != (dim_z, 1):
raise ValueError('z must be convertible to shape ({}, 1)'.format(dim_z))
if ndim == 1:
z = z[:, 0]
if ndim == 0:... |
Computes the inverse of a diagonal NxN np.array S. In general this will
be much faster than calling np.linalg.inv().
However, does NOT check if the off diagonal elements are non-zero. So long
as S is truly diagonal, the output is identical to np.linalg.inv().
Parameters
----------
S : np.array... | def inv_diagonal(S):
"""
Computes the inverse of a diagonal NxN np.array S. In general this will
be much faster than calling np.linalg.inv().
However, does NOT check if the off diagonal elements are non-zero. So long
as S is truly diagonal, the output is identical to np.linalg.inv().
Parameter... |
Computes the sum of the outer products of the rows in A and B
P = \Sum {A[i] B[i].T} for i in 0..N
Notionally:
P = 0
for y in A:
P += np.outer(y, y)
This is a standard computation for sigma points used in the UKF, ensemble
Kalman filter, etc., where A would be the... | def outer_product_sum(A, B=None):
"""
Computes the sum of the outer products of the rows in A and B
P = \Sum {A[i] B[i].T} for i in 0..N
Notionally:
P = 0
for y in A:
P += np.outer(y, y)
This is a standard computation for sigma points used in the UKF, ensemble... |
save the current state of the Kalman filter | def save(self):
""" save the current state of the Kalman filter"""
kf = self._kf
# force all attributes to be computed. this is only necessary
# if the class uses properties that compute data only when
# accessed
for prop in self.properties:
self._DL[prop[0]... |
Flattens any np.array of column vectors into 1D arrays. Basically,
this makes data readable for humans if you are just inspecting via
the REPL. For example, if you have saved a KalmanFilter object with 89
epochs, self.x will be shape (89, 9, 1) (for example). After flatten
is run, self.x... | def flatten(self):
"""
Flattens any np.array of column vectors into 1D arrays. Basically,
this makes data readable for humans if you are just inspecting via
the REPL. For example, if you have saved a KalmanFilter object with 89
epochs, self.x will be shape (89, 9, 1) (for example... |
Add a new measurement (z) to the Kalman filter. If z is None, nothing
is changed.
Parameters
----------
z : np.array
measurement for this update. | def update(self, z):
"""
Add a new measurement (z) to the Kalman filter. If z is None, nothing
is changed.
Parameters
----------
z : np.array
measurement for this update.
"""
# run update on each filter, and save the likelihood
for i... |
Predict next state (prior) using the IMM state propagation
equations.
Parameters
----------
u : np.array, optional
Control vector. If not `None`, it is multiplied by B
to create the control input into the system. | def predict(self, u=None):
"""
Predict next state (prior) using the IMM state propagation
equations.
Parameters
----------
u : np.array, optional
Control vector. If not `None`, it is multiplied by B
to create the control input into the system.
... |
Computes the IMM's mixed state estimate from each filter using
the the mode probability self.mu to weight the estimates. | def _compute_state_estimate(self):
"""
Computes the IMM's mixed state estimate from each filter using
the the mode probability self.mu to weight the estimates.
"""
self.x.fill(0)
for f, mu in zip(self.filters, self.mu):
self.x += f.x * mu
self.P.fill(... |
Compute the mixing probability for each filter. | def _compute_mixing_probabilities(self):
"""
Compute the mixing probability for each filter.
"""
self.cbar = dot(self.mu, self.M)
for i in range(self.N):
for j in range(self.N):
self.omega[i, j] = (self.M[i, j]*self.mu[i]) / self.cbar[j] |
r"""
Performs the predict step of the UKF. On return, self.x and
self.P contain the predicted state (x) and covariance (P). '
Important: this MUST be called before update() is called for the first
time.
Parameters
----------
dt : double, optional
If... | def predict(self, dt=None, UT=None, fx=None, **fx_args):
r"""
Performs the predict step of the UKF. On return, self.x and
self.P contain the predicted state (x) and covariance (P). '
Important: this MUST be called before update() is called for the first
time.
Parameters... |
Update the UKF with the given measurements. On return,
self.x and self.P contain the new mean and covariance of the filter.
Parameters
----------
z : numpy.array of shape (dim_z)
measurement vector
R : numpy.array((dim_z, dim_z)), optional
Measurement n... | def update(self, z, R=None, UT=None, hx=None, **hx_args):
"""
Update the UKF with the given measurements. On return,
self.x and self.P contain the new mean and covariance of the filter.
Parameters
----------
z : numpy.array of shape (dim_z)
measurement vecto... |
Compute cross variance of the state `x` and measurement `z`. | def cross_variance(self, x, z, sigmas_f, sigmas_h):
"""
Compute cross variance of the state `x` and measurement `z`.
"""
Pxz = zeros((sigmas_f.shape[1], sigmas_h.shape[1]))
N = sigmas_f.shape[0]
for i in range(N):
dx = self.residual_x(sigmas_f[i], x)
... |
Performs the UKF filter over the list of measurement in `zs`.
Parameters
----------
zs : list-like
list of measurements at each time step `self._dt` Missing
measurements must be represented by 'None'.
Rs : None, np.array or list-like, default=None
o... | def batch_filter(self, zs, Rs=None, dts=None, UT=None, saver=None):
"""
Performs the UKF filter over the list of measurement in `zs`.
Parameters
----------
zs : list-like
list of measurements at each time step `self._dt` Missing
measurements must be repr... |
Runs the Rauch-Tung-Striebal Kalman smoother on a set of
means and covariances computed by the UKF. The usual input
would come from the output of `batch_filter()`.
Parameters
----------
Xs : numpy.array
array of the means (state variable x) of the output of a Kalman
... | def rts_smoother(self, Xs, Ps, Qs=None, dts=None, UT=None):
"""
Runs the Rauch-Tung-Striebal Kalman smoother on a set of
means and covariances computed by the UKF. The usual input
would come from the output of `batch_filter()`.
Parameters
----------
Xs : numpy.a... |
Returns slant range to the object. Call once for each
new measurement at dt time from last call. | def get_range(self, process_err_pct=0.05):
"""
Returns slant range to the object. Call once for each
new measurement at dt time from last call.
"""
vel = self.vel + 5 * randn()
alt = self.alt + 10 * randn()
self.pos += vel*self.dt
err = (self.pos * proc... |
Predict next position using the Kalman filter state propagation
equations for each filter in the bank.
Parameters
----------
u : np.array
Optional control vector. If non-zero, it is multiplied by B
to create the control input into the system. | def predict(self, u=0):
"""
Predict next position using the Kalman filter state propagation
equations for each filter in the bank.
Parameters
----------
u : np.array
Optional control vector. If non-zero, it is multiplied by B
to create the contro... |
Add a new measurement (z) to the Kalman filter. If z is None, nothing
is changed.
Parameters
----------
z : np.array
measurement for this update.
R : np.array, scalar, or None
Optionally provide R to override the measurement noise for this
o... | def update(self, z, R=None, H=None):
"""
Add a new measurement (z) to the Kalman filter. If z is None, nothing
is changed.
Parameters
----------
z : np.array
measurement for this update.
R : np.array, scalar, or None
Optionally provide R... |
Performs the residual resampling algorithm used by particle filters.
Based on observation that we don't need to use random numbers to select
most of the weights. Take int(N*w^i) samples of each particle i, and then
resample any remaining using a standard resampling algorithm [1]
Parameters
------... | def residual_resample(weights):
""" Performs the residual resampling algorithm used by particle filters.
Based on observation that we don't need to use random numbers to select
most of the weights. Take int(N*w^i) samples of each particle i, and then
resample any remaining using a standard resampling a... |
Performs the stratified resampling algorithm used by particle filters.
This algorithms aims to make selections relatively uniformly across the
particles. It divides the cumulative sum of the weights into N equal
divisions, and then selects one particle randomly from each division. This
guarantees that ... | def stratified_resample(weights):
""" Performs the stratified resampling algorithm used by particle filters.
This algorithms aims to make selections relatively uniformly across the
particles. It divides the cumulative sum of the weights into N equal
divisions, and then selects one particle randomly fro... |
Performs the systemic resampling algorithm used by particle filters.
This algorithm separates the sample space into N divisions. A single random
offset is used to to choose where to sample from for all divisions. This
guarantees that every sample is exactly 1/N apart.
Parameters
----------
wei... | def systematic_resample(weights):
""" Performs the systemic resampling algorithm used by particle filters.
This algorithm separates the sample space into N divisions. A single random
offset is used to to choose where to sample from for all divisions. This
guarantees that every sample is exactly 1/N apa... |
This is the naive form of roulette sampling where we compute the
cumulative sum of the weights and then use binary search to select the
resampled point based on a uniformly distributed random number. Run time
is O(n log n). You do not want to use this algorithm in practice; for some
reason it is popular... | def multinomial_resample(weights):
""" This is the naive form of roulette sampling where we compute the
cumulative sum of the weights and then use binary search to select the
resampled point based on a uniformly distributed random number. Run time
is O(n log n). You do not want to use this algorithm in ... |
Add a new measurement `z` to the H-Infinity filter. If `z` is None,
nothing is changed.
Parameters
----------
z : ndarray
measurement for this update. | def update(self, z):
"""
Add a new measurement `z` to the H-Infinity filter. If `z` is None,
nothing is changed.
Parameters
----------
z : ndarray
measurement for this update.
"""
if z is None:
return
# rename for readabi... |
Predict next position.
Parameters
----------
u : ndarray
Optional control vector. If non-zero, it is multiplied by `B`
to create the control input into the system. | def predict(self, u=0):
"""
Predict next position.
Parameters
----------
u : ndarray
Optional control vector. If non-zero, it is multiplied by `B`
to create the control input into the system.
"""
# x = Fx + Bu
self.x = dot(self.F,... |
Batch processes a sequences of measurements.
Parameters
----------
Zs : list-like
list of measurements at each time step `self.dt` Missing
measurements must be represented by 'None'.
update_first : bool, default=False, optional,
controls whether the ... | def batch_filter(self, Zs,update_first=False, saver=False):
""" Batch processes a sequences of measurements.
Parameters
----------
Zs : list-like
list of measurements at each time step `self.dt` Missing
measurements must be represented by 'None'.
update_... |
Predicts the next state of the filter and returns it. Does not
alter the state of the filter.
Parameters
----------
u : ndarray
optional control input
Returns
-------
x : ndarray
State vector of the prediction. | def get_prediction(self, u=0):
""" Predicts the next state of the filter and returns it. Does not
alter the state of the filter.
Parameters
----------
u : ndarray
optional control input
Returns
-------
x : ndarray
State vector of ... |
measurement noise matrix | def V(self, value):
""" measurement noise matrix"""
if np.isscalar(value):
self._V = np.array([[value]], dtype=float)
else:
self._V = value
self._V_inv = linalg.inv(self._V) |
Add a new measurement (z) to the kalman filter. If z is None, nothing
is changed.
Parameters
----------
z : np.array
measurement for this update.
R2 : np.array, scalar, or None
Sqrt of meaaurement noize. Optionally provide to override the
me... | def update(self, z, R2=None):
"""
Add a new measurement (z) to the kalman filter. If z is None, nothing
is changed.
Parameters
----------
z : np.array
measurement for this update.
R2 : np.array, scalar, or None
Sqrt of meaaurement noize.... |
Predict next state (prior) using the Kalman filter state propagation
equations.
Parameters
----------
u : np.array, optional
Optional control vector. If non-zero, it is multiplied by B
to create the control input into the system. | def predict(self, u=0):
"""
Predict next state (prior) using the Kalman filter state propagation
equations.
Parameters
----------
u : np.array, optional
Optional control vector. If non-zero, it is multiplied by B
to create the control input into ... |
Process uncertainty | def Q(self, value):
""" Process uncertainty"""
self._Q = value
self._Q1_2 = cholesky(self._Q, lower=True) |
covariance matrix | def P(self, value):
""" covariance matrix"""
self._P = value
self._P1_2 = cholesky(self._P, lower=True) |
measurement uncertainty | def R(self, value):
""" measurement uncertainty"""
self._R = value
self._R1_2 = cholesky(self._R, lower=True) |
This hook is called to determine if the websocket should return
an HTTP response and close.
Our behavior here is to start the ASGI application, and then wait
for either `accept` or `close` in order to determine if we should
close the connection. | async def process_request(self, path, headers):
"""
This hook is called to determine if the websocket should return
an HTTP response and close.
Our behavior here is to start the ASGI application, and then wait
for either `accept` or `close` in order to determine if we should
... |
This is the main handler function for the 'websockets' implementation
to call into. We just wait for close then return, and instead allow
'send' and 'receive' events to drive the flow. | async def ws_handler(self, protocol, path):
"""
This is the main handler function for the 'websockets' implementation
to call into. We just wait for close then return, and instead allow
'send' and 'receive' events to drive the flow.
"""
self.handshake_completed_event.set(... |
Wrapper around the ASGI callable, handling exceptions and unexpected
termination states. | async def run_asgi(self):
"""
Wrapper around the ASGI callable, handling exceptions and unexpected
termination states.
"""
try:
result = await self.app(self.scope, self.asgi_receive, self.asgi_send)
except BaseException as exc:
self.closed_event.se... |
Called by the server to commence a graceful shutdown. | def shutdown(self):
"""
Called by the server to commence a graceful shutdown.
"""
if self.cycle is None or self.cycle.response_complete:
self.transport.close()
else:
self.cycle.keep_alive = False |
Called by the server to commence a graceful shutdown. | def shutdown(self):
"""
Called by the server to commence a graceful shutdown.
"""
if self.cycle is None or self.cycle.response_complete:
event = h11.ConnectionClosed()
self.conn.send(event)
self.transport.close()
else:
self.cycle.ke... |
Called on a keep-alive connection if no new data is received after a short delay. | def timeout_keep_alive_handler(self):
"""
Called on a keep-alive connection if no new data is received after a short delay.
"""
if not self.transport.is_closing():
event = h11.ConnectionClosed()
self.conn.send(event)
self.transport.close() |
Builds a scope and request message into a WSGI environ object. | def build_environ(scope, message, body):
"""
Builds a scope and request message into a WSGI environ object.
"""
environ = {
"REQUEST_METHOD": scope["method"],
"SCRIPT_NAME": "",
"PATH_INFO": scope["path"],
"QUERY_STRING": scope["query_string"].decode("ascii"),
"SE... |
Return an ASGI message, with any body-type content omitted and replaced
with a placeholder. | def message_with_placeholders(message):
"""
Return an ASGI message, with any body-type content omitted and replaced
with a placeholder.
"""
new_message = message.copy()
for attr in PLACEHOLDER_FORMAT.keys():
if message.get(attr) is not None:
content = message[attr]
... |
setup root logger with ColoredFormatter. | def setup_logger(log_level, log_file=None):
"""setup root logger with ColoredFormatter."""
level = getattr(logging, log_level.upper(), None)
if not level:
color_print("Invalid log level: %s" % log_level, "RED")
sys.exit(1)
# hide traceback when log level is INFO/WARNING/ERROR/CRITICAL
... |
log with color by different level | def log_with_color(level):
""" log with color by different level
"""
def wrapper(text):
color = log_colors_config[level.upper()]
getattr(logger, level.lower())(coloring(text, color))
return wrapper |
call hook actions.
Args:
actions (list): each action in actions list maybe in two format.
format1 (dict): assignment, the value returned by hook function will be assigned to variable.
{"var": "${func()}"}
format2 (str): only call hook functions.
... | def do_hook_actions(self, actions, hook_type):
""" call hook actions.
Args:
actions (list): each action in actions list maybe in two format.
format1 (dict): assignment, the value returned by hook function will be assigned to variable.
{"var": "${func()}"... |
handle skip feature for test
- skip: skip current test unconditionally
- skipIf: skip current test if condition is true
- skipUnless: skip current test unless condition is true
Args:
test_dict (dict): test info
Raises:
SkipTest: skip test | def _handle_skip_feature(self, test_dict):
""" handle skip feature for test
- skip: skip current test unconditionally
- skipIf: skip current test if condition is true
- skipUnless: skip current test unless condition is true
Args:
test_dict (dict): test in... |
extract output variables | def extract_output(self, output_variables_list):
""" extract output variables
"""
variables_mapping = self.session_context.session_variables_mapping
output = {}
for variable in output_variables_list:
if variable not in variables_mapping:
logger.log_wa... |
run tests in test_suite
Args:
test_suite: unittest.TestSuite()
Returns:
list: tests_results | def _run_suite(self, test_suite):
""" run tests in test_suite
Args:
test_suite: unittest.TestSuite()
Returns:
list: tests_results
"""
tests_results = []
for testcase in test_suite:
testcase_name = testcase.config.get("name")
... |
aggregate results
Args:
tests_results (list): list of (testcase, result) | def _aggregate(self, tests_results):
""" aggregate results
Args:
tests_results (list): list of (testcase, result)
"""
summary = {
"success": True,
"stat": {
"testcases": {
"total": len(tests_results),
... |
run testcase/testsuite file or folder.
Args:
path (str): testcase/testsuite file/foler path.
dot_env_path (str): specified .env file path.
mapping (dict): if mapping is specified, it will override variables in config block.
Returns:
instance: HttpRunner(... | def run_path(self, path, dot_env_path=None, mapping=None):
""" run testcase/testsuite file or folder.
Args:
path (str): testcase/testsuite file/foler path.
dot_env_path (str): specified .env file path.
mapping (dict): if mapping is specified, it will override variabl... |
main interface.
Args:
path_or_tests:
str: testcase/testsuite file/foler path
dict: valid testcase/testsuite data | def run(self, path_or_tests, dot_env_path=None, mapping=None):
""" main interface.
Args:
path_or_tests:
str: testcase/testsuite file/foler path
dict: valid testcase/testsuite data
"""
if validator.is_testcase_path(path_or_tests):
... |
set variables mapping to os.environ | def set_os_environ(variables_mapping):
""" set variables mapping to os.environ
"""
for variable in variables_mapping:
os.environ[variable] = variables_mapping[variable]
logger.log_debug("Set OS environment variable: {}".format(variable)) |
set variables mapping to os.environ | def unset_os_environ(variables_mapping):
""" set variables mapping to os.environ
"""
for variable in variables_mapping:
os.environ.pop(variable)
logger.log_debug("Unset OS environment variable: {}".format(variable)) |
prepend url with base_url unless it's already an absolute URL | def build_url(base_url, path):
""" prepend url with base_url unless it's already an absolute URL """
if absolute_http_url_regexp.match(path):
return path
elif base_url:
return "{}/{}".format(base_url.rstrip("/"), path.lstrip("/"))
else:
raise ParamsError("base url missed!") |
Do an xpath-like query with json_content.
Args:
json_content (dict/list/string): content to be queried.
query (str): query string.
delimiter (str): delimiter symbol.
Returns:
str: queried result.
Examples:
>>> json_content = {
"ids": [1, 2, 3, 4],
... | def query_json(json_content, query, delimiter='.'):
""" Do an xpath-like query with json_content.
Args:
json_content (dict/list/string): content to be queried.
query (str): query string.
delimiter (str): delimiter symbol.
Returns:
str: queried result.
Examples:
... |
update origin dict with override dict recursively
e.g. origin_dict = {'a': 1, 'b': {'c': 2, 'd': 4}}
override_dict = {'b': {'c': 3}}
return: {'a': 1, 'b': {'c': 3, 'd': 4}} | def deep_update_dict(origin_dict, override_dict):
""" update origin dict with override dict recursively
e.g. origin_dict = {'a': 1, 'b': {'c': 2, 'd': 4}}
override_dict = {'b': {'c': 3}}
return: {'a': 1, 'b': {'c': 3, 'd': 4}}
"""
if not override_dict:
return origin_dict
for ke... |
convert dict to params string
Args:
src_dict (dict): source mapping data structure
Returns:
str: string params data
Examples:
>>> src_dict = {
"a": 1,
"b": 2
}
>>> convert_dict_to_params(src_dict)
>>> "a=1&b=2" | def convert_dict_to_params(src_dict):
""" convert dict to params string
Args:
src_dict (dict): source mapping data structure
Returns:
str: string params data
Examples:
>>> src_dict = {
"a": 1,
"b": 2
}
>>> convert_dict_to_params(src_dict... |
convert keys in dict to lower case
Args:
origin_dict (dict): mapping data structure
Returns:
dict: mapping with all keys lowered.
Examples:
>>> origin_dict = {
"Name": "",
"Request": "",
"URL": "",
"METHOD": "",
"Headers"... | def lower_dict_keys(origin_dict):
""" convert keys in dict to lower case
Args:
origin_dict (dict): mapping data structure
Returns:
dict: mapping with all keys lowered.
Examples:
>>> origin_dict = {
"Name": "",
"Request": "",
"URL": "",
... |
deepcopy dict data, ignore file object (_io.BufferedReader)
Args:
data (dict): dict data structure
{
'a': 1,
'b': [2, 4],
'c': lambda x: x+1,
'd': open('LICENSE'),
'f': {
'f1': {'a1': 2},
... | def deepcopy_dict(data):
""" deepcopy dict data, ignore file object (_io.BufferedReader)
Args:
data (dict): dict data structure
{
'a': 1,
'b': [2, 4],
'c': lambda x: x+1,
'd': open('LICENSE'),
'f': {
... |
ensure variables are in mapping format.
Args:
variables (list/dict): original variables
Returns:
dict: ensured variables in dict format
Examples:
>>> variables = [
{"a": 1},
{"b": 2}
]
>>> print(ensure_mapping_format(variables))
... | def ensure_mapping_format(variables):
""" ensure variables are in mapping format.
Args:
variables (list/dict): original variables
Returns:
dict: ensured variables in dict format
Examples:
>>> variables = [
{"a": 1},
{"b": 2}
]
... |
extend raw_variables with override_variables.
override_variables will merge and override raw_variables.
Args:
raw_variables (list):
override_variables (list):
Returns:
dict: extended variables mapping
Examples:
>>> raw_variables = [{"var1": "val1"}, {"var2": "val2"... | def extend_variables(raw_variables, override_variables):
""" extend raw_variables with override_variables.
override_variables will merge and override raw_variables.
Args:
raw_variables (list):
override_variables (list):
Returns:
dict: extended variables mapping
Example... |
print info in mapping.
Args:
info_mapping (dict): input(variables) or output mapping.
Examples:
>>> info_mapping = {
"var_a": "hello",
"var_b": "world"
}
>>> info_mapping = {
"status_code": 500
}
>>> print_... | def print_info(info_mapping):
""" print info in mapping.
Args:
info_mapping (dict): input(variables) or output mapping.
Examples:
>>> info_mapping = {
"var_a": "hello",
"var_b": "world"
}
>>> info_mapping = {
"status_code"... |
create scaffold with specified project name. | def create_scaffold(project_name):
""" create scaffold with specified project name.
"""
if os.path.isdir(project_name):
logger.log_warning(u"Folder {} exists, please specify a new folder name.".format(project_name))
return
logger.color_print("Start to create new project: {}".format(proj... |
generate cartesian product for lists
Args:
args (list of list): lists to be generated with cartesian product
Returns:
list: cartesian product in list
Examples:
>>> arg1 = [{"a": 1}, {"a": 2}]
>>> arg2 = [{"x": 111, "y": 112}, {"x": 121, "y": 122}]
>>> args = [arg1... | def gen_cartesian_product(*args):
""" generate cartesian product for lists
Args:
args (list of list): lists to be generated with cartesian product
Returns:
list: cartesian product in list
Examples:
>>> arg1 = [{"a": 1}, {"a": 2}]
>>> arg2 = [{"x": 111, "y": 112}, {"x"... |
prettify JSON testcase format | def prettify_json_file(file_list):
""" prettify JSON testcase format
"""
for json_file in set(file_list):
if not json_file.endswith(".json"):
logger.log_warning("Only JSON file format can be prettified, skip: {}".format(json_file))
continue
logger.color_print("Start ... |
omit too long str/bytes | def omit_long_data(body, omit_len=512):
""" omit too long str/bytes
"""
if not isinstance(body, basestring):
return body
body_len = len(body)
if body_len <= omit_len:
return body
omitted_body = body[0:omit_len]
appendix_str = " ... OMITTED {} CHARACTORS ...".format(body_le... |
dump json data to file | def dump_json_file(json_data, pwd_dir_path, dump_file_name):
""" dump json data to file
"""
class PythonObjectEncoder(json.JSONEncoder):
def default(self, obj):
try:
return super().default(self, obj)
except TypeError:
return str(obj)
logs_... |
prepare dump file info. | def _prepare_dump_info(project_mapping, tag_name):
""" prepare dump file info.
"""
test_path = project_mapping.get("test_path") or "tests_mapping"
pwd_dir_path = project_mapping.get("PWD") or os.getcwd()
file_name, file_suffix = os.path.splitext(os.path.basename(test_path.rstrip("/")))
dump_file... |
dump tests data to json file.
the dumped file is located in PWD/logs folder.
Args:
json_data (list/dict): json data to dump
project_mapping (dict): project info
tag_name (str): tag name, loaded/parsed/summary | def dump_logs(json_data, project_mapping, tag_name):
""" dump tests data to json file.
the dumped file is located in PWD/logs folder.
Args:
json_data (list/dict): json data to dump
project_mapping (dict): project info
tag_name (str): tag name, loaded/parsed/summary
"""
... |
check testcase format if valid | def _check_format(file_path, content):
""" check testcase format if valid
"""
# TODO: replace with JSON schema validation
if not content:
# testcase file content is empty
err_msg = u"Testcase file content is empty: {}".format(file_path)
logger.log_error(err_msg)
raise exc... |
load yaml file and check file content format | def load_yaml_file(yaml_file):
""" load yaml file and check file content format
"""
with io.open(yaml_file, 'r', encoding='utf-8') as stream:
yaml_content = yaml.load(stream)
_check_format(yaml_file, yaml_content)
return yaml_content |
load json file and check file content format | def load_json_file(json_file):
""" load json file and check file content format
"""
with io.open(json_file, encoding='utf-8') as data_file:
try:
json_content = json.load(data_file)
except exceptions.JSONDecodeError:
err_msg = u"JSONDecodeError: JSON file format error:... |
load csv file and check file content format
Args:
csv_file (str): csv file path, csv file content is like below:
Returns:
list: list of parameters, each parameter is in dict format
Examples:
>>> cat csv_file
username,password
test1,111111
test2,222222
... | def load_csv_file(csv_file):
""" load csv file and check file content format
Args:
csv_file (str): csv file path, csv file content is like below:
Returns:
list: list of parameters, each parameter is in dict format
Examples:
>>> cat csv_file
username,password
te... |
load folder path, return all files endswith yml/yaml/json in list.
Args:
folder_path (str): specified folder path to load
recursive (bool): load files recursively if True
Returns:
list: files endswith yml/yaml/json | def load_folder_files(folder_path, recursive=True):
""" load folder path, return all files endswith yml/yaml/json in list.
Args:
folder_path (str): specified folder path to load
recursive (bool): load files recursively if True
Returns:
list: files endswith yml/yaml/json
"""
... |
load .env file.
Args:
dot_env_path (str): .env file path
Returns:
dict: environment variables mapping
{
"UserName": "debugtalk",
"Password": "123456",
"PROJECT_KEY": "ABCDEFGH"
}
Raises:
exceptions.FileFormat... | def load_dot_env_file(dot_env_path):
""" load .env file.
Args:
dot_env_path (str): .env file path
Returns:
dict: environment variables mapping
{
"UserName": "debugtalk",
"Password": "123456",
"PROJECT_KEY": "ABCDEFGH"
... |
locate filename and return absolute file path.
searching will be recursive upward until current working directory.
Args:
start_path (str): start locating path, maybe file path or directory path
Returns:
str: located file path. None if file not found.
Raises:
exceptions.Fil... | def locate_file(start_path, file_name):
""" locate filename and return absolute file path.
searching will be recursive upward until current working directory.
Args:
start_path (str): start locating path, maybe file path or directory path
Returns:
str: located file path. None if fil... |
load python module functions.
Args:
module: python module
Returns:
dict: functions mapping for specified python module
{
"func1_name": func1,
"func2_name": func2
} | def load_module_functions(module):
""" load python module functions.
Args:
module: python module
Returns:
dict: functions mapping for specified python module
{
"func1_name": func1,
"func2_name": func2
}
"""
module_functions ... |
extend with api reference
Raises:
exceptions.ApiNotFound: api not found | def __extend_with_api_ref(raw_testinfo):
""" extend with api reference
Raises:
exceptions.ApiNotFound: api not found
"""
api_name = raw_testinfo["api"]
# api maybe defined in two types:
# 1, individual file: each file is corresponding to one api definition
# 2, api sets file: one ... |
load api/testcases/testsuites definitions from folder.
Args:
folder_path (str): api/testcases/testsuites files folder.
Returns:
dict: api definition mapping.
{
"tests/api/basic.yml": [
{"api": {"def": "api_login", "request": {}, "validate": []}}... | def load_folder_content(folder_path):
""" load api/testcases/testsuites definitions from folder.
Args:
folder_path (str): api/testcases/testsuites files folder.
Returns:
dict: api definition mapping.
{
"tests/api/basic.yml": [
{"api": {"def"... |
load api definitions from api folder.
Args:
api_folder_path (str): api files folder.
api file should be in the following format:
[
{
"api": {
"def": "api_login",
"request": {},
... | def load_api_folder(api_folder_path):
""" load api definitions from api folder.
Args:
api_folder_path (str): api files folder.
api file should be in the following format:
[
{
"api": {
"def": "api_login",
... |
API test: parse command line options and run commands. | def main_hrun():
""" API test: parse command line options and run commands.
"""
import argparse
from httprunner import logger
from httprunner.__about__ import __description__, __version__
from httprunner.api import HttpRunner
from httprunner.compat import is_py2
from httprunner.validator... |
Performance test with locust: parse command line options and run commands. | def main_locust():
""" Performance test with locust: parse command line options and run commands.
"""
# monkey patch ssl at beginning to avoid RecursionError when running locust.
from gevent import monkey; monkey.patch_ssl()
import multiprocessing
import sys
from httprunner import logger
... |
check if variable or function exist | def is_var_or_func_exist(content):
""" check if variable or function exist
"""
if not isinstance(content, basestring):
return False
try:
match_start_position = content.index("$", 0)
except ValueError:
return False
while match_start_position < len(content):
dolla... |
extract all variable names from content, which is in format $variable
Args:
content (str): string content
Returns:
list: variables list extracted from string content
Examples:
>>> regex_findall_variables("$variable")
["variable"]
>>> regex_findall_variables("/blog... | def regex_findall_variables(content):
""" extract all variable names from content, which is in format $variable
Args:
content (str): string content
Returns:
list: variables list extracted from string content
Examples:
>>> regex_findall_variables("$variable")
["variable... |
parse parameters and generate cartesian product.
Args:
parameters (list) parameters: parameter name and value in list
parameter value may be in three types:
(1) data list, e.g. ["iOS/10.1", "iOS/10.2", "iOS/10.3"]
(2) call built-in parameterize function, "${param... | def parse_parameters(parameters, variables_mapping=None, functions_mapping=None):
""" parse parameters and generate cartesian product.
Args:
parameters (list) parameters: parameter name and value in list
parameter value may be in three types:
(1) data list, e.g. ["iOS/10.1",... |
get variable from variables_mapping.
Args:
variable_name (str): variable name
variables_mapping (dict): variables mapping
Returns:
mapping variable value.
Raises:
exceptions.VariableNotFound: variable is not found. | def get_mapping_variable(variable_name, variables_mapping):
""" get variable from variables_mapping.
Args:
variable_name (str): variable name
variables_mapping (dict): variables mapping
Returns:
mapping variable value.
Raises:
exceptions.VariableNotFound: variable is n... |
get function from functions_mapping,
if not found, then try to check if builtin function.
Args:
variable_name (str): variable name
variables_mapping (dict): variables mapping
Returns:
mapping function object.
Raises:
exceptions.FunctionNotFound: function is neither... | def get_mapping_function(function_name, functions_mapping):
""" get function from functions_mapping,
if not found, then try to check if builtin function.
Args:
variable_name (str): variable name
variables_mapping (dict): variables mapping
Returns:
mapping function object.
... |
parse function params to args and kwargs.
Args:
params (str): function param in string
Returns:
dict: function meta dict
{
"args": [],
"kwargs": {}
}
Examples:
>>> parse_function_params("")
{'args': [], 'kwargs': {}}... | def parse_function_params(params):
""" parse function params to args and kwargs.
Args:
params (str): function param in string
Returns:
dict: function meta dict
{
"args": [],
"kwargs": {}
}
Examples:
>>> parse_function_pa... |
make string in content as lazy object with functions_mapping
Raises:
exceptions.VariableNotFound: if any variable undefined in check_variables_set | def prepare_lazy_data(content, functions_mapping=None, check_variables_set=None, cached=False):
""" make string in content as lazy object with functions_mapping
Raises:
exceptions.VariableNotFound: if any variable undefined in check_variables_set
"""
# TODO: refactor type check
if content ... |
parse lazy data with evaluated variables mapping.
Notice: variables_mapping should not contain any variable or function. | def parse_lazy_data(content, variables_mapping=None):
""" parse lazy data with evaluated variables mapping.
Notice: variables_mapping should not contain any variable or function.
"""
# TODO: refactor type check
if content is None or isinstance(content, (numeric_types, bool, type)):
retur... |
evaluate data instantly.
Notice: variables_mapping should not contain any variable or function. | def eval_lazy_data(content, variables_mapping=None, functions_mapping=None):
""" evaluate data instantly.
Notice: variables_mapping should not contain any variable or function.
"""
variables_mapping = variables_mapping or {}
check_variables_set = set(variables_mapping.keys())
return parse_la... |
extract all variables in content recursively. | def extract_variables(content):
""" extract all variables in content recursively.
"""
if isinstance(content, (list, set, tuple)):
variables = set()
for item in content:
variables = variables | extract_variables(item)
return variables
elif isinstance(content, dict):
... |
extend test with api definition, test will merge and override api definition.
Args:
test_dict (dict): test block, this will override api_def_dict
api_def_dict (dict): api definition
Examples:
>>> api_def_dict = {
"name": "get token 1",
"request": {...},
... | def _extend_with_api(test_dict, api_def_dict):
""" extend test with api definition, test will merge and override api definition.
Args:
test_dict (dict): test block, this will override api_def_dict
api_def_dict (dict): api definition
Examples:
>>> api_def_dict = {
"n... |
eval each prepared variable and function in variables_mapping.
Args:
variables_mapping (dict):
{
"varA": LazyString(123$varB),
"varB": LazyString(456$varC),
"varC": LazyString(${sum_two($a, $b)}),
"a": 1,
"b": 2,
... | def parse_variables_mapping(variables_mapping, ignore=False):
""" eval each prepared variable and function in variables_mapping.
Args:
variables_mapping (dict):
{
"varA": LazyString(123$varB),
"varB": LazyString(456$varC),
"varC": LazyString($... |
parse testcase/testsuite config. | def __prepare_config(config, project_mapping, session_variables_set=None):
""" parse testcase/testsuite config.
"""
# get config variables
raw_config_variables = config.pop("variables", {})
raw_config_variables_mapping = utils.ensure_mapping_format(raw_config_variables)
override_variables = util... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.