Python unittest2.main() Examples

The following are 24 code examples of unittest2.main(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module unittest2 , or try the search function .
Example #1
Source File: main_test.py    From gae-secure-scaffold-python with Apache License 2.0 6 votes vote down vote up
def testStrictHandlerMethodRouting(self):
    """Checks that handler functions properly limit applicable HTTP methods."""
    router = webapp2.Router(main._USER_ROUTES + main._AJAX_ROUTES +
                            main._ADMIN_ROUTES + main._ADMIN_AJAX_ROUTES)
    routes = router.match_routes + router.build_routes.values()
    failed_routes = []
    while routes:
      route = routes.pop()
      if issubclass(route.__class__, webapp2_extras.routes.MultiRoute):
        routes += list(route.get_routes())
        continue

      if issubclass(route.handler, webapp2.RedirectHandler):
        continue

      if route.handler_method and not route.methods:
        failed_routes.append('%s (%s)' % (route.template,
                                          route.handler.__name__))

    if failed_routes:
      self.fail('Some handlers specify a handler_method but are missing a '
                'methods" attribute and may be vulnerable to XSRF via GET '
                'requests:\n * ' + '\n * '.join(failed_routes)) 
Example #2
Source File: test_docstring_wrap.py    From python-docstring-mode with MIT License 6 votes vote down vote up
def test_sphinx_nop(self):
        """
        Long and Sphinx- (and docstring!)-rich docstrings don't get mangled.
        """
        ds = \
    """
    Phasellus purus.

    :param int arg: Cras placerat accumsan nulla.

    >>> print("hello")
    hello

    Aliquam erat volutpat.  Nunc eleifend leo vitae magna.  In id erat non orci
    commodo lobortis.  Proin neque massa, cursus ut, gravida ut, lobortis eget,
    lacus.  Sed diam.  Praesent fermentum tempor tellus.  Nullam tempus.
    """
        self.assertEqual(
            ds,
            main(["test"], ds)
        ) 
Example #3
Source File: test_program.py    From ConTroll_Remote_Access_Trojan with Apache License 2.0 6 votes vote down vote up
def testCatchBreakInstallsHandler(self):
        module = sys.modules['unittest2.main']
        original = module.installHandler
        def restore():
            module.installHandler = original
        self.addCleanup(restore)

        self.installed = False
        def fakeInstallHandler():
            self.installed = True
        module.installHandler = fakeInstallHandler
        
        program = self.program
        program.catchbreak = True
        
        program.testRunner = FakeRunner
        
        program.runTests()
        self.assertTrue(self.installed) 
Example #4
Source File: main_test.py    From gae-secure-scaffold-python with Apache License 2.0 6 votes vote down vote up
def testRoutesInheritance(self):
    errors = ''
    errors += self._VerifyInheritance(main._UNAUTHENTICATED_ROUTES,
                                      handlers.BaseHandler)
    errors += self._VerifyInheritance(main._UNAUTHENTICATED_AJAX_ROUTES,
                                      handlers.BaseAjaxHandler)
    errors += self._VerifyInheritance(main._USER_ROUTES,
                                      handlers.AuthenticatedHandler)
    errors += self._VerifyInheritance(main._AJAX_ROUTES,
                                      handlers.AuthenticatedAjaxHandler)
    errors += self._VerifyInheritance(main._ADMIN_ROUTES,
                                      handlers.AdminHandler)
    errors += self._VerifyInheritance(main._ADMIN_AJAX_ROUTES,
                                      handlers.AdminAjaxHandler)
    errors += self._VerifyInheritance(main._CRON_ROUTES,
                                      handlers.BaseCronHandler)
    errors += self._VerifyInheritance(main._TASK_ROUTES,
                                      handlers.BaseTaskHandler)
    if errors:
      self.fail('Some handlers do not inherit from the correct classes:\n' +
                errors) 
Example #5
Source File: test_docstring_wrap.py    From python-docstring-mode with MIT License 5 votes vote down vote up
def test_self(self):
        """
        This module's, class's, & method's docstrings are fine and therefore
        not mangled.  They're all interesting because they have different
        indentations.
        """
        for ds in (__doc__, self.__class__.__doc__, self.test_self.__doc__):
            self.assertEqual(
                ds,
                main(["test"], ds)
            ) 
Example #6
Source File: test.py    From hangman with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_same_letter_twice(self):
        """Test error message when user enters same letter twice."""
        self.choice.return_value = "ant"
        self.input.side_effect = list("anntn")

        gallows.main()

        self.xprint.assert_any_call("You have already guessed that letter. "
                                    "Choose again.") 
Example #7
Source File: test.py    From hangman with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_numeric_input(self):
        """Test error message when user inputs numbers."""
        self.choice.return_value = "ant"
        self.input.side_effect = list("a2nt" "n")

        gallows.main()

        self.xprint.assert_any_call('Please enter a LETTER.') 
Example #8
Source File: test.py    From hangman with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_out_of_order(self):
        """Test win scenario with out of order input of letters."""
        self.choice.return_value = "ant"
        self.input.side_effect = list("tan" "n")

        gallows.main()

        self.xprint.assert_any_call('Yes! The secret word is "ant"! '
                                    'You have won!') 
Example #9
Source File: test.py    From hangman with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_two_game(self):
        """Test two winning game plays."""
        from itertools import chain
        self.choice.side_effect = ["ant", "baboon"]
        self.input.side_effect = chain(list("ant"), ["yes"], list("babon"), ["no"])

        gallows.main()

        self.xprint.assert_any_call('Yes! The secret word is "ant"! '
                                    'You have won!')
        self.xprint.assert_any_call('Yes! The secret word is "baboon"! '
                                    'You have won!') 
Example #10
Source File: test.py    From hangman with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_lose(self):
        """Test user lose scenario."""
        self.choice.return_value = "ant" 
        self.input.side_effect = list("bcdefg" "n")

        gallows.main()

        self.xprint.assert_any_call('You have run out of guesses!') 
Example #11
Source File: test.py    From hangman with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_win(self):
        """Test user win scenario."""
        self.choice.return_value = "ant"
        self.input.side_effect = list("ant" "n")

        gallows.main()

        self.xprint.assert_any_call('Yes! The secret word is "ant"! '
                                    'You have won!') 
Example #12
Source File: test_docstring_wrap.py    From python-docstring-mode with MIT License 5 votes vote down vote up
def test_single_space_used_when_specified(self):
        """
        When called with --single-space, only a single space is inserted at
        the end of sentences.
        """
        ds = """
        Sentence number one. Sentence number two.
        """
        self.assertEqual(
            ds,
            main(["test", "--single-space"], ds)) 
Example #13
Source File: test_docstring_wrap.py    From python-docstring-mode with MIT License 5 votes vote down vote up
def test_single_line_too_wide(self):
        """
        Overly long single line docstrings get refilled correctly.
        """
        ds = """
        This is totally too long and must be refilled.  Fortunately we have an awesome plugin for that!
        """  # noqa
        self.assertEqual(
            """
        This is totally too long and must be refilled.  Fortunately we have an
        awesome plugin for that!
        """,
            main(["test"], ds)
        ) 
Example #14
Source File: test_docstring_wrap.py    From python-docstring-mode with MIT License 5 votes vote down vote up
def test_epytext_nop(self):
        """
        wrapPythonDocstring has an impressive multi-paragraph docstring full of
        epytext and doesn't get mangled.
        """
        self.assertEqual(
            wrapPythonDocstring.__doc__,
            main(["test"], wrapPythonDocstring.__doc__)
        ) 
Example #15
Source File: __init__.py    From pysmt with Apache License 2.0 5 votes vote down vote up
def __call__(self, test_fun):
        msg = "Quantifier Eliminator for %s not available" % self.logic
        cond = len(get_env().factory.all_quantifier_eliminators(logic=self.logic)) == 0
        @unittest.skipIf(cond, msg)
        @wraps(test_fun)
        def wrapper(*args, **kwargs):
            return test_fun(*args, **kwargs)
        return wrapper


# Export a main function 
Example #16
Source File: test_program.py    From ConTroll_Remote_Access_Trojan with Apache License 2.0 5 votes vote down vote up
def test_ExitAsDefault(self):
        self.assertRaises(
            SystemExit,
            unittest2.main,
            argv=["foobar"],
            testRunner=unittest2.TextTestRunner(stream=StringIO()),
            testLoader=self.FooBarLoader()) 
Example #17
Source File: test_program.py    From ConTroll_Remote_Access_Trojan with Apache License 2.0 5 votes vote down vote up
def test_Exit(self):
        self.assertRaises(
            SystemExit,
            unittest2.main,
            argv=["foobar"],
            testRunner=unittest2.TextTestRunner(stream=StringIO()),
            exit=True,
            testLoader=self.FooBarLoader()) 
Example #18
Source File: test_program.py    From ConTroll_Remote_Access_Trojan with Apache License 2.0 5 votes vote down vote up
def test_NonExit(self):
        program = unittest2.main(exit=False,
                                argv=["foobar"],
                                testRunner=unittest2.TextTestRunner(stream=StringIO()),
                                testLoader=self.FooBarLoader())
        self.assertTrue(hasattr(program, 'result')) 
Example #19
Source File: responder_test.py    From mitogen with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_exec_guard(self):
        touched = self.call("derp.py", self.HAS_EXEC_GUARD)
        bits = touched.decode().split()
        self.assertEquals(bits[-3:], ['def', 'main():', 'pass']) 
Example #20
Source File: unix_test.py    From mitogen with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, latch, **kwargs):
        super(MyService, self).__init__(**kwargs)
        # used to wake up main thread once client has made its request
        self.latch = latch 
