Python unittesting: adding test methods dynamically?

Python unittesting: adding test methods dynamically?

Content Index :

Python unittesting: adding test methods dynamically?
Tag : python , By : ranja
Date : November 29 2020, 04:01 AM

To fix this issue At last I've managed to solve this purely based on Python 2.7's infrastructure by calling in TestSuites:
#modules of the tested objects not included here
from TemplateMaker import Param
from lxml import etree

import unittest
import os
import os.path

class TestSuiteParam(unittest.TestSuite):
    def __init__(self):
        self._tests = []
        dir = 'test_param_items'
        for f in os.listdir(dir):
            if os.path.isfile(dir + "\\" + f) and f[0] != '_':
                # "_test_filename" is for inactive/switched off tests 
                tp = TestParam(f, dir)
        super(TestSuiteParam, self).__init__(self._tests)

class TestParam(unittest.TestCase):
    def __init__(self, inFile, inDir):
        func = self.TestCaseFactory(inFile, inDir)
        setattr(TestParam, func.__name__, func)
        super(TestParam, self).__init__(func.__name__)

    def TestCaseFactory(inFileName, inDir):
        def func(inObj):
            with open(inDir + "\\" + inFileName, "r") as testFile:
                testNode = testFile.read()
                par = Param(inETree=etree.XML(testNode))
                inObj.assertEqual(testNode, etree.tostring(par.eTree))
        func.__name__ = "test_" + inFileName[:-4]
        return func

No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Dynamically adding methods to a class in Python

Tag : python , By : Alex S
Date : March 29 2020, 07:55 AM
this will help Because you use the same scope for all function declarations. Define each function in a separate scope.

unittesting(Python), test if function returns an array

Tag : python , By : Tonix
Date : March 29 2020, 07:55 AM
Any of those help I have a python function somefunc(), that must return an array like this [1, 2, 3]. Now I'm writing a unittest to check what this functions return: , You can write:
from mymodule import somefunc

class TestingFunctionsTest(unittest.TestCase):
    def test_somefunc(self):
        self.assertEqual(somefunc(), [1, 2, 3])

Adding test methods dynamically using decorator

Tag : python , By : dlouzan
Date : March 29 2020, 07:55 AM
hop of those help? The best solution is to use the sub tests feature of unittest in python 3.4. Documentation found here and used like:
class NumbersTest(unittest.TestCase):

    def test_even(self):
        Test that numbers between 0 and 5 are all even.
        for i in range(0, 6):
            with self.subTest(i=i):
                self.assertEqual(i % 2, 0)
class sub_test_data(object):

    def __init__(self, *test_data):
        self.test_data = test_data

    def __call__(self, func):
        func.sub_test_data = self.test_data
        func.has_sub_tests = True
        return func

def create_test_driver(func, *args):
    def test_driver(self):
            func(self, *args)
        except AssertionError as e:
            e.args += ({"test_args": args},)
    return test_driver  

def create_sub_tests(cls):
    for attr_name, func in list(vars(cls).items()):
        if getattr(func, "has_sub_tests", False):
            for i, value in enumerate(func.sub_test_data):
                test_name = 'test_{}_subtest{}'.format(attr_name, i)
                setattr(cls, test_name, create_test_driver(func, value))
    return cls

class NumbersTest(unittest.TestCase):
    tickets = [0, 1, 2, 3, 4, 5]

    def even(self, t):
        self.assertEqual(t % 2, 0)

Python unittesting: Test whether two angles are almost equal

Tag : python , By : Kirks
Date : March 29 2020, 07:55 AM
Does that help You can use the squared Euclidian distance between two points on the unit circle and the law of cosines to get the absolute difference between two angles:
from math import sin, cos, acos
from unittest import assertAlmostEqual        

def assertAlmostEqualAngles(x, y, **kwargs):
    c2 = (sin(x)-sin(y))**2 + (cos(x)-cos(y))**2
    angle_diff = acos((2.0 - c2)/2.0) # a = b = 1
    assertAlmostEqual(angle_diff, 0.0, **kwargs)
from math import sin, cos, acos, radians, degrees
from unittest import assertAlmostEqual        

def assertAlmostEqualAngles(x, y, **kwargs):
    x,y = radians(x),radians(y)
    c2 = (sin(x)-sin(y))**2 + (cos(x)-cos(y))**2
    angle_diff = degrees(acos((2.0 - c2)/2.0))
    assertAlmostEqual(angle_diff, 0.0, **kwargs)

