Python six.assertRaisesRegex() Examples

The following are 30 code examples of six.assertRaisesRegex(). 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 six , or try the search function .
Example #1
Source File: test_variable.py    From chainer with MIT License 6 votes vote down vote up
def check_shape_mismatch(self, x_data, retain):
        xp = backend.get_array_module(x_data)

        class DummyFunction(chainer.Function):
            label = 'dummy_function'

            def forward(self, inputs):
                if not retain:
                    self.retain_inputs(())
                return xp.array(1, np.float32),

            def backward(self, inputs, grads):
                return xp.array([1, 2], np.float32),

        x = chainer.Variable(x_data)
        y = DummyFunction()(x)
        with six.assertRaisesRegex(self, ValueError, 'dummy_function'):
            y.backward() 
Example #2
Source File: test_openedx_secret_key_mixins.py    From opencraft with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_do_not_create_insecure_secret_keys(self, mocks, mock_consul):
        """
        Test that if we have a brand-new instance with no appservers, we refuse to create insecure
        keys for those appservers if we don't have a secure secret key for the instance.
        """
        instance = OpenEdXInstanceFactory()
        instance.secret_key_b64encoded = ''
        instance.save()

        expected_error_string = re.escape(
            'Attempted to create secret key for instance {}, but no master key present.'.format(instance)
        )

        # Six provides a compatibility method for assertRaisesRegex, since the method
        # is named differently between Py2k and Py3k.
        with six.assertRaisesRegex(self, ValueError, expected_error_string):
            instance.spawn_appserver() 
Example #3
Source File: text_format_test.py    From sklearn-theano with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def testParseBadEnumValue(self, message_module):
    message = message_module.TestAllTypes()
    text = 'optional_nested_enum: BARR'
    six.assertRaisesRegex(self, 
        text_format.ParseError,
        (r'1:23 : Enum type "\w+.TestAllTypes.NestedEnum" '
         r'has no value named BARR.'),
        text_format.Parse, text, message)

    message = message_module.TestAllTypes()
    text = 'optional_nested_enum: 100'
    six.assertRaisesRegex(self, 
        text_format.ParseError,
        (r'1:23 : Enum type "\w+.TestAllTypes.NestedEnum" '
         r'has no value with number 100.'),
        text_format.Parse, text, message) 
Example #4
Source File: test_variable.py    From chainer with MIT License 6 votes vote down vote up
def check_dtype_mismatch(self, x_data, retain):
        xp = backend.get_array_module(x_data)

        class DummyFunction(chainer.Function):
            label = 'dummy_function'

            def forward(self, inputs):
                if not retain:
                    self.retain_inputs(())
                return xp.array(1, np.float32),

            def backward(self, inputs, grads):
                return xp.array([1], np.int32),

        x = chainer.Variable(x_data)
        y = DummyFunction()(x)
        with six.assertRaisesRegex(self, TypeError, 'dummy_function'):
            y.backward() 
Example #5
Source File: test_variable.py    From chainer with MIT License 6 votes vote down vote up
def check_type_mismatch(self, x_data, retain):
        xp = backend.get_array_module(x_data)

        class DummyFunction(chainer.Function):
            label = 'dummy_function'

            def forward(self, inputs):
                if not retain:
                    self.retain_inputs(())
                return xp.array(1, np.float32),

            def backward(self, inputs, grads):
                return [1]

        x = chainer.Variable(x_data)
        y = DummyFunction()(x)
        with six.assertRaisesRegex(self, TypeError, 'dummy_function'):
            y.backward() 
Example #6
Source File: test_stream_server.py    From pagure with GNU General Public License v2.0 6 votes vote down vote up
def test_get_obj_from_path(self):
        """Tests for get_obj_from_path."""
        # Simple issue case.
        result = pss.get_obj_from_path("/test/issue/1")
        self.assertEqual(result.id, 1)

        # Simple PR case.
        result = pss.get_obj_from_path("/test/pull-request/3")
        self.assertEqual(result.id, 3)

        # Non-existent repo.
        six.assertRaisesRegex(
            self,
            PagureEvException,
            r"Project 'foo' not found",
            pss.get_obj_from_path,
            "/foo/issue/1",
        )

        # NOTE: we cannot test the 'Invalid object provided' exception
        # as it's a backup (current code will never hit it) 
