Ejemplo n.º 1
0
def main():
    suite = unittest.TestLoader().loadTestsFromTestCase(TestHttpTask)
    unittest.TextTestRunner(verbosity=2).run(suite)
Ejemplo n.º 2
0
        for op in (("PADDB", 8), ("PADDW", 16), ("PADDD", 32), ("PADDQ", 64)):
            self.int_sse_op(op[0], op_add, op[1], 128, SSE_V0, SSE_V0)
            self.int_sse_op(op[0], op_add, op[1], 128, SSE_V0, SSE_V1)
            self.int_sse_op(op[0], op_add, op[1], 128, SSE_V1, SSE_V0)
            self.int_sse_op(op[0], op_add, op[1], 128, SSE_V1, SSE_V1)

    def test_SSE_SUB(self):
        for op in (("PSUBB", 8), ("PSUBW", 16), ("PSUBD", 32), ("PSUBQ", 64)):
            self.int_sse_op(op[0], op_sub, op[1], 128, SSE_V0, SSE_V0)
            self.int_sse_op(op[0], op_sub, op[1], 128, SSE_V0, SSE_V1)
            self.int_sse_op(op[0], op_sub, op[1], 128, SSE_V1, SSE_V0)
            self.int_sse_op(op[0], op_sub, op[1], 128, SSE_V1, SSE_V1)

    def test_SSE_simp(self):
        self.symb_sse_ops(["PADDB", "PADDB", "PSUBB"], ExprInt(0, XMM0.size),
                          SSE_A, SSE_A)
        self.symb_sse_ops(["PADDB", "PADDQ", "PSUBQ"], ExprInt(0, XMM0.size),
                          SSE_A, SSE_A)
        self.symb_sse_ops(["PADDB", "PSUBQ", "PADDQ"], ExprInt(0, XMM0.size),
                          SSE_A, SSE_A)

    def test_AND(self):
        self.mmx_logical_op("PAND", op_and, MMX_V0, MMX_V1)
        self.sse_logical_op("PAND", op_and, SSE_V0, SSE_V1)


if __name__ == '__main__':
    testsuite = unittest.TestLoader().loadTestsFromTestCase(TestX86Semantic)
    report = unittest.TextTestRunner(verbosity=2).run(testsuite)
    exit(len(report.errors + report.failures))
Ejemplo n.º 3
0
def test():
    """Run the unit tests."""
    import unittest
    tests = unittest.TestLoader().discover('tests')
    unittest.TextTestRunner(verbosity=2).run(testsg)
Ejemplo n.º 4
0
        tags = {}
        for i in range(-3, 3):
            tags[i] = self.eth.get_tag(i).get_buffer_as_string()

        self.assertEqual(tags[-1], tags[2])
        self.assertEqual(tags[-2], tags[1])
        self.assertEqual(tags[-3], tags[0])

        # Accessing non-existent tags raises IndexError
        self.assertRaises(IndexError, self.eth.get_tag, 3)
        self.assertRaises(IndexError, self.eth.get_tag, -4)
        self.assertRaises(IndexError, self.eth.set_tag, 3, EthernetTag())
        self.assertRaises(IndexError, self.eth.set_tag, -4, EthernetTag())

        # Test Ethernet constructor
        data = self.eth.get_buffer_as_string()
        eth_copy = Ethernet(data)
        self.assertEqual(eth_copy.tag_cnt, 3)
        self.assertEqual(eth_copy.get_header_size(), 26)
        self.assertEqual(eth_copy.get_ether_type(), 0x0800)

        # Remove the deprecated 802.1QinQ header and check resulting frame
        eth_copy.pop_tag(1)
        self.assertEqual(eth_copy.tag_cnt, 2)
        self.assertEqual(eth_copy.get_packet(),
                         self.frame[:12] + tags[0] + tags[2] + self.frame[-2:])


