python类warns()的实例源码

test_requests.py 文件源码 项目:filegardener 作者: smorin 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def test_https_warnings(self, httpbin_secure, httpbin_ca_bundle):
        """warnings are emitted with requests.get"""
        if HAS_MODERN_SSL or HAS_PYOPENSSL:
            warnings_expected = ('SubjectAltNameWarning', )
        else:
            warnings_expected = ('SNIMissingWarning',
                                 'InsecurePlatformWarning',
                                 'SubjectAltNameWarning', )

        with pytest.warns(None) as warning_records:
            warnings.simplefilter('always')
            requests.get(httpbin_secure('status', '200'),
                         verify=httpbin_ca_bundle)

        warning_records = [item for item in warning_records
                           if item.category.__name__ != 'ResourceWarning']

        warnings_category = tuple(
            item.category.__name__ for item in warning_records)
        assert warnings_category == warnings_expected
test_requests.py 文件源码 项目:filegardener 作者: smorin 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def test_https_warnings(self, httpbin_secure, httpbin_ca_bundle):
        """warnings are emitted with requests.get"""
        if HAS_MODERN_SSL or HAS_PYOPENSSL:
            warnings_expected = ('SubjectAltNameWarning', )
        else:
            warnings_expected = ('SNIMissingWarning',
                                 'InsecurePlatformWarning',
                                 'SubjectAltNameWarning', )

        with pytest.warns(None) as warning_records:
            warnings.simplefilter('always')
            requests.get(httpbin_secure('status', '200'),
                         verify=httpbin_ca_bundle)

        warning_records = [item for item in warning_records
                           if item.category.__name__ != 'ResourceWarning']

        warnings_category = tuple(
            item.category.__name__ for item in warning_records)
        assert warnings_category == warnings_expected
test_warn.py 文件源码 项目:warn 作者: Carreau 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def test_1():


    with pytest.warns(DeprecationWarning) as records:
        warnings.simplefilter('ignore')
        print('warnings.warn is ', warnings.warn.__module__)
        print('filters', warnings.filters)
        filterwarnings('default', category=DeprecationWarning,
            emodule='examples.dependency')
        filterwarnings('ignore', category=DeprecationWarning,
            emodule='examples.dependency.bar')
        consumer()

    for r in records.list:
        print('Record :', r.message, 'In file', r.filename)
    assert len(records) == 1
test_hiwenet.py 文件源码 项目:hiwenet 作者: raamana 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def test_more_metrics():
    ew = hiwenet(features, groups, weight_method='diff_medians',
                 use_original_distribution=True)
    assert len(ew) == num_groups
    assert ew.shape[0] == num_groups and ew.shape[1] == num_groups

    ew_abs = hiwenet(features, groups, weight_method='diff_medians_abs',
                     use_original_distribution=True)
    assert np.allclose(np.abs(ew), ew_abs, equal_nan=True)

    with warns(HiwenetWarning):
        ew = hiwenet(features, groups, weight_method='diff_medians',
                     use_original_distribution=False)

    with warns(HiwenetWarning):
        ew = hiwenet(features, groups,
                     weight_method='manhattan',
                     use_original_distribution=True)
tests.py 文件源码 项目:gtfs-tripify 作者: ResidentMario 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def test_empty_trip_id_2(self):
        feed = {'header': {'timestamp': 1},
                'entity': [{'id': '000022',
                            'type': 'vehicle_update',
                            'vehicle': {'current_stop_sequence': 0,
                                        'stop_id': '',
                                        'current_status': 'IN_TRANSIT_TO',
                                        'timestamp': 0,
                                        'trip': {'route_id': '',
                                                 'trip_id': '',
                                                 'start_date': ''}}}]}
        # noinspection PyUnresolvedReferences
        with pytest.warns(UserWarning):
            feed = gt.correct(feed)

        assert len(feed['entity']) == 0