Example #7
Source File: test_stream_server.py    From pagure with GNU General Public License v2.0 6 votes vote down vote up
def test_get_pull_request(self):
        """Tests for _get_pull_request."""
        # Simple case: get the existing PR from the existing repo.
        result = pss._get_pull_request(self.repo, "3")
        self.assertEqual(result.id, 3)

        # PR that doesn't exist.
        six.assertRaisesRegex(
            self,
            PagureEvException,
            r"Pull-Request '2' not found",
            pss._get_pull_request,
            self.repo,
            "2",
        )

        # PR from a project with no PR tracker.
        six.assertRaisesRegex(
            self,
            PagureEvException,
            r"No pull-request tracker found",
            pss._get_pull_request,
            self.repo2,
            "1",
        ) 
Example #8
Source File: test_keras_estimators.py    From spark-deep-learning with Apache License 2.0 6 votes vote down vote up
def test_validate_params(self):
        """Test that `KerasImageFileEstimator._validateParams` method works as expected"""
        kifest = KerasImageFileEstimator()

        # should raise an error to define required parameters
        # assuming at least one param without default value
        six.assertRaisesRegex(self, ValueError, 'defined', kifest._validateParams, {})
        kifest.setParams(imageLoader=_load_image_from_uri, inputCol='c1', labelCol='c2')
        kifest.setParams(modelFile='/path/to/file.ext')

        # should raise an error to define or tune parameters
        # assuming at least one tunable param without default value
        six.assertRaisesRegex(self, ValueError, 'tuned', kifest._validateParams, {})
        kifest.setParams(kerasOptimizer='adam', kerasLoss='mse', kerasFitParams={})
        kifest.setParams(outputCol='c3', outputMode='vector')

        # should raise an error to not override
        six.assertRaisesRegex(
            self, ValueError, 'not tuned', kifest._validateParams, {kifest.imageLoader: None})

        # should pass test on supplying all parameters
        self.assertTrue(kifest._validateParams({})) 
Example #9
Source File: text_format_test.py    From go2mapillary with GNU General Public License v3.0 5 votes vote down vote up
def testParseUnknownField(self, message_module):
    message = message_module.TestAllTypes()
    text = 'unknown_field: 8\n'
    six.assertRaisesRegex(self, text_format.ParseError, (
        r'1:1 : Message type "\w+.TestAllTypes" has no field named '
        r'"unknown_field".'), text_format.Parse, text, message) 
Example #10
Source File: text_format_test.py    From coremltools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def testParseDuplicateScalars(self):
    message = unittest_pb2.TestAllTypes()
    text = ('optional_int32: 42 ' 'optional_int32: 67')
    six.assertRaisesRegex(self, text_format.ParseError, (
        '1:36 : Message type "protobuf_unittest.TestAllTypes" should not '
        'have multiple "optional_int32" fields.'), text_format.Parse, text,
                          message) 
Example #11
Source File: replicates.py    From redis-trib.py with MIT License 5 votes vote down vote up
def test_quit_problems(self):
        comm.start_cluster('127.0.0.1', 7100)
        comm.join_cluster('127.0.0.1', 7100, '127.0.0.1', 7101)
        comm.replicate('127.0.0.1', 7100, '127.0.0.1', 7102)
        time.sleep(1)

        rc = StrictRedisCluster(
            startup_nodes=[{
                'host': '127.0.0.1',
                'port': 7100
            }],
            decode_responses=True)

        for i in range(20):
            rc.set('key_%s' % i, 'value_%s' % i)
        for i in range(20):
            self.assertEqual('value_%s' % i, rc.get('key_%s' % i))

        nodes = base.list_nodes('127.0.0.1', 7100)
        self.assertEqual(3, len(nodes))
        self.assertEqual(
            list(range(8192)), nodes[('127.0.0.1', 7101)].assigned_slots)
        self.assertEqual(
            list(range(8192, 16384)), nodes[('127.0.0.1',
                                             7100)].assigned_slots)
        for i in range(20):
            rc.delete('key_%s' % i)

        six.assertRaisesRegex(self, ValueError,
                              '^The master still has slaves$',
                              comm.quit_cluster, '127.0.0.1', 7100)
        comm.quit_cluster('127.0.0.1', 7102)
        comm.quit_cluster('127.0.0.1', 7101)
        six.assertRaisesRegex(self, ValueError, '^This is the last node',
                              comm.quit_cluster, '127.0.0.1', 7100)
        comm.shutdown_cluster('127.0.0.1', 7100) 