suite = unittest.TestLoader().loadTestsFromTestCase(TestEthernet)
unittest.TextTestRunner(verbosity=1).run(suite)
Ejemplo n.º 5
0
def main():
    watcher()

    names, test_params, arg_i, arg_p, options = parse_args(sys.argv)
    # get params from command line
    TestInputSingleton.input = TestInputParser.get_test_input(sys.argv)
    # ensure command line params get higher priority
    test_params.update(TestInputSingleton.input.test_params)
    TestInputSingleton.input.test_params = test_params
    print "Global Test input params:"
    pprint(TestInputSingleton.input.test_params)

    xunit = XUnitTestResult()

    # Create root logs directory
    if not os.path.exists("logs"):
        os.makedirs("logs")

    # Create testrunner logs subdirectory
    str_time = time.strftime("%y-%b-%d_%H-%M-%S", time.localtime())
    logs_folder = "logs/testrunner-" + str_time
    logs_folder_abspath = os.path.abspath(logs_folder)
    if not os.path.exists(logs_folder):
        os.makedirs(logs_folder)

    results = []
    case_number = 1
    if "GROUP" in test_params:
        print "Only cases in GROUPs '{0}' will be executed".format(test_params["GROUP"])
    if "EXCLUDE_GROUP" in test_params:
        print "Cases from GROUPs '{0}' will be excluded".format(test_params["EXCLUDE_GROUP"])

    for name in names:
        start_time = time.time()
        argument_split = [a.strip() for a in re.split("[,]?([^,=]+)=", name)[1:]]
        params = dict(zip(argument_split[::2], argument_split[1::2]))

        if ("GROUP" or "EXCLUDE_GROUP") in test_params:
            #determine if the test relates to the specified group(can be separated by ';')
            if not ("GROUP" in params and len(set(test_params["GROUP"].split(";")) & set(params["GROUP"].split(";")))) or \
                    "EXCLUDE_GROUP" in params and len(set(test_params["EXCLUDE_GROUP"].split(";")) & set(params["EXCLUDE_GROUP"].split(";"))):
                print "test '{0}' was skipped".format(name)
                continue

        log_config_filename = ""
        #reduce the number of chars in the file name, if there are many(255 bytes filename limit)
        if len(name) > 240:
            name = os.path.join(name[:220] + time.strftime("%y-%b-%d_%H-%M-%S", time.localtime()))
        if params:
            log_name = os.path.join(logs_folder_abspath, name + ".log")
            log_config_filename = os.path.join(logs_folder_abspath, name + ".logging.conf")
        else:
            dotnames = name.split('.')
            log_name = os.path.join(logs_folder_abspath, dotnames[-1] + ".log")
            log_config_filename = os.path.join(logs_folder_abspath, dotnames[-1] + ".logging.conf")
        create_log_file(log_config_filename, log_name, options.loglevel)
        logging.config.fileConfig(log_config_filename)
        print "\n./testrunner -i {0} {1} -t {2}\n"\
              .format(arg_i or "", arg_p or "", name)
        name = name.split(",")[0]

        # Update the test params for each test
        TestInputSingleton.input.test_params = params
        TestInputSingleton.input.test_params.update(test_params)
        TestInputSingleton.input.test_params["case_number"] = case_number
        print "Test Input params:"
        pprint(TestInputSingleton.input.test_params)
        suite = unittest.TestLoader().loadTestsFromName(name)
        result = unittest.TextTestRunner(verbosity=2).run(suite)
        time_taken = time.time() - start_time

        # Concat params to test name
        # To make tests more readable
        params = ''
        if TestInputSingleton.input.test_params:
            for key, value in TestInputSingleton.input.test_params.items():
                if key and value:
                    params += "," + str(key) + ":" + str(value)

        if result.failures or result.errors:
            # Immediately get the server logs, if
            # the test has failed or has errors
            if "get-logs" in TestInputSingleton.input.test_params:
                get_server_logs(TestInputSingleton.input, logs_folder)

            if "get-cbcollect-info" in TestInputSingleton.input.test_params:
                if TestInputSingleton.input.param("get-cbcollect-info", True):
                    get_cbcollect_info(TestInputSingleton.input, logs_folder)

            errors = []
            for failure in result.failures:
                test_case, failure_string = failure
                errors.append(failure_string)
                break
            for error in result.errors:
                test_case, error_string = error
                errors.append(error_string)
                break
            xunit.add_test(name=name, status='fail', time=time_taken,
                           errorType='membase.error', errorMessage=str(errors),
                           params=params)
            results.append({"result": "fail", "name": name})
        else:
            xunit.add_test(name=name, time=time_taken, params=params)
            results.append({"result": "pass", "name": name, "time": time_taken})
        xunit.write("{0}/report-{1}".format(logs_folder, str_time))
        xunit.print_summary()
        print "testrunner logs, diags and results are available under {0}".format(logs_folder)
        case_number += 1
        if (result.failures or result.errors) and \
                TestInputSingleton.input.param("stop-on-failure", False):
            print "test fails, all of the following tests will be skipped!!!"
            break

    if "makefile" in TestInputSingleton.input.test_params:
        # print out fail for those tests which failed and do sys.exit() error code
        fail_count = 0
        for result in results:
            if result["result"] == "fail":
                print result["name"], " fail "
                fail_count += 1
            else:
                print result["name"], " pass"
        if fail_count > 0:
            sys.exit(1)