test_input_A.py 文件源码 项目:PyPardisoProject 作者: haasad 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def test_input_A_dtypes():
    A, b = create_test_A_b_rand(10,0.5)
    for d in [np.float16, np.float32, np.int16, np.int32, np.int64, np.complex64, 
              np.complex128, np.complex128, np.uint16, np.uint32, np.uint64]:
        with pytest.raises(TypeError):
            ps.solve(A.astype(d), b)


#def test_input_A_empty_col():
#    A, b = create_test_A_b_rand(25, 0.1)
#    A = np.array(A.todense())
#    A[0,:] = 0
#    A[:,0] = 0
#    A[0, 1] = 1
#    Asp = sp.csr_matrix(A)
#    with pytest.warns(PyPardisoWarning):
#        x = ps.solve(A,b)
#        print(x)

# dosen't necessarily return inf value, can also be just really big
test_net.py 文件源码 项目:skorch 作者: dnouri 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def test_pickle_save_load_cuda_intercompatibility(
            self, net_cls, module_cls, tmpdir):
        from skorch.exceptions import DeviceWarning

        net = net_cls(module=module_cls, use_cuda=True).initialize()

        p = tmpdir.mkdir('skorch').join('testmodel.pkl')
        with open(str(p), 'wb') as f:
            pickle.dump(net, f)
        del net

        with patch('torch.cuda.is_available', lambda *_: False):
            with pytest.warns(DeviceWarning) as w:
                with open(str(p), 'rb') as f:
                    m = pickle.load(f)

        # The loaded model should not use CUDA anymore as it
        # already knows CUDA is not available.
        assert m.use_cuda is False

        assert len(w.list) == 1  # only 1 warning
        assert w.list[0].message.args[0] == (
            'Model configured to use CUDA but no CUDA '
            'devices available. Loading on CPU instead.')
test_palettes.py 文件源码 项目:mizani 作者: has2k1 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def test_brewer_pal():
    result = brewer_pal()(5)
    assert all(s[0] == '#' and len(s) == 7 for s in result)

    result = brewer_pal('qual', 2)(5)
    assert all(s[0] == '#' and len(s) == 7 for s in result)

    result = brewer_pal('div', 2)(5)
    assert all(s[0] == '#' and len(s) == 7 for s in result)

    with pytest.raises(ValueError):
        brewer_pal('div', 200)(5)

    result = brewer_pal('seq', 'Greens')(5)
    assert all(s[0] == '#' and len(s) == 7 for s in result)

    with pytest.warns(UserWarning):
        brewer_pal()(100)

    result = brewer_pal('seq', 'Blues')(2)
    assert all(s[0] == '#' and len(s) == 7 for s in result)
test_formatters.py 文件源码 项目:mizani 作者: has2k1 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def test_date_format():
    x = pd.date_range('1/1/2010', periods=4, freq='4AS')
    result = date_format('%Y')(x)
    assert result == ['2010', '2014', '2018', '2022']

    x = [datetime(year=2005+i, month=i, day=i) for i in range(1, 5)]
    result = date_format('%Y:%m:%d')(x)
    assert result == \
        ['2006:01:01', '2007:02:02', '2008:03:03', '2009:04:04']

    # Different timezones
    pct = pytz.timezone('US/Pacific')
    ug = pytz.timezone('Africa/Kampala')
    x = [datetime(2010, 1, 1, tzinfo=ug),
         datetime(2010, 1, 1, tzinfo=pct)]
    with pytest.warns(UserWarning):
        date_format()(x)
test_resource_warnings.py 文件源码 项目:nidaqmx-python 作者: ni 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def test_task_double_close(self):
        with pytest.warns(DaqResourceWarning):
            with nidaqmx.Task() as task:
                task.close()