How to set test group to @Test methods dynamically using TestNG?

Tag : java , By : user119605
Date : March 29 2020, 07:55 AM
like below fixes the issue You should perhaps start exploring the beanshell way of method selection that TestNG provides to you for this purpose.
Sometime back I wrote up a blog post which talks about how to work with Beanshell expressions in TestNG. You can read more about it here and refer to the official TestNG documentation here.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="1265_Suite" parallel="false" verbose="2">
    <test name="92" parallel="false" preserve-order="true">
                <script language="beanshell">
                    <![CDATA[whatGroup = System.getProperty("groupToRun");
                (groups.containsKey(whatGroup) || testngMethod.getGroups().length ==0);
            <class name="com.rationaleemotions.stackoverflow.MyTest1"/>
            <class name="com.rationaleemotions.stackoverflow.MyTest2"/>
mvn clean test -DsuiteXmlFile=dynamic_groups.xml -DgroupToRun=group2

 T E S T S
Running TestSuite
... TestNG 6.11 by C├ędric Beust (cedric@beust.com)

test1 called
test3 called
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 15.377 sec - in TestSuite

Results :

Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
Related Posts Related QUESTIONS :
  • Python subprocess doesn't work without sleep
  • How can I adjust 'the time' in python with module Re
  • Join original np array with resulting np array in a form of dictionary? multidimensional array? etc?
  • Forcing labels on histograms in each individual graph in a figure
  • For an infinite dataset, is the data used in each epoch the same?
  • Is there a more efficent way to extend a string?
  • How to calculate each single element of a numpy array based on conditions
  • How do I change the width of Jupyter notebook's cell's left part?
  • Measure distance between lat/lon coordinates and utm coordinates
  • Installing megam for NLTK on Windows
  • filter dataframe on each value of a samn column have a specific value of another column in Panda\Python
  • Threading with pubsub throwing AssertionError: 'callableObj is not callable' in wxPython
  • Get grouped data from 2 dataframes with condition
  • How can I import all of sklearns regressors
  • How to take all elements except the first k
  • Whats wrong with my iteration list of lists from csv
  • Tensorflow Estimator API save image summary in eval mode
  • How to Pack with PyQt - how to make QFrame/Layout adapt to content
  • How do I get certain Time Range in Python
  • python doubly linked list - insertAfter node
  • Open .h5 file in Python
  • Joining a directory name with a binary file name
  • python, sort list with two arguments in compare function
  • Is it possible to print from Python using non-ANSI colors?
  • Pandas concat historical data using date minus some number of days
  • CV2: Import Error in Python OpenCV
  • Is it possible to do this loop in a one-liner?
  • invalid literal for int() with base 10: - django
  • Why does my code print a value that I have not assigned as yet?
  • the collatz func in automate boring stuff with python
  • How to find all possible combinations of parameters and funtions
  • about backpropagation deep neural network in tensorflow
  • Sort strings in pandas
  • How do access my flask app hosted in docker?
  • Replace the sentence include some text with Python regex
  • Counting the most common element in a 2D List in Python
  • logout a user from the system using a function in python
  • mp4 metadata not found but exists
  • Django: QuerySet with ExpressionWrapper
  • Pandas string search in list of dicts
  • Decryption from RSA encrypted string from sqlite is not the same
  • need of maximum value in int
  • a list of several tuples, how to extract the same of the first two elements in the small tuple in the large tuple
  • Display image of 2D Sinewaves in 3D
  • how to prevent a for loop from overwriting a dictionary?
  • How To Fix: RuntimeError: size mismatch in pyTorch
  • Concatenating two Pandas DataFrames while maintaining index order
  • Why does this not run into an infinite loop?
  • Python Multithreading no current event loop
  • Element Tree - Seaching for specific element value without looping
  • Ignore Nulls in pandas map dictionary
  • How do I get scrap data from web pages using beautifulsoup in python
  • Variable used, golobal or local?
  • I have a regex statement to pull all numbers out of a text file, but it only finds 77 out of the 81 numbers in the file
  • How do I create a dataframe of jobs and companies that includes hyperlinks?
  • Detect if user has clicked the 'maximized' button
  • Does flask_login automatically set the "next" argument?
  • Indents in python 3
  • How to create a pool of threads
  • Pandas giving IndexError on one dataframe but not on another similar dataframe
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com