# Test fixture directory containing config files
FIXTURE_DIR = FIXTURES_DIR_PATH + "/invalid-yaml-configs-duplicate-keys"

class InvalidYamlDuplicateKeysTests(unittest.TestCase, ValidationAssertions):
  """Basic test case for when the matrix file is invalid."""

  def setUp(self):
    # Load the validation of the config files
    self.validationIndex = ValidatorScript.Validator.validateConfigs(FIXTURE_DIR)

  def test_that_validation_index_is_dictionary(self):
    self.assertTrue(isinstance(self.validationIndex, dict))
    self.assertTrue(len(self.validationIndex) > 0)

  def test_some_yaml_yml_files_are_invalid(self):
    print ShellColor.WARNING + "Some Yaml Single documents are invalid" + ShellColor.ENDC
    for filePath, validationObject in self.validationIndex.iteritems():
      isValid = isConfigValid(validationObject)
      printFileValidationStatus(filePath, validationObject)

      # Verify if the directory is in the file path
      self.assertIn(FIXTURE_DIR, filePath)

      # Verify the file
      self.assertThatConfigIsInvalid(filePath, validationObject)

if __name__ == '__main__':
  suite = unittest.TestLoader().loadTestsFromTestCase(InvalidYamlSingleDocumentFileTests)
  unittest.TextTestRunner(verbosity=2).run(suite)
Ejemplo n.º 7
0
def test_suite():
    return unittest.TestLoader().loadTestsFromName(__name__)
Ejemplo n.º 8
0
def suite():
    suite = unittest.TestSuite()
    suite = unittest.TestLoader().loadTestsFromTestCase(TestLitleBatchResponse)
    return suite
Ejemplo n.º 9
0
        K = kernel.create([a_feat, b_feat], [c_feat])

        self.assertEqual(K.shape, (2, 1))

    def test_sparse(self):
        """Tests that sparse features may also be used to construct the kernels.
        """
        # Create SOAP features for a system
        desc = SOAP([1, 8],
                    5.0,
                    2,
                    2,
                    sigma=0.2,
                    periodic=False,
                    crossover=True,
                    sparse=True)
        a = molecule('H2O')
        a_feat = desc.create(a)
        kernel = REMatchKernel(metric="linear", alpha=0.1, threshold=1e-6)
        K = kernel.create([a_feat])


if __name__ == '__main__':
    suites = []
    suites.append(
        unittest.TestLoader().loadTestsFromTestCase(AverageKernelTests))
    suites.append(
        unittest.TestLoader().loadTestsFromTestCase(REMatchKernelTests))
    alltests = unittest.TestSuite(suites)
    result = unittest.TextTestRunner(verbosity=0).run(alltests)
    def test_get_default_media_name(self):
        """
        Test get_default_media_name
        """

        self.assertEqual(GenericMedia(0, '').get_default_media_name(), '')

    def test_get_media_path(self):
        """
        Test get_media_path
        """

        self.assertEqual(GenericMedia(0, '').get_media_path(), '')

    def test_get_media_root(self):
        """
        Test get_media_root
        """

        sickbeard.PROG_DIR = os.path.join('some', 'path', 'to', 'SickRage')

        self.assertEqual(GenericMedia.get_media_root(), os.path.join('some', 'path', 'to', 'SickRage', 'gui', 'slick'))


if __name__ == '__main__':
    print('=====> Testing {0}'.format(__file__))

    SUITE = unittest.TestLoader().loadTestsFromTestCase(GenericMediaTests)
    unittest.TextTestRunner(verbosity=2).run(SUITE)
Ejemplo n.º 11
0
            (5.0, 5.0))))  # Center
        self.assertEquals([0], self.grid.nearest(Point(
            (0.0, 5.0))))  # Left Edge
        self.assertEquals([1], self.grid.nearest(Point(
            (5.0, 10.0))))  # Top Edge
        self.assertEquals([2], self.grid.nearest(Point(
            (10.0, 5.0))))  # Right Edge
        self.assertEquals([3], self.grid.nearest(Point(
            (5.0, 0.0))))  # Bottom Edge

    def test_nearest_2(self):
        self.assertEquals([0, 1, 3], self.grid.nearest(Point(
            (-100000.0, 5.0))))  # Left Edge
        self.assertEquals([1, 2, 3], self.grid.nearest(Point(
            (100000.0, 5.0))))  # Right Edge
        self.assertEquals([0, 2, 3], self.grid.nearest(Point(
            (5.0, -100000.0))))  # Bottom Edge
        self.assertEquals([0, 1, 2], self.grid.nearest(Point(
            (5.0, 100000.0))))  # Top Edge