Example #12
Source File: text_format_test.py    From coremltools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def testParseDuplicateNestedMessageScalars(self):
    message = unittest_pb2.TestAllTypes()
    text = ('optional_nested_message { bb: 1 } '
            'optional_nested_message { bb: 2 }')
    six.assertRaisesRegex(self, text_format.ParseError, (
        '1:65 : Message type "protobuf_unittest.TestAllTypes.NestedMessage" '
        'should not have multiple "bb" fields.'), text_format.Parse, text,
                          message) 
Example #13
Source File: test_function_node.py    From chainer with MIT License 5 votes vote down vote up
def test_invalid_output_type(self):
        class FunctionNode(chainer.FunctionNode):

            def forward(self, inputs):
                return object(),

        f = FunctionNode()
        x1 = chainer.Variable(self.x1)

        with six.assertRaisesRegex(
                self,
                TypeError,
                'forward output must be a tuple of ndarrays'):
            f.apply((x1,)) 
Example #14
Source File: text_format_test.py    From coremltools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def testParseDuplicateExtensionScalars(self):
    message = unittest_pb2.TestAllExtensions()
    text = ('[protobuf_unittest.optional_int32_extension]: 42 '
            '[protobuf_unittest.optional_int32_extension]: 67')
    six.assertRaisesRegex(self, text_format.ParseError, (
        '1:96 : Message type "protobuf_unittest.TestAllExtensions" '
        'should not have multiple '
        '"protobuf_unittest.optional_int32_extension" extensions.'),
                          text_format.Parse, text, message) 
Example #15
Source File: text_format_test.py    From coremltools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def testParseMessageByFieldNumber(self):
    message = unittest_pb2.TestAllTypes()
    text = ('34: 1\n' 'repeated_uint64: 2\n')
    text_format.Parse(text, message, allow_field_number=True)
    self.assertEqual(1, message.repeated_uint64[0])
    self.assertEqual(2, message.repeated_uint64[1])

    message = unittest_mset_pb2.TestMessageSetContainer()
    text = ('1 {\n'
            '  1545008 {\n'
            '    15: 23\n'
            '  }\n'
            '  1547769 {\n'
            '    25: \"foo\"\n'
            '  }\n'
            '}\n')
    text_format.Parse(text, message, allow_field_number=True)
    ext1 = unittest_mset_pb2.TestMessageSetExtension1.message_set_extension
    ext2 = unittest_mset_pb2.TestMessageSetExtension2.message_set_extension
    self.assertEqual(23, message.message_set.Extensions[ext1].i)
    self.assertEqual('foo', message.message_set.Extensions[ext2].str)

    # Can't parse field number without set allow_field_number=True.
    message = unittest_pb2.TestAllTypes()
    text = '34:1\n'
    six.assertRaisesRegex(self, text_format.ParseError, (
        r'1:1 : Message type "\w+.TestAllTypes" has no field named '
        r'"34".'), text_format.Parse, text, message)

    # Can't parse if field number is not found.
    text = '1234:1\n'
    six.assertRaisesRegex(
        self,
        text_format.ParseError,
        (r'1:1 : Message type "\w+.TestAllTypes" has no field named '
         r'"1234".'),
        text_format.Parse,
        text,
        message,
        allow_field_number=True) 
Example #16
Source File: text_format_test.py    From coremltools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def testParseGroupNotClosed(self):
    message = unittest_pb2.TestAllTypes()
    text = 'RepeatedGroup: <'
    six.assertRaisesRegex(self, text_format.ParseError, '1:16 : Expected ">".',
                          text_format.Parse, text, message)
    text = 'RepeatedGroup: {'
    six.assertRaisesRegex(self, text_format.ParseError, '1:16 : Expected "}".',
                          text_format.Parse, text, message) 
Example #17
Source File: test_data_loader.py    From image-segmentation-keras with MIT License 5 votes vote down vote up
def test_get_pairs_from_paths_with_no_matching_segs(self):
        images = ["A.jpg", "B.jpg", "C.jpeg", "D.png"]
        segs = ["A.png", "B.png", "C.png"]
        self._setup_images_and_segs(images, segs)

        expected = [("A.jpg", "A.png"),
                    ("B.jpg", "B.png"),
                    ("C.jpeg", "C.png")]
        expected_values = []
        # Transform paths
        for (x, y) in expected:
            expected_values.append((os.path.join(self.img_path, x), os.path.join(self.seg_path, y)))
        six.assertRaisesRegex(self, data_loader.DataLoaderError, "No corresponding segmentation found for image", data_loader.get_pairs_from_paths, self.img_path, self.seg_path) 