Example #21
Source File: fork_test.py    From mitogen with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_okay(self):
        # When forking from the master process, Mitogen had nothing to do with
        # setting up stdio -- that was inherited wherever the Master is running
        # (supervisor, iTerm, etc). When forking from a Mitogen child context
        # however, Mitogen owns all of fd 0, 1, and 2, and during the fork
        # procedure, it deletes all of these descriptors. That leaves the
        # process in a weird state that must be handled by some combination of
        # fork.py and ExternalContext.main().

        # Below we simply test whether ExternalContext.main() managed to boot
        # successfully. In future, we need lots more tests.
        c1 = self.router.fork()
        c2 = self.router.fork(via=c1)
        self.assertEquals(123, c2.call(ping)) 
Example #22
Source File: system_test.py    From qpid-dispatch with Apache License 2.0 5 votes vote down vote up
def main_module():
    """
    Return the module name of the __main__ module - i.e. the filename with the
    path and .py extension stripped. Useful to run the tests in the current file but
    using the proper module prefix instead of '__main__', as follows:
        if __name__ == '__main__':
            unittest.main(module=main_module())
    """
    return os.path.splitext(os.path.basename(__main__.__file__))[0] 
Example #23
Source File: test_pyecdsa.py    From scalyr-agent-2 with Apache License 2.0 5 votes vote down vote up
def __main__():
    unittest.main() 