suite = unittest.TestSuite()
test_classes = [SegmentGrid_Tester]
for i in test_classes:
    a = unittest.TestLoader().loadTestsFromTestCase(i)
    suite.addTest(a)

if __name__ == '__main__':
    runner = unittest.TextTestRunner()
    runner.run(suite)
Ejemplo n.º 12
0
def suite():
    return unittest.TestLoader().loadTestsFromTestCase(
        TestHeadingRecognizeDatesInHeading)
Ejemplo n.º 13
0
def run_tests(test_list,
              build_dir,
              tests_dir,
              junitoutput,
              tmpdir,
              num_jobs,
              test_suite_name,
              enable_coverage=False,
              args=None,
              combined_logs_len=0,
              build_timings=None,
              failfast=False):
    args = args or []

    # Warn if bitcoind is already running (unix only)
    try:
        pidofOutput = subprocess.check_output(["pidof", "bitcoind"])
        if pidofOutput is not None and pidofOutput != b'':
            print(
                "{}WARNING!{} There is already a bitcoind process running on this system. Tests may fail unexpectedly due to resource contention!"
                .format(BOLD[1], BOLD[0]))
    except (OSError, subprocess.SubprocessError):
        pass

    # Warn if there is a cache directory
    cache_dir = os.path.join(build_dir, "test", "cache")
    if os.path.isdir(cache_dir):
        print(
            "{}WARNING!{} There is a cache directory here: {}. If tests fail unexpectedly, try deleting the cache directory."
            .format(BOLD[1], BOLD[0], cache_dir))

    # Test Framework Tests
    print("Running Unit Tests for Test Framework Modules")
    test_framework_tests = unittest.TestSuite()
    for module in TEST_FRAMEWORK_MODULES:
        test_framework_tests.addTest(unittest.TestLoader().loadTestsFromName(
            "test_framework.{}".format(module)))
    result = unittest.TextTestRunner(verbosity=1,
                                     failfast=True).run(test_framework_tests)
    if not result.wasSuccessful():
        logging.debug(
            "Early exiting after failure in TestFramework unit tests")
        sys.exit(False)

    flags = ['--cachedir={}'.format(cache_dir)] + args

    if enable_coverage:
        coverage = RPCCoverage()
        flags.append(coverage.flag)
        logging.debug("Initializing coverage directory at {}".format(
            coverage.dir))
    else:
        coverage = None

    if len(test_list) > 1 and num_jobs > 1:
        # Populate cache
        try:
            subprocess.check_output(
                [sys.executable,
                 os.path.join(tests_dir, 'create_cache.py')] + flags +
                [os.path.join("--tmpdir={}", "cache").format(tmpdir)])
        except subprocess.CalledProcessError as e:
            sys.stdout.buffer.write(e.output)
            raise

    # Run Tests
    start_time = time.time()
    test_results = execute_test_processes(num_jobs, test_list, tests_dir,
                                          tmpdir, flags, failfast)
    runtime = time.time() - start_time

    max_len_name = len(max(test_list, key=len))
    print_results(test_results, tests_dir, max_len_name, runtime,
                  combined_logs_len)

    if junitoutput is not None:
        save_results_as_junit(test_results, junitoutput, runtime,
                              test_suite_name)

    if (build_timings is not None):
        build_timings.save_timings(test_results)

    if coverage:
        coverage_passed = coverage.report_rpc_coverage()

        logging.debug("Cleaning up coverage data")
        coverage.cleanup()
    else:
        coverage_passed = True

    # Clear up the temp directory if all subdirectories are gone
    if not os.listdir(tmpdir):
        os.rmdir(tmpdir)

    all_passed = all(
        map(lambda test_result: test_result.was_successful,
            test_results)) and coverage_passed

    sys.exit(not all_passed)
Ejemplo n.º 14
0
 def handle(self, *args, **options):
     suite = unittest.TestLoader().loadTestsFromTestCase(TestDB)
     unittest.TextTestRunner().run(suite)
Ejemplo n.º 15
0
def suite():
    return unittest.TestLoader().loadTestsFromTestCase(TestMatrixUtils)