test_resource_warnings.py 文件源码 项目:nidaqmx-python 作者: ni 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def test_unclosed_task(self):
        task = nidaqmx.Task()
        # Since __del__ is not guaranteed to be called, for the purposes of
        # consistent test results call __del__ manually.
        with pytest.warns(DaqResourceWarning):
            task.__del__()
schema_cache_test.py 文件源码 项目:data_pipeline 作者: Yelp 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def test_schema_cache_deprecated(self):
        with pytest.warns(DeprecationWarning) as deprecation_record:
            SchematizerClient()
        assert (deprecation_record[0].message.args[0] ==
                "data_pipeline.schema_cache.SchematizerClient is deprecated.")
test_main.py 文件源码 项目:python-devtools 作者: samuelcolvin 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def test_small_call_frame_warning():
    debug_ = Debug(frame_context_length=2)
    with pytest.warns(SyntaxWarning):
        v = debug_.format(
            1,
            2,
            3,
        )
    assert re.sub(':\d{2,}', ':<line no>', str(v)) == (
        'tests/test_main.py:<line no> test_small_call_frame_warning\n'
        '    1 (int)\n'
        '    2 (int)\n'
        '    3 (int)'
    )
test_main.py 文件源码 项目:python-devtools 作者: samuelcolvin 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def test_eval():
    with pytest.warns(RuntimeWarning):
        v = eval('debug.format(1)')

    assert str(v) == '<string>:1 <module>\n    1 (int)'
test_main.py 文件源码 项目:python-devtools 作者: samuelcolvin 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def test_warnings_disabled():
    debug_ = Debug(warnings=False)
    with pytest.warns(None) as warnings:
        v1 = eval('debug_.format(1)')
        assert str(v1) == '<string>:1 <module>\n    1 (int)'
        v2 = debug_.format(1)
        assert 'test_warnings_disabled\n    1 (int)' in str(v2)
    assert len(warnings) == 0
test_main.py 文件源码 项目:python-devtools 作者: samuelcolvin 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def test_eval_kwargs():
    with pytest.warns(RuntimeWarning):
        v = eval('debug.format(1, apple="pear")')

    assert set(str(v).split('\n')) == {
        "<string>:1 <module>",
        "    1 (int)",
        "    apple: 'pear' (str) len=4",
    }
test_main.py 文件源码 项目:python-devtools 作者: samuelcolvin 项目源码 文件源码 阅读 37 收藏 0 点赞 0 评论 0
def test_exec(capsys):
    with pytest.warns(RuntimeWarning):
        exec(
            'a = 1\n'
            'b = 2\n'
            'debug(b, a + b)'
        )

    stdout, stderr = capsys.readouterr()
    assert stdout == (
        '<string>:3 <module>\n'
        '    2 (int)\n'
        '    3 (int)\n'
    )
    assert stderr == ''
test_latexipy.py 文件源码 项目:latexipy 作者: masasin 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def test_height_too_high(self):
        with pytest.warns(UserWarning):
            height = MAX_HEIGHT_INCH + 1
            assert lp.figure_size(height=height) == (self.width,
                                                     MAX_HEIGHT_INCH)
test_latexipy.py 文件源码 项目:latexipy 作者: masasin 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
def test_warns_if_no_figures(self):
        with patch('pathlib.Path.mkdir'), \
                patch('matplotlib.pyplot.savefig'):
            with pytest.warns(UserWarning):
                self.f()
test_tabulate.py 文件源码 项目:ananke 作者: beiko-lab 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def test_tabulate_skipped_sample_warning():
    """Test that a warning is provided if sequences in the FASTA file are not
    used because there is no corresponding sample in the metadata mapping"""
    seqf = open("./tests/data/sequences_extra_sample.fasta")
    metadata_mapping = read_metadata("./tests/data/metadata_mapping.txt",
                                     "time_points", "time_mask")
    with pytest.warns(UserWarning):
        seqcount = tabulate(seqf, metadata_mapping, False)
    seqf.close()


问题


面经


文章

微信
公众号

扫码关注公众号