Example #18
Source File: test_argument.py    From chainer with MIT License 5 votes vote down vote up
def test_parse_kwargs(self):

        def test(**kwargs):
            return parse_kwargs(kwargs, ('foo', 1), ('bar', 2))

        self.assertEqual(test(), (1, 2))
        self.assertEqual(test(bar=1, foo=2), (2, 1))

        re = r'test\(\) got unexpected keyword argument\(s\) \'ham\', \'spam\''
        with six.assertRaisesRegex(self, TypeError, re):
            test(spam=1, ham=2) 
Example #19
Source File: test_forget.py    From chainer with MIT License 5 votes vote down vote up
def test_invalid_tuple_type_13th(self):
        with six.assertRaisesRegex(self, RuntimeError, '13th.*int'):
            functions.forget(lambda: (self.v,) * 12 + (1,)) 
Example #20
Source File: test_forget.py    From chainer with MIT License 5 votes vote down vote up
def test_invalid_tuple_type_12th(self):
        with six.assertRaisesRegex(self, RuntimeError, '12th.*int'):
            functions.forget(lambda: (self.v,) * 11 + (1,)) 
Example #21
Source File: test_forget.py    From chainer with MIT License 5 votes vote down vote up
def test_invalid_tuple_type_4th(self):
        with six.assertRaisesRegex(self, RuntimeError, '4th.*int'):
            functions.forget(lambda: (self.v,) * 3 + (1,)) 
Example #22
Source File: test_forget.py    From chainer with MIT License 5 votes vote down vote up
def test_invalid_tuple_type_3rd(self):
        with six.assertRaisesRegex(self, RuntimeError, '3rd.*int'):
            functions.forget(lambda: (self.v, self.v, 1)) 
Example #23
Source File: test_forget.py    From chainer with MIT License 5 votes vote down vote up
def test_invalid_tuple_type_2nd(self):
        with six.assertRaisesRegex(self, RuntimeError, '2nd.*int'):
            functions.forget(lambda: (self.v, 1)) 
Example #24
Source File: test_forget.py    From chainer with MIT License 5 votes vote down vote up
def test_invalid_tuple_type_1st(self):
        with six.assertRaisesRegex(self, RuntimeError, '1st.*int'):
            functions.forget(lambda: (1,)) 
Example #25
Source File: test_forget.py    From chainer with MIT License 5 votes vote down vote up
def test_invalid_type(self):
        with six.assertRaisesRegex(self, RuntimeError, 'int'):
            functions.forget(lambda: 1) 
Example #26
Source File: test_classifier.py    From chainer with MIT License 5 votes vote down vote up
def test_invalid_label_key_type(self):
        with six.assertRaisesRegex(
                self, TypeError, 'label_key must be int or str'):
            links.Classifier(links.Linear(10, 3), label_key=None) 
Example #27
Source File: test_variable.py    From chainer with MIT License 5 votes vote down vote up
def test_traceback_numpy_error(self):
        x = chainer.Variable(np.array(0.))
        line = inspect.currentframe().f_lineno + 1
        y = chainer.functions.sqrt(x)  # `line` is THIS line
        with six.assertRaisesRegex(self, FloatingPointError, 'line %d' % line):
            with np.errstate(divide='raise'):
                y.backward() 
Example #28
Source File: test_variable.py    From chainer with MIT License 5 votes vote down vote up
def test_invalid_value_type(self):
        with six.assertRaisesRegex(self, TypeError, 'int'):
            chainer.Variable(1) 
Example #29
Source File: test_optimizers_by_linear_model.py    From chainer with MIT License 5 votes vote down vote up
def test_initialize(self):
        skip, msg = self.skip_loss_scaling()
        if skip:
            return unittest.SkipTest(msg)
        model = self.model.model
        assert isinstance(model, chainer.Link)
        optimizer = self.create()
        optimizer.setup(model)
        _optimizer_loss_scaling(optimizer, self.loss_scaling)

        msg = 'optimization target must be a link'
        with six.assertRaisesRegex(self, TypeError, msg):
            optimizer.setup('xxx') 
Example #30
Source File: text_format_test.py    From go2mapillary with GNU General Public License v3.0 5 votes vote down vote up
def testParseBadIntValue(self, message_module):
    message = message_module.TestAllTypes()
    text = 'optional_int32: bork'
    six.assertRaisesRegex(self, text_format.ParseError,
                          ('1:17 : Couldn\'t parse integer: bork'),
                          text_format.Parse, text, message)