Ejemplo n.º 16
0
def test():
    #Tests are inside the folder tests 
    tests = unittest.TestLoader().discover('tests')
    unittest.TextTestRunner().run(tests)
Ejemplo n.º 17
0
def do_tests():
    suite = unittest.TestLoader().loadTestsFromTestCase(CheckTidiness)
    return 0 if unittest.TextTestRunner(verbosity=2).run(suite).wasSuccessful() else 1
        self._test_tracker([], None, None, None, [None])

    def test_0(self):
        self._test_tracker([0], 0, 0, 0, [0])

    def test_01(self):
        self._test_tracker([0, 1], 0, 1, 0.5, [0, 1])

    def test_011(self):
        self._test_tracker([0, 1, 1], 0, 1, 2 / 3.0, [1])

    def test_0112(self):
        self._test_tracker([0, 1, 1, 2], 0, 2, 4 / 4.0, [1])

    def test_0111225(self):
        self._test_tracker([0, 1, 1, 2, 2, 5], 0, 5, 11 / 6.0, [1, 2])

    def test_011122555(self):
        self._test_tracker([0, 1, 1, 2, 2, 5, 5, 5], 0, 5, 21 / 8.0, [5])

    def test_extremes(self):
        tracker = TempTracker()
        self.assertRaises(Exception, tracker.insert, -1)
        self.assertRaises(Exception, tracker.insert, 111)


if __name__ == "__main__":
    # unittest.main()
    suite = unittest.TestLoader().loadTestsFromTestCase(TestTempTracker)
    unittest.TextTestRunner(verbosity=2).run(suite)
Ejemplo n.º 19
0
    def test_initial_state(self):
        self.assertEqual(self.test_d.currentState, 's1')
        pass
    
    def test_get_next_state(self):
        self.assertEqual(self.test_d.get_next_state('t1a1'), 's2')
        pass
        
    def test_get_trans_list(self):
        self.assertEqual(self.test_d.get_trans_list('s1'), [['test','t1a1','s2']] )
        pass
        
    def test_demo(self):
        self.test_ruberto = Fsm('demo')
        self.assertEqual(self.test_ruberto.mach[0], 'Ruberto.com MBT Demo')
        self.assertEqual(self.test_ruberto.currentState,'custState')
        self.assertEqual(self.test_ruberto.get_next_state('tag-link-12'),'mgmtState')
        nextstate = self.test_ruberto.set_next_state('tag-link-12')
        self.assertEqual(nextstate,'mgmtState')
        self.assertEqual(self.test_ruberto.get_current_state_oracle(),'Management')
        nextstate = self.test_ruberto.set_next_state('tag-link-3')
        self.assertEqual(self.test_ruberto.get_current_state_oracle(),'Test Automation')
        pass
    

if __name__ == '__main__':
    unittest.main()
    suite = unittest.TestLoader().loadTestsFromTestCase(TestFsm)
    unittest.TextTestRunner(verbosity=2).run(suite())              
        
