import re import sys import subprocess import traceback import pyutilib.th as unittest basedir = os.path.split(os.path.abspath(__file__))[0] starting_dir = os.getcwd() class GcovrTxt(unittest.TestCase): def __init__(self, *args, **kwds): unittest.TestCase.__init__(self, *args, **kwds) GcovrTxt = unittest.category("smoke")(GcovrTxt) class GcovrXml(unittest.TestCase): def __init__(self, *args, **kwds): unittest.TestCase.__init__(self, *args, **kwds) self.xml_re = re.compile('((timestamp)|(version))="[^"]*"') def compare_xml(self): F = open("coverage.xml") testData = self.xml_re.sub('\\1=""', F.read()).replace("\r", "") F.close() F = open("reference/coverage.xml") refData = self.xml_re.sub('\\1=""', F.read()).replace("\r", "") F.close() self.assertSequenceEqual(testData.split("\n"), refData.split("\n"))
import re import sys import subprocess import traceback import pyutilib.th as unittest basedir = os.path.split(os.path.abspath(__file__))[0] starting_dir = os.getcwd() class GcovrTxt(unittest.TestCase): def __init__(self, *args, **kwds): unittest.TestCase.__init__(self, *args, **kwds) GcovrTxt = unittest.category('smoke')(GcovrTxt) class GcovrXml(unittest.TestCase): def __init__(self, *args, **kwds): unittest.TestCase.__init__(self, *args, **kwds) self.xml_re = re.compile('((timestamp)|(version))="[^"]*"') def compare_xml(self): F = open("coverage.xml") testData = self.xml_re.sub('\\1=""', F.read()).replace("\r", "") F.close() F = open("reference/coverage.xml") refData = self.xml_re.sub('\\1=""', F.read()).replace("\r", "") F.close() self.assertSequenceEqual(testData.split('\n'), refData.split('\n'))
cls = types.new_class(name, (unittest.TestCase, )) cls.__module__ = __name__ cls = unittest.category(*case.level)(cls) driver[model] = cls globals()[name] = cls # # Iterate through all test scenarios and add test methods # for key, value in test_scenarios(lambda c: c.test_pickling): model, solver, io = key cls = driver[model] # Symbolic labels test_name = "test_" + solver + "_" + io + "_symbolic_labels" test_method = create_test_method(model, solver, io, value, True) if test_method is not None: test_method = unittest.category('smoke', 'nightly', solver)(test_method) setattr(cls, test_name, test_method) test_method = None # Non-symbolic labels test_name = "test_" + solver + "_" + io + "_nonsymbolic_labels" test_method = create_test_method(model, solver, io, value, False) if test_method is not None: test_method = unittest.category('smoke', 'nightly', solver)(test_method) setattr(cls, test_name, test_method) test_method = None # Reset the cls variable, since it contains a unittest.TestCase subclass. # This prevents this class from being processed twice! cls = None
continue # print("Testing ",testdir) # # JDS: This is crazy fragile. If testdirs is ever anything BUT # "pyomobook" you will be creating invalid class names # #testdir_ = testdir.replace('-','_') #testClassName = 'Test_'+testdir_.split("pyomobook"+os.sep)[1] testClassName = 'Test_' + os.path.basename(testdir).replace('-', '_') assert '.' not in testClassName Test = globals()[testClassName] = type(testClassName, (unittest.TestCase, ), {}) if testClassName in only_book_tests: Test = unittest.category("book")(Test) else: Test = unittest.category("book", "smoke", "nightly")(Test) # Find all .py files in the test directory for file in list(glob.glob(os.path.join(testdir,'*.py'))) \ + list(glob.glob(os.path.join(testdir,'*','*.py'))): test_file = os.path.abspath(file) bname = os.path.basename(test_file) dir_ = os.path.dirname(test_file) name = os.path.splitext(bname)[0] tname = os.path.basename(dir_) + '_' + name suffix = None # Look for txt and yml file names matching py file names. Add
import pyutilib.subprocess import pyomo.scripting.pyomo_main as main class Tests(unittest.TestCase): def pyomo(self, cmd): os.chdir(currdir) output = main.main(['convert', '--logging=quiet', '-c']+cmd) return output class BaselineTests(Tests): def __init__(self, *args, **kwds): Tests.__init__(self, *args, **kwds) BaselineTests = unittest.category('smoke', 'nightly','expensive')(BaselineTests) # #The following test generates an BAR file for the test case #and checks that it matches the current pyomo baseline BAR file # @unittest.nottest def barwriter_baseline_test(self, name): baseline = currdir+name+'.pyomo.bar' output = currdir+name+'.test.bar' if not os.path.exists(baseline): self.skipTest("baseline file (%s) not found" % (baseline,)) if os.path.exists(datadir+name+'_testCase.py'): testDir = datadir else:
def test_init12(self): self.assertTrue("reference_test_model" not in sys.modules) scenario_tree_model = CreateAbstractScenarioTreeModel().\ create_instance( join(testdatadir, "reference_test_scenario_tree.dat")) def scenario_model_callback(scenario_name, node_list): instance = reference_test_model.create_instance() if scenario_name == "s1": instance.p = 1.0 elif scenario_name == "s2": instance.p = 2.0 else: assert scenario_name == "s3" instance.p = 3.0 return instance with ScenarioTreeInstanceFactory( model=scenario_model_callback, scenario_tree=scenario_tree_model) as factory: self.assertTrue(factory.model_directory() is None) self.assertTrue(factory.scenario_tree_directory() is None) self._check_factory(factory) self.assertEqual(factory._closed, True) self.assertEqual(len(factory._archives), 0) Test = unittest.category('smoke','nightly','expensive')(Test) if __name__ == "__main__": #import logging #logging.getLogger('pyomo.pysp').setLevel(logging.DEBUG) unittest.main()
for case in tests: test_name = ("test_" + case.name + "_" + case.io + ("" if symbolic_labels else "_non") + "_symbolic_labels") test_method = CreateTestMethod(case, modelClass, test_name, symbolic_labels=symbolic_labels) if test_method is not None: setattr(cls, test_name, test_method) class PickleTests_simple_LP(unittest.TestCase): pass PickleTests_simple_LP = unittest.category('smoke', 'nightly', 'expensive')(PickleTests_simple_LP) addfntests(PickleTests_simple_LP, testCases, model_types.simple_LP, symbolic_labels=False) addfntests(PickleTests_simple_LP, testCases, model_types.simple_LP, symbolic_labels=True) class PickleTests_piecewise_LP(unittest.TestCase): pass PickleTests_piecewise_LP = unittest.category(
import pyomo.scripting.pyomo_main as main class Tests(unittest.TestCase): def pyomo(self, cmd): os.chdir(currdir) output = main.main(['convert', '--logging=quiet', '-c'] + cmd) return output class BaselineTests(Tests): def __init__(self, *args, **kwds): Tests.__init__(self, *args, **kwds) BaselineTests = unittest.category('smoke', 'nightly', 'expensive')(BaselineTests) # #The following test generates an nl file for the test case #and checks that it matches the current pyomo baseline nl file # @unittest.nottest def barwriter_baseline_test(self, name): if os.path.exists(datadir + name + '.dat'): self.pyomo([ '--output=' + currdir + name + '.test.bar', datadir + name + '_testCase.py', datadir + name + '.dat' ]) else: self.pyomo([
return writer_test def addfntests(cls, tests, modelClass, symbolic_labels=False): for case in tests: test_name = ("test_"+case.name+"_"+case.io +("" if symbolic_labels else "_non") +"_symbolic_labels") test_method = CreateTestMethod(case, modelClass, test_name, symbolic_labels=symbolic_labels) if test_method is not None: setattr(cls, test_name, test_method) class WriterTests_simple_LP(unittest.TestCase): pass WriterTests_simple_LP = unittest.category('smoke','nightly','expensive')(WriterTests_simple_LP) addfntests(WriterTests_simple_LP,testCases, model_types.simple_LP, symbolic_labels=False) addfntests(WriterTests_simple_LP,testCases, model_types.simple_LP, symbolic_labels=True) class WriterTests_compiled_LP(unittest.TestCase): pass WriterTests_compiled_LP = unittest.category('smoke','nightly','expensive')(WriterTests_compiled_LP) addfntests(WriterTests_compiled_LP,testCases, model_types.compiled_LP, symbolic_labels=False) addfntests(WriterTests_compiled_LP,testCases, model_types.compiled_LP, symbolic_labels=True) class WriterTests_trivial_constraints_LP(unittest.TestCase): pass WriterTests_trivial_constraints_LP = unittest.category('smoke','nightly','expensive')(WriterTests_trivial_constraints_LP) addfntests(WriterTests_trivial_constraints_LP,testCases, model_types.trivial_constraints_LP, symbolic_labels=False) addfntests(WriterTests_trivial_constraints_LP,testCases, model_types.trivial_constraints_LP, symbolic_labels=True) class WriterTests_piecewise_LP(unittest.TestCase): pass WriterTests_piecewise_LP = unittest.category('smoke','nightly','expensive')(WriterTests_piecewise_LP)
# https://github.com/ghackebeil/gjh_asl_json has_gjh_asl_json = False if os.system('gjh_asl_json -v') == 0: has_gjh_asl_json = True class Tests(unittest.TestCase): def pyomo(self, cmd): os.chdir(currdir) output = main.main(['convert', '--logging=quiet', '-c']+cmd) return output class SmokeASLTests(Tests): def __init__(self, *args, **kwds): Tests.__init__(self, *args, **kwds) SmokeASLTests = unittest.category('smoke','nightly','expensive')(SmokeASLTests) class ExpensiveASLTests(Tests): def __init__(self, *args, **kwds): Tests.__init__(self, *args, **kwds) ExpensiveASLTests = unittest.category('expensive')(ExpensiveASLTests) # # The following test calls the gjh_asl_json executable to # generate JSON files corresponding to both the # AMPL-generated nl file and the Pyomo-generated nl # file. The JSON files are then diffed using the pyutilib.th # test class method assertMatchesJsonBaseline() # @unittest.nottest def pyomo_asl_test(self, name):
sys.path.append(currdir) #from pyomo.data.cute import CUTE_classifications as CUTE import CUTE_classifications as CUTE sys.path.pop() class Tests(unittest.TestCase): def pyomo(self, cmd): os.chdir(currdir) output = main.main(['convert', '--logging=quiet', '-c']+cmd) return output class SmokeBaselineTests(Tests): def __init__(self, *args, **kwds): Tests.__init__(self, *args, **kwds) SmokeBaselineTests = unittest.category('smoke','nightly','expensive')(SmokeBaselineTests) class ExpensiveBaselineTests(Tests): def __init__(self, *args, **kwds): Tests.__init__(self, *args, **kwds) ExpensiveBaselineTests = unittest.category('expensive')(ExpensiveBaselineTests) """ The following test generates an nl file for the test case and checks that it matches the current pyomo baseline nl file. """ @unittest.nottest def pyomo_baseline_test(self, name): if name in CUTE.baseline_skipped_models: self.skipTest('Ignoring test '+name) return
def test_bundles_incomplete(self): G = networkx.DiGraph() G.add_node("r") for i in range(4): G.add_node("u"+str(i), bundle="B") G.add_edge("r", "u"+str(i)) model = ScenarioTreeModelFromNetworkX( G, edge_probability_attribute=None) self.assertEqual(model.Bundling.value, True) self.assertEqual(list(model.Bundles), ["B"]) self.assertEqual(list(model.BundleScenarios["B"]), ["u"+str(i) for i in range(4)]) G.node["u0"]["bundle"] = None with self.assertRaises(ValueError): ScenarioTreeModelFromNetworkX( G, edge_probability_attribute=None) del G.node["u0"]["bundle"] with self.assertRaises(ValueError): ScenarioTreeModelFromNetworkX( G, edge_probability_attribute=None) TestScenarioTree = unittest.category('smoke','nightly','expensive')(TestScenarioTree) TestScenarioTreeFromNetworkX = unittest.category('smoke','nightly','expensive')(TestScenarioTreeFromNetworkX) if __name__ == "__main__": unittest.main()
for fname in glob.glob(os.path.join(tdir, '*')): if not os.path.isdir(fname): continue # Only test files in directories ending in -ch. These directories # contain the updated python and scripting files corresponding to # each chapter in the book. if '-ch' not in fname: continue # print("Testing ",fname) # Declare an empty TestCase class fname_ = fname.replace('-', '_') tfname_ = 'Test_' + fname_.split("pyomobook" + os.sep)[1] Test = globals()[tfname_] = type(tfname_, (unittest.TestCase, ), {}) Test = unittest.category("book")(Test) # Find all .py files in the test directory for file in list(glob.glob(fname + '/*.py')) + list( glob.glob(fname + '/*/*.py')): bname = os.path.basename(file) dir_ = os.path.dirname(os.path.abspath(file)) + os.sep name = '.'.join(bname.split('.')[:-1]) tname = os.path.basename(os.path.dirname(dir_)) + '_' + name suffix = None # Look for txt and yml file names matching py file names. Add # a test for any found for suffix_ in ['.txt', '.yml']: if os.path.exists(dir_ + name + suffix_):
self.assertTrue(v in d.values) d = TableDistribution([1,2], weights=[1, 0]) v = d.sample() self.assertEqual(v, 1) def test_UniformDistrubtion(self): d = UniformDistribution(1,10) v = d.sample() self.assertTrue(1 <= v <= 10) def test_NormalDistrubtion(self): d = NormalDistribution(0,1) d.sample() def test_LogNormalDistrubtion(self): d = LogNormalDistribution(0,1) d.sample() def test_GammaDistrubtion(self): d = GammaDistribution(1,1) d.sample() def test_BetaDistrubtion(self): d = BetaDistribution(1,1) d.sample() TestEmbeddedSP = unittest.category('smoke','nightly','expensive')(TestEmbeddedSP) if __name__ == "__main__": unittest.main()
sys.path.pop() class Tests(unittest.TestCase): def pyomo(self, cmd): os.chdir(currdir) output = main.main(['convert', '--logging=quiet', '-c'] + cmd) return output class SmokeBaselineTests(Tests): def __init__(self, *args, **kwds): Tests.__init__(self, *args, **kwds) SmokeBaselineTests = unittest.category('smoke', 'nightly', 'expensive')(SmokeBaselineTests) class ExpensiveBaselineTests(Tests): def __init__(self, *args, **kwds): Tests.__init__(self, *args, **kwds) ExpensiveBaselineTests = unittest.category('expensive')(ExpensiveBaselineTests) """ The following test generates an nl file for the test case and checks that it matches the current pyomo baseline nl file. """ @unittest.nottest
return pickle_test def addfntests(cls, tests, modelClass, symbolic_labels=False): for case in tests: test_name = ("test_"+case.name+"_"+case.io +("" if symbolic_labels else "_non") +"_symbolic_labels") test_method = CreateTestMethod(case, modelClass, test_name, symbolic_labels=symbolic_labels) if test_method is not None: setattr(cls, test_name, test_method) class PickleTests_simple_LP(unittest.TestCase): pass PickleTests_simple_LP = unittest.category('smoke','nightly','expensive')(PickleTests_simple_LP) addfntests(PickleTests_simple_LP,testCases, model_types.simple_LP, symbolic_labels=False) addfntests(PickleTests_simple_LP,testCases, model_types.simple_LP, symbolic_labels=True) class PickleTests_piecewise_LP(unittest.TestCase): pass PickleTests_piecewise_LP = unittest.category('smoke','nightly','expensive')(PickleTests_piecewise_LP) addfntests(PickleTests_piecewise_LP,testCases, model_types.piecewise_LP, symbolic_labels=False) addfntests(PickleTests_piecewise_LP,testCases, model_types.piecewise_LP, symbolic_labels=True) class PickleTests_unused_vars_LP(unittest.TestCase): pass PickleTests_unused_vars_LP = unittest.category('smoke','nightly','expensive')(PickleTests_unused_vars_LP) addfntests(PickleTests_unused_vars_LP,testCases, model_types.unused_vars_LP, symbolic_labels=False) addfntests(PickleTests_unused_vars_LP,testCases, model_types.unused_vars_LP, symbolic_labels=True) class PickleTests_unused_vars_MILP(unittest.TestCase): pass PickleTests_unused_vars_MILP = unittest.category('smoke','nightly','expensive')(PickleTests_unused_vars_MILP)
self.assertEqual(sorted(list(model.Stages)), sorted(["Stage1", "Stage2", "Stage3"])) self.assertEqual(sorted(list(model.Nodes)), sorted(["R", "0", "1", "00", "01"])) self.assertEqual(sorted(list(model.Children["R"])), sorted(["0", "1"])) self.assertEqual(sorted(list(model.Children["0"])), sorted(["00", "01"])) self.assertEqual(sorted(list(model.Children["1"])), sorted([])) self.assertEqual(sorted(list(model.Children["00"])), sorted([])) self.assertEqual(sorted(list(model.Children["01"])), sorted([])) self.assertEqual(sorted(list(model.Scenarios)), sorted(["00", "01", "1"])) self.assertEqual(model.ConditionalProbability["R"], 1.0) self.assertEqual(model.ConditionalProbability["0"], 0.5) self.assertEqual(model.ConditionalProbability["1"], 0.5) self.assertEqual(model.ConditionalProbability["00"], 0.5) self.assertEqual(model.ConditionalProbability["01"], 0.5) model.StageCost["Stage1"] = "c1" model.StageCost["Stage2"] = "c2" model.StageCost["Stage3"] = "c3" model.StageVariables["Stage1"].add("x") model.StageVariables["Stage2"].add("x") ScenarioTree(scenariotreeinstance=model) TestScenarioTree = unittest.category('smoke', 'nightly', 'expensive')(TestScenarioTree) if __name__ == "__main__": unittest.main()
if '-ch' not in fname: continue print("Testing ", fname) #print("HERE - DIRECTORY") # Declare an empty TestCase class fname_ = fname.replace('-', '_') if 'pyomobook' in fname_: tfname_ = 'Test_' + fname_.split("pyomobook" + os.sep)[1] tfname2_ = 'Test2_' + fname_.split("pyomobook" + os.sep)[1] else: tfname_ = 'Test_' + fname_.split("examples" + os.sep)[1] tfname2_ = 'Test2_' + fname_.split("examples" + os.sep)[1] Test = globals()[tfname_] = type(tfname_, (unittest.TestCase, ), {}) Test = unittest.category("book")(Test) Test2 = globals()[tfname2_] = type(tfname2_, (unittest.TestCase, ), {}) Test2 = unittest.category("book2")(Test2) # for file in list(glob.glob(fname + '/*.py')) + list( glob.glob(fname + '/*/*.py')): #print(file) bname = os.path.basename(file) dir_ = os.path.dirname(os.path.abspath(file)) + os.sep name = '.'.join(bname.split('.')[:-1]) tname = os.path.basename(os.path.dirname(dir_)) + '_' + name # suffix = None for suffix_ in ['.txt', '.yml', '.txt2', '.yml2']: if os.path.exists(dir_ + name + suffix_):
# farmer location farmer_examples_dir = os.path.join(pysp_examples_dir, "farmer") farmer_model_dir = os.path.join(farmer_examples_dir, "models") farmer_scenariotree_dir = os.path.join(farmer_examples_dir, "scenariodata") class TestInstanceFactory(unittest.TestCase): @classmethod def setUpClass(cls): import pyomo.environ def test_random_bundles(self): self.assertTrue("ReferenceModel" not in sys.modules) scenario_instance_factory = \ ScenarioTreeInstanceFactory(farmer_model_dir, farmer_scenariotree_dir) scenario_tree = \ scenario_instance_factory.generate_scenario_tree(random_bundles=2) self.assertEqual(scenario_tree.contains_bundles(), True) self.assertEqual(len(scenario_tree._scenario_bundles), 2) self.assertTrue("ReferenceModel" in sys.modules) del sys.modules["ReferenceModel"] TestInstanceFactory = unittest.category('smoke', 'nightly', 'expensive')(TestInstanceFactory) if __name__ == "__main__": unittest.main()
continue # print("Testing ",testdir) # # JDS: This is crazy fragile. If testdirs is ever anything BUT # "pyomobook" you will be creating invalid class names # #testdir_ = testdir.replace('-','_') #testClassName = 'Test_'+testdir_.split("pyomobook"+os.sep)[1] testClassName = 'Test_'+os.path.basename(testdir).replace('-','_') assert '.' not in testClassName Test = globals()[testClassName] = type( testClassName, (unittest.TestCase,), {}) if testClassName in only_book_tests: Test = unittest.category("book")(Test) else: Test = unittest.category("book","smoke","nightly")(Test) # Find all .py files in the test directory for file in list(glob.glob(os.path.join(testdir,'*.py'))) \ + list(glob.glob(os.path.join(testdir,'*','*.py'))): test_file = os.path.abspath(file) bname = os.path.basename(test_file) dir_ = os.path.dirname(test_file) name=os.path.splitext(bname)[0] tname = os.path.basename(dir_)+'_'+name suffix = None # Look for txt and yml file names matching py file names. Add
import os from os.path import abspath, dirname currdir = dirname(abspath(__file__)) + os.sep import pyutilib.th as unittest tmp = os.environ.get('PYUTILIB_UNITTEST_CATEGORY', '') os.environ['PYUTILIB_UNITTEST_CATEGORY'] = '_foo_' #@unittest.category('_oof_') class Tester4(unittest.TestCase): def test_pass(self): self.fail("Should not execute this suite") Tester4 = unittest.category('_oof_')(Tester4) os.environ['PYUTILIB_UNITTEST_CATEGORY'] = tmp if __name__ == "__main__": unittest.main()
instance = reference_test_model.create_instance() if scenario_name == "s1": instance.p = 1.0 elif scenario_name == "s2": instance.p = 2.0 else: assert scenario_name == "s3" instance.p = 3.0 return instance with ScenarioTreeInstanceFactory( model=scenario_model_callback, scenario_tree=join( testdatadir, "reference_test_scenario_tree.dat")) as factory: my_scenario_tree = factory.generate_scenario_tree() with ScenarioTreeInstanceFactory( model=scenario_model_callback, scenario_tree=my_scenario_tree) as factory: self.assertTrue(factory.model_directory() is None) self.assertTrue(factory.scenario_tree_directory() is None) self._check_factory(factory) self.assertEqual(factory._closed, True) self.assertEqual(len(factory._archives), 0) Test = unittest.category('smoke', 'nightly', 'expensive')(Test) if __name__ == "__main__": unittest.main()
v = d.sample() self.assertEqual(v, 1) def test_UniformDistrubtion(self): d = UniformDistribution(1, 10) v = d.sample() self.assertTrue(1 <= v <= 10) def test_NormalDistrubtion(self): d = NormalDistribution(0, 1) d.sample() def test_LogNormalDistrubtion(self): d = LogNormalDistribution(0, 1) d.sample() def test_GammaDistrubtion(self): d = GammaDistribution(1, 1) d.sample() def test_BetaDistrubtion(self): d = BetaDistribution(1, 1) d.sample() TestEmbeddedSP = unittest.category('smoke', 'nightly', 'expensive')(TestEmbeddedSP) if __name__ == "__main__": unittest.main()
import os import os.path import re import sys import subprocess import traceback import pyutilib.th as unittest basedir = os.path.split(os.path.abspath(__file__))[0] starting_dir = os.getcwd() class GcovrTxt(unittest.TestCase): def __init__(self, *args, **kwds): unittest.TestCase.__init__(self, *args, **kwds) GcovrTxt = unittest.category('smoke')(GcovrTxt) class GcovrXml(unittest.TestCase): def __init__(self, *args, **kwds): unittest.TestCase.__init__(self, *args, **kwds) self.xml_re = re.compile('((timestamp)|(version))="[^"]*"') def compare_xml(self): F = open("coverage.xml") testData = self.xml_re.sub('\\1=""',F.read()).replace("\r","") F.close() F = open('coverage.xml', 'w') F.write(testData) F.close() F = open("reference/coverage.xml")
self.assertEqual(sorted(list(model.Nodes)), sorted(["R", "0", "1", "00", "01"])) self.assertEqual(sorted(list(model.Children["R"])), sorted(["0", "1"])) self.assertEqual(sorted(list(model.Children["0"])), sorted(["00", "01"])) self.assertEqual(sorted(list(model.Children["1"])), sorted([])) self.assertEqual(sorted(list(model.Children["00"])), sorted([])) self.assertEqual(sorted(list(model.Children["01"])), sorted([])) self.assertEqual(sorted(list(model.Scenarios)), sorted(["00", "01", "1"])) self.assertEqual(model.ConditionalProbability["R"], 1.0) self.assertEqual(model.ConditionalProbability["0"], 0.5) self.assertEqual(model.ConditionalProbability["1"], 0.5) self.assertEqual(model.ConditionalProbability["00"], 0.5) self.assertEqual(model.ConditionalProbability["01"], 0.5) model.StageCost["Stage1"] = "c1" model.StageCost["Stage2"] = "c2" model.StageCost["Stage3"] = "c3" model.StageVariables["Stage1"].add("x") model.StageVariables["Stage2"].add("x") ScenarioTree(scenariotreeinstance=model) TestScenarioTree = unittest.category('smoke', 'nightly', 'expensive')(TestScenarioTree) TestScenarioTreeFromNetworkX = unittest.category( 'smoke', 'nightly', 'expensive')(TestScenarioTreeFromNetworkX) if __name__ == "__main__": unittest.main()
sorted(list(model.Children["0"])), sorted(["00","01"])) self.assertEqual( sorted(list(model.Children["1"])), sorted([])) self.assertEqual( sorted(list(model.Children["00"])), sorted([])) self.assertEqual( sorted(list(model.Children["01"])), sorted([])) self.assertEqual( sorted(list(model.Scenarios)), sorted(["00", "01", "1"])) self.assertEqual(model.ConditionalProbability["R"], 1.0) self.assertEqual(model.ConditionalProbability["0"], 0.5) self.assertEqual(model.ConditionalProbability["1"], 0.5) self.assertEqual(model.ConditionalProbability["00"], 0.5) self.assertEqual(model.ConditionalProbability["01"], 0.5) model.StageCost["Stage1"] = "c1" model.StageCost["Stage2"] = "c2" model.StageCost["Stage3"] = "c3" model.StageVariables["Stage1"].add("x") model.StageVariables["Stage2"].add("x") ScenarioTree(scenariotreeinstance=model) TestScenarioTree = unittest.category('smoke','nightly','expensive')(TestScenarioTree) if __name__ == "__main__": unittest.main()
import os from os.path import abspath, dirname currdir = dirname(abspath(__file__)) + os.sep import pyutilib.th as unittest tmp = os.environ.get('PYUTILIB_UNITTEST_CATEGORY', '') os.environ['PYUTILIB_UNITTEST_CATEGORY'] = '_bar_' #@unittest.category('_foo_') class Tester3(unittest.TestCase): @unittest.category('_bar_ ', ' _rab_') def test_pass(self): print("Executing Tester3.test_pass") @unittest.category('_oof_', ' _rab_') def test_fail(self): self.fail("test_fail will always fail") Tester3 = unittest.category('foo')(Tester3) os.environ['PYUTILIB_UNITTEST_CATEGORY'] = tmp if __name__ == "__main__": unittest.main()
for fname in glob.glob(os.path.join(tdir,'*')): #print("HERE "+fname) if not os.path.isdir(fname): continue #print("HERE - DIRECTORY") # Declare an empty TestCase class fname_ = fname.replace('-','_') if 'pyomobook' in fname_: tfname_ = 'Test_'+fname_.split("pyomobook"+os.sep)[1] tfname2_ = 'Test2_'+fname_.split("pyomobook"+os.sep)[1] else: tfname_ = 'Test_'+fname_.split("examples"+os.sep)[1] tfname2_ = 'Test2_'+fname_.split("examples"+os.sep)[1] Test = globals()[tfname_] = type(tfname_, (unittest.TestCase,), {}) Test = unittest.category("book")(Test) Test2 = globals()[tfname2_] = type(tfname2_, (unittest.TestCase,), {}) Test2 = unittest.category("book2")(Test2) # for file in list(glob.glob(fname+'/*.py')) + list(glob.glob(fname+'/*/*.py')): #print(file) bname = os.path.basename(file) dir_ = os.path.dirname(os.path.abspath(file))+os.sep name='.'.join(bname.split('.')[:-1]) tname = os.path.basename(os.path.dirname(dir_))+'_'+name # suffix = None for suffix_ in ['.txt', '.yml', '.txt2', '.yml2']: if os.path.exists(dir_+name+suffix_): suffix = suffix_
for case in tests: test_name = ("test_" + case.name + "_" + case.io + ("" if symbolic_labels else "_non") + "_symbolic_labels") test_method = CreateTestMethod(case, modelClass, test_name, symbolic_labels=symbolic_labels) if test_method is not None: setattr(cls, test_name, test_method) class WriterTests_simple_LP(unittest.TestCase): pass WriterTests_simple_LP = unittest.category('smoke', 'nightly', 'expensive')(WriterTests_simple_LP) addfntests(WriterTests_simple_LP, testCases, model_types.simple_LP, symbolic_labels=False) addfntests(WriterTests_simple_LP, testCases, model_types.simple_LP, symbolic_labels=True) class WriterTests_compiled_LP(unittest.TestCase): pass WriterTests_compiled_LP = unittest.category(
has_gjh_asl_json = True class Tests(unittest.TestCase): def pyomo(self, cmd): os.chdir(currdir) output = main.main(['convert', '--logging=quiet', '-c'] + cmd) return output class SmokeASLTests(Tests): def __init__(self, *args, **kwds): Tests.__init__(self, *args, **kwds) SmokeASLTests = unittest.category('smoke', 'nightly', 'expensive')(SmokeASLTests) class ExpensiveASLTests(Tests): def __init__(self, *args, **kwds): Tests.__init__(self, *args, **kwds) ExpensiveASLTests = unittest.category('expensive')(ExpensiveASLTests) # # The following test calls the gjh_asl_json executable to # generate JSON files corresponding to both the # AMPL-generated nl file and the Pyomo-generated nl # file. The JSON files are then diffed using the pyutilib.th
@unittest.skip("demonstrating skipping") def test_skip(self): self.fail("test_skip will always be skipped") def test_data(self): self.recordTestData('foo', 'bar') #@unittest.category('_foo_') class Tester2(unittest.TestCase): def test_pass(self): pass Tester2 = unittest.category('_foo_')(Tester2) # # This class will create a test failure when the # test category is _ignore_. This is used to validate # that tests classes will be skipped if another category # is specified. # #@unittest.category('_ignore_') class Tester3(unittest.TestCase): def test_fail(self): if os.environ.get('PYUTILIB_UNITTEST_CATEGORIES', '') == '_ignore_': self.fail(
# # Create test driver classes for each test model # driver = {} for model in test_models(): # Get the test case for the model case = test_models(model) # Create the test class name = "Test_%s" % model if new_available: cls = new.classobj(name, (unittest.TestCase,), {}) else: cls = types.new_class(name, (unittest.TestCase,)) cls = unittest.category(*case.level)(cls) driver[model] = cls globals()[name] = cls # # Iterate through all test scenarios and add test methods # for key, value in test_scenarios(lambda c: c.test_pickling): model, solver, io = key cls = driver[model] # Symbolic labels test_name = "test_"+solver+"_"+io +"_symbolic_labels" test_method = create_test_method(model, solver, io, value, True) if test_method is not None: setattr(cls, test_name, test_method) # Non-symbolic labels test_name = "test_"+solver+"_"+io +"_nonsymbolic_labels"
pysp_examples_dir = os.path.dirname(pysp_examples_dir) pysp_examples_dir = os.path.join(pysp_examples_dir, "examples", "pysp") # farmer location farmer_examples_dir = os.path.join(pysp_examples_dir, "farmer") farmer_model_dir = os.path.join(farmer_examples_dir, "models") farmer_scenariotree_dir = os.path.join(farmer_examples_dir, "scenariodata") class TestInstanceFactory(unittest.TestCase): @classmethod def setUpClass(cls): import pyomo.environ def test_random_bundles(self): self.assertTrue("ReferenceModel" not in sys.modules) scenario_instance_factory = \ ScenarioTreeInstanceFactory(farmer_model_dir, farmer_scenariotree_dir) scenario_tree = \ scenario_instance_factory.generate_scenario_tree(random_bundles=2) self.assertEqual(scenario_tree.contains_bundles(), True) self.assertEqual(len(scenario_tree._scenario_bundles), 2) self.assertTrue("ReferenceModel" in sys.modules) del sys.modules["ReferenceModel"] TestInstanceFactory = unittest.category('smoke','nightly','expensive')(TestInstanceFactory) if __name__ == "__main__": unittest.main()