Example #24
Source File: tests.py    From LearningApacheSpark with MIT License 4 votes vote down vote up
def test_multithread_broadcast_pickle(self):
        import threading

        b1 = self.sc.broadcast(list(range(3)))
        b2 = self.sc.broadcast(list(range(3)))

        def f1():
            return b1.value

        def f2():
            return b2.value

        funcs_num_pickled = {f1: None, f2: None}

        def do_pickle(f, sc):
            command = (f, None, sc.serializer, sc.serializer)
            ser = CloudPickleSerializer()
            ser.dumps(command)

        def process_vars(sc):
            broadcast_vars = list(sc._pickled_broadcast_vars)
            num_pickled = len(broadcast_vars)
            sc._pickled_broadcast_vars.clear()
            return num_pickled

        def run(f, sc):
            do_pickle(f, sc)
            funcs_num_pickled[f] = process_vars(sc)

        # pickle f1, adds b1 to sc._pickled_broadcast_vars in main thread local storage
        do_pickle(f1, self.sc)

        # run all for f2, should only add/count/clear b2 from worker thread local storage
        t = threading.Thread(target=run, args=(f2, self.sc))
        t.start()
        t.join()

        # count number of vars pickled in main thread, only b1 should be counted and cleared
        funcs_num_pickled[f1] = process_vars(self.sc)

        self.assertEqual(funcs_num_pickled[f1], 1)
        self.assertEqual(funcs_num_pickled[f2], 1)
        self.assertEqual(len(list(self.sc._pickled_broadcast_vars)), 0)