Ejemplo n.º 20
0
def run_tests(*,
              test_list,
              src_dir,
              build_dir,
              tmpdir,
              jobs=1,
              enable_coverage=False,
              args=None,
              combined_logs_len=0,
              failfast=False,
              use_term_control):
    args = args or []

    # Warn if bitcoind is already running
    # pidof might fail or return an empty string if bitcoind is not running
    try:
        if subprocess.check_output(["pidof", "bitcoind"]) not in [b'']:
            print(
                "%sWARNING!%s There is already a bitcoind process running on this system. Tests may fail unexpectedly due to resource contention!"
                % (BOLD[1], BOLD[0]))
    except (OSError, subprocess.SubprocessError):
        pass

    # Warn if there is a cache directory
    cache_dir = "%s/test/cache" % build_dir
    if os.path.isdir(cache_dir):
        print(
            "%sWARNING!%s There is a cache directory here: %s. If tests fail unexpectedly, try deleting the cache directory."
            % (BOLD[1], BOLD[0], cache_dir))

    # Test Framework Tests
    print("Running Unit Tests for Test Framework Modules")
    test_framework_tests = unittest.TestSuite()
    for module in TEST_FRAMEWORK_MODULES:
        test_framework_tests.addTest(unittest.TestLoader().loadTestsFromName(
            "test_framework.{}".format(module)))
    result = unittest.TextTestRunner(verbosity=1,
                                     failfast=True).run(test_framework_tests)
    if not result.wasSuccessful():
        logging.debug(
            "Early exiting after failure in TestFramework unit tests")
        sys.exit(False)

    tests_dir = src_dir + '/test/functional/'

    flags = ['--cachedir={}'.format(cache_dir)] + args

    if enable_coverage:
        coverage = RPCCoverage()
        flags.append(coverage.flag)
        logging.debug("Initializing coverage directory at %s" % coverage.dir)
    else:
        coverage = None

    if len(test_list) > 1 and jobs > 1:
        # Populate cache
        try:
            subprocess.check_output(
                [sys.executable, tests_dir + 'create_cache.py'] + flags +
                ["--tmpdir=%s/cache" % tmpdir])
        except subprocess.CalledProcessError as e:
            sys.stdout.buffer.write(e.output)
            raise

    #Run Tests
    job_queue = TestHandler(
        num_tests_parallel=jobs,
        tests_dir=tests_dir,
        tmpdir=tmpdir,
        test_list=test_list,
        flags=flags,
        use_term_control=use_term_control,
    )
    start_time = time.time()
    test_results = []

    max_len_name = len(max(test_list, key=len))
    test_count = len(test_list)
    for i in range(test_count):
        test_result, testdir, stdout, stderr = job_queue.get_next()
        test_results.append(test_result)
        done_str = "{}/{} - {}{}{}".format(i + 1, test_count, BOLD[1],
                                           test_result.name, BOLD[0])
        if test_result.status == "Passed":
            logging.debug("%s passed, Duration: %s s" %
                          (done_str, test_result.time))
        elif test_result.status == "Skipped":
            logging.debug("%s skipped" % (done_str))
        else:
            print("%s failed, Duration: %s s\n" % (done_str, test_result.time))
            print(BOLD[1] + 'stdout:\n' + BOLD[0] + stdout + '\n')
            print(BOLD[1] + 'stderr:\n' + BOLD[0] + stderr + '\n')
            if combined_logs_len and os.path.isdir(testdir):
                # Print the final `combinedlogslen` lines of the combined logs
                print('{}Combine the logs and print the last {} lines ...{}'.
                      format(BOLD[1], combined_logs_len, BOLD[0]))
                print('\n============')
                print('{}Combined log for {}:{}'.format(
                    BOLD[1], testdir, BOLD[0]))
                print('============\n')
                combined_logs_args = [
                    sys.executable,
                    os.path.join(tests_dir, 'combine_logs.py'), testdir
                ]
                if BOLD[0]:
                    combined_logs_args += ['--color']
                combined_logs, _ = subprocess.Popen(
                    combined_logs_args,
                    universal_newlines=True,
                    stdout=subprocess.PIPE).communicate()
                print("\n".join(
                    deque(combined_logs.splitlines(), combined_logs_len)))

            if failfast:
                logging.debug("Early exiting after test failure")
                break

    print_results(test_results, max_len_name, (int(time.time() - start_time)))

    if coverage:
        coverage_passed = coverage.report_rpc_coverage()

        logging.debug("Cleaning up coverage data")
        coverage.cleanup()
    else:
        coverage_passed = True

    # Clear up the temp directory if all subdirectories are gone
    if not os.listdir(tmpdir):
        os.rmdir(tmpdir)

    all_passed = all(
        map(lambda test_result: test_result.was_successful,
            test_results)) and coverage_passed

    # This will be a no-op unless failfast is True in which case there may be dangling
    # processes which need to be killed.
    job_queue.kill_and_join()

    sys.exit(not all_passed)
                    'imageDetails']

                self.assertEqual("image/svg+xml", ids['mediaType'])
                self.assertEqual("data:image/svg+xml;base64",
                                 ids['logotypeURI'][0][0:25])

        self.assertIn(rfc3709.id_pe_logotype, extn_list)

    def testExtensionsMap(self):
        substrate = pem.readBase64fromText(self.pem_text)
        asn1Object, rest = der_decoder(substrate, asn1Spec=self.asn1Spec)

        self.assertFalse(rest)
        self.assertTrue(asn1Object.prettyPrint())
        self.assertEqual(substrate, der_encoder(asn1Object))

        for extn in asn1Object['tbsCertificate']['extensions']:
            if extn['extnID'] in rfc5280.certificateExtensionsMap.keys():
                extnValue, rest = der_decoder(
                    extn['extnValue'],
                    asn1Spec=rfc5280.certificateExtensionsMap[extn['extnID']])

                self.assertEqual(extn['extnValue'], der_encoder(extnValue))


suite = unittest.TestLoader().loadTestsFromModule(sys.modules[__name__])

if __name__ == '__main__':
    result = unittest.TextTestRunner(verbosity=2).run(suite)
    sys.exit(not result.wasSuccessful())
Ejemplo n.º 22
0
def testSuite():
    suite = unittest.TestSuite()
    loader = unittest.TestLoader()
    for klass in [SQLStorageTests, BridgeStabilityTests]:
        suite.addTest(loader.loadTestsFromTestCase(klass))
    return suite
Ejemplo n.º 23
0
        fc = FieldContainer(im, unit=Quantity('5 V'), dimensions=[y, x])
        fc.seal()
        grad_y, grad_x = np.gradient(fc.data)
        grad_y /= np.gradient(y.data).reshape((4, 1))
        grad_x /= np.gradient(x.data).reshape((1, 3))
        grad_y = FieldContainer(
            grad_y, unit=fc.unit / y.unit,
            dimensions=copy.deepcopy(fc.dimensions)
            )
        grad_x = FieldContainer(
            grad_x, unit=fc.unit / x.unit,
            dimensions=copy.deepcopy(fc.dimensions)
            )
        grad_x = grad_x.inUnitsOf(grad_y)
        expected_result = FieldContainer(
            (grad_x.data ** 2 + grad_y.data ** 2) ** 0.5,
            unit=copy.deepcopy(grad_y.unit),
            dimensions=copy.deepcopy(fc.dimensions)
            )
        result = Gradient().gradientWorker(fc)
        self.assertEqual(expected_result, result)

if __name__ == "__main__":
    import sys
    if len(sys.argv) == 1:
        unittest.main()
    else:
        suite = unittest.TestLoader().loadTestsFromTestCase(
            eval(sys.argv[1:][0]))
        unittest.TextTestRunner().run(suite)
Ejemplo n.º 24
0

def random_search(values, v):
    cv = set(values)

    while bool(cv):
        ri = random.randrange(0, len(values))

        if values[ri] == v:
            return ri
        else:
            cv.discard(values[ri])

    return None


class TestStringMethods(unittest.TestCase):
    def test_1(self):
        self.assertEqual(random_search([1, 2, 3, 4, 5, 6, 7], 1), 0)

    def test_2(self):
        self.assertEqual(random_search([26, 31, 41, 41, 58, 59], 30), None)

    def test_3(self):
        self.assertEqual(random_search([26, 31, 41, 41, 58, 59], 59), 5)


if __name__ == '__main__':
    suite = unittest.TestLoader().loadTestsFromTestCase(TestStringMethods)
    unittest.TextTestRunner(verbosity=2).run(suite)
Ejemplo n.º 25
0
import unittest
from testsuites.test_disciz01_serach import DiscuzSearch
from testsuites.test_disciz03_search import DiscizSearch

test_dir = "./"
suite = unittest.TestLoader().discover(test_dir, pattern="test*.py")
#
# suite=unittest.TestSuite()
# suite.addTest(unittest.makeSuite(DiscuzSearch))
# suite.addTest(unittest.makeSuite(DiscizSearch))

if __name__ == "__main__":
    runner = unittest.TextTestRunner(verbosity=2)
    runner.run(suite)
Ejemplo n.º 26
0
        page = BeautifulSoup(p.read())
        artist = PixivArtist(mid=1107124, page=page)
        targetDir = os.path.abspath(os.sep + 'images')
        _config = PixivConfig.PixivConfig()
        _config.avatarNameFormat = ''
        _config.filenameFormat = '%member_token% (%member_id%)' + os.sep + '%R-18%' + os.sep + '%image_id% - %title% - %tags%'
        _config.tagsSeparator = ' '
        _config.tagsLimit = 0
        filename = PixivHelper.createAvatarFilename(artist, targetDir)
        self.assertEqual(filename, targetDir + os.sep + 'kirabara29 (1107124)' + os.sep + 'folder.jpg')

    def testParseLoginError(self):
        p = open('./test/test-login-error.htm', 'r')
        page = BeautifulSoup(p.read())
        r = page.findAll('span', attrs={'class': 'error'})
        self.assertTrue(len(r) > 0)
        self.assertEqual(u'Please ensure your pixiv ID, email address and password is entered correctly.', r[0].string)

    def testParseLoginForm(self):
        p = open('./test/test-login-form.html', 'r')
        page = BeautifulSoup(p.read())
        r = page.findAll('form', attrs={'action': '/login.php'})
        # print(r)
        self.assertTrue(len(r) > 0)


if __name__ == '__main__':
        # unittest.main()
    suite = unittest.TestLoader().loadTestsFromTestCase(TestPixivHelper)
    unittest.TextTestRunner(verbosity=5).run(suite)
Ejemplo n.º 27
0
# ————合并test_login.py和test_openapp.py文件进行执行————success——

import unittest
from test_mwgx import test_config
from test_mwgx import test_login
from test_mwgx import test_buy
import HTMLTestRunner

if __name__ == '__main__':
    suite = unittest.TestSuite()
    suite.addTests(unittest.TestLoader().loadTestsFromTestCase(
        test_config.SetConfig))
    suite.addTests(unittest.TestLoader().loadTestsFromTestCase(
        test_buy.BuyTest))
    suite.addTests(unittest.TestLoader().loadTestsFromTestCase(
        test_login.LoginTest))

    #     # 测试报告生成方法一:这一步是在当前文件夹里自动生成一个txt格式的测试报告,测试报告名称就叫:UnittestTextReport.txt.
    # with open('./UnittestTextReport.txt', 'a') as f:
    #     runner = unittest.TextTestRunner(stream=f, verbosity=2)
    #     runner.run(suite)

    # 测试报告生成方法二:这一步是在当前文件夹中自动生成一个html格式的测试报告,报告名称是:HTMLReport.html,需要使用浏览器打开查看
    with open('HTMLReport.html', 'wb') as f:
        runner = HTMLTestRunner.HTMLTestRunner(
            stream=f,
            title='HLJ Test Report',
            description='generated by HTMLTestRunner.',
            verbosity=2)
        runner.run(suite)
Ejemplo n.º 28
0
# coding:utf-8

import htmltestrunner
import unittest
import unittest_demo
import unittest_module


report_title = '测试报告'
desc = '测试用例执行报告'
report_file = 'UnittestReport.html'
test_suite = unittest.TestSuite()
test_suite.addTest(unittest.TestLoader().loadTestsFromTestCase(unittest_demo.TestDemo))
test_suite.addTest(unittest.TestLoader().loadTestsFromTestCase(unittest_module.TestDemo1))
test_suite.addTest(unittest.TestLoader().loadTestsFromTestCase(unittest_module.TestDemo2))

with open(report_file, 'wb') as r:
    runner = htmltestrunner.HTMLTestRunner(stream=r, title=report_title, description=desc)
    runner.run(test_suite)
Ejemplo n.º 29
0
import unittest
import time
import HTMLTestRunnerNew
from common.test_http_request import TestHttpRequest
from conf import project_path
from common import send_email

suite = unittest.TestSuite()
loader = unittest.TestLoader()

suite.addTest(loader.loadTestsFromTestCase(TestHttpRequest))

now = time.strftime('%Y-%m-%d_%H_%M_%S')  #获取当前时间!!!
file_name = "test" + now + ".html"

#执行用例,并输出报告
with open(project_path.report_path + file_name, "wb") as file:
    runner = HTMLTestRunnerNew.HTMLTestRunner(stream=file,
                                              verbosity=2,
                                              title='测试报告',
                                              description='接口测试',
                                              tester='张三')
    runner.run(suite)

# #发送邮件
# sendEmail= send_email.SendEmail(username='******', passwd='ywlejecyxesbcbdf', receivers='*****@*****.**',
#         title='HTTP日志', content='HTTP测试报告0705', file=project_path.report_path+file_name)
# sendEmail.send_mail()
Ejemplo n.º 30
0
    def test_user_username(self):
        """ Test the User.username object of mirrormanager2.lib.model.
        """
        tests.create_base_items(self.session)
        tests.create_user_groups(self.session)

        for index, string in enumerate([
                'pingou', 'kevin', 'ralph', 'shaiton']):
            item = model.User.get(self.session, index + 1)
            self.assertEqual(item.username, string)

    def test_user_groups(self):
        """ Test the User.groups object of mirrormanager2.lib.model.
        """
        tests.create_base_items(self.session)
        tests.create_user_groups(self.session)

        item = model.User.get(self.session, 1)
        self.assertEqual(item.groups, ['fpca', 'packager'])
        item = model.User.get(self.session, 2)
        self.assertEqual(item.groups, ['fpca', 'packager'])
        item = model.User.get(self.session, 3)
        self.assertEqual(item.groups, ['fpca'])
        item = model.User.get(self.session, 4)
        self.assertEqual(item.groups, ['fpca', 'packager'])


if __name__ == '__main__':
    SUITE = unittest.TestLoader().loadTestsFromTestCase(MMLibModeltests)
    unittest.TextTestRunner(verbosity=10).run(SUITE)