Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit dac5605

Browse filesBrowse files
TST replace assert_raise_* by pytest.raises in linear_model (#19440)
1 parent 31b34b5 commit dac5605
Copy full SHA for dac5605

File tree

7 files changed

+228
-156
lines changed
Filter options

7 files changed

+228
-156
lines changed

‎sklearn/linear_model/tests/test_coordinate_descent.py

Copy file name to clipboardExpand all lines: sklearn/linear_model/tests/test_coordinate_descent.py
+23-18Lines changed: 23 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -14,14 +14,10 @@
1414
from sklearn.model_selection import train_test_split
1515
from sklearn.pipeline import make_pipeline
1616
from sklearn.preprocessing import StandardScaler
17-
1817
from sklearn.exceptions import ConvergenceWarning
1918
from sklearn.utils._testing import assert_allclose
2019
from sklearn.utils._testing import assert_array_almost_equal
2120
from sklearn.utils._testing import assert_almost_equal
22-
from sklearn.utils._testing import assert_raises
23-
from sklearn.utils._testing import assert_raises_regex
24-
from sklearn.utils._testing import assert_raise_message
2521
from sklearn.utils._testing import assert_warns
2622
from sklearn.utils._testing import assert_warns_message
2723
from sklearn.utils._testing import ignore_warnings
@@ -735,7 +731,8 @@ def test_multioutput_enetcv_error():
735731
X = rng.randn(10, 2)
736732
y = rng.randn(10, 2)
737733
clf = ElasticNetCV()
738-
assert_raises(ValueError, clf.fit, X, y)
734+
with pytest.raises(ValueError):
735+
clf.fit(X, y)
739736

740737

741738
def test_multitask_enet_and_lasso_cv():
@@ -810,14 +807,18 @@ def test_precompute_invalid_argument():
810807
X, y, _, _ = build_dataset()
811808
for clf in [ElasticNetCV(precompute="invalid"),
812809
LassoCV(precompute="invalid")]:
813-
assert_raises_regex(ValueError, ".*should be.*True.*False.*auto.*"
814-
"array-like.*Got 'invalid'", clf.fit, X, y)
810+
err_msg = ".*should be.*True.*False.*auto.* array-like.*Got 'invalid'"
811+
with pytest.raises(ValueError, match=err_msg):
812+
clf.fit(X, y)
815813

816814
# Precompute = 'auto' is not supported for ElasticNet and Lasso
817-
assert_raises_regex(ValueError, ".*should be.*True.*False.*array-like.*"
818-
"Got 'auto'", ElasticNet(precompute='auto').fit, X, y)
819-
assert_raises_regex(ValueError, ".*should be.*True.*False.*array-like.*"
820-
"Got 'auto'", Lasso(precompute='auto').fit, X, y)
815+
err_msg = ".*should be.*True.*False.*array-like.*Got 'auto'"
816+
with pytest.raises(ValueError, match=err_msg):
817+
ElasticNet(precompute='auto').fit(X, y)
818+
819+
err_msg = ".*should be.*True.*False.*array-like.*Got 'auto'"
820+
with pytest.raises(ValueError, match=err_msg):
821+
Lasso(precompute='auto').fit(X, y)
821822

822823

823824
def test_elasticnet_precompute_incorrect_gram():
@@ -946,7 +947,8 @@ def test_random_descent():
946947

947948
# Raise error when selection is not in cyclic or random.
948949
clf_random = ElasticNet(selection='invalid')
949-
assert_raises(ValueError, clf_random.fit, X, y)
950+
with pytest.raises(ValueError):
951+
clf_random.fit(X, y)
950952

951953

952954
def test_enet_path_positive():
@@ -963,7 +965,8 @@ def test_enet_path_positive():
963965
# For multi output, positive parameter is not allowed
964966
# Test that an error is raised
965967
for path in [enet_path, lasso_path]:
966-
assert_raises(ValueError, path, X, Y, positive=True)
968+
with pytest.raises(ValueError):
969+
path(X, Y, positive=True)
967970

968971

969972
def test_sparse_dense_descent_paths():
@@ -991,7 +994,8 @@ def test_check_input_false():
991994
# With no input checking, providing X in C order should result in false
992995
# computation
993996
X = check_array(X, order='C', dtype='float64')
994-
assert_raises(ValueError, clf.fit, X, y, check_input=False)
997+
with pytest.raises(ValueError):
998+
clf.fit(X, y, check_input=False)
995999

9961000

9971001
@pytest.mark.parametrize("check_input", [True, False])
@@ -1105,10 +1109,11 @@ def test_enet_l1_ratio():
11051109
X = np.array([[1, 2, 4, 5, 8], [3, 5, 7, 7, 8]]).T
11061110
y = np.array([12, 10, 11, 21, 5])
11071111

1108-
assert_raise_message(ValueError, msg, ElasticNetCV(
1109-
l1_ratio=0, random_state=42).fit, X, y)
1110-
assert_raise_message(ValueError, msg, MultiTaskElasticNetCV(
1111-
l1_ratio=0, random_state=42).fit, X, y[:, None])
1112+
with pytest.raises(ValueError, match=msg):
1113+
ElasticNetCV(l1_ratio=0, random_state=42).fit(X, y)
1114+
1115+
with pytest.raises(ValueError, match=msg):
1116+
MultiTaskElasticNetCV(l1_ratio=0, random_state=42).fit(X, y[:, None])
11121117

11131118
# Test that l1_ratio=0 is allowed if we supply a grid manually
11141119
alphas = [0.1, 10]

‎sklearn/linear_model/tests/test_logistic.py

Copy file name to clipboardExpand all lines: sklearn/linear_model/tests/test_logistic.py
+68-44Lines changed: 68 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import os
2+
import re
23
import warnings
34
import numpy as np
45
from numpy.testing import assert_allclose, assert_almost_equal
@@ -18,8 +19,6 @@
1819
from sklearn.model_selection import cross_val_score
1920
from sklearn.preprocessing import LabelEncoder, StandardScaler
2021
from sklearn.utils import compute_class_weight, _IS_32BIT
21-
from sklearn.utils._testing import assert_raise_message
22-
from sklearn.utils._testing import assert_raises
2322
from sklearn.utils._testing import assert_warns
2423
from sklearn.utils._testing import ignore_warnings
2524
from sklearn.utils._testing import assert_warns_message
@@ -79,24 +78,33 @@ def test_predict_2_classes():
7978
def test_error():
8079
# Test for appropriate exception on errors
8180
msg = "Penalty term must be positive"
82-
assert_raise_message(ValueError, msg,
83-
LogisticRegression(C=-1).fit, X, Y1)
84-
assert_raise_message(ValueError, msg,
85-
LogisticRegression(C="test").fit, X, Y1)
81+
82+
with pytest.raises(ValueError, match=msg):
83+
LogisticRegression(C=-1).fit(X, Y1)
84+
85+
with pytest.raises(ValueError, match=msg):
86+
LogisticRegression(C="test").fit(X, Y1)
8687

8788
msg = "is not a valid scoring value"
88-
assert_raise_message(ValueError, msg,
89-
LogisticRegressionCV(scoring='bad-scorer', cv=2).fit,
90-
X, Y1)
89+
with pytest.raises(ValueError, match=msg):
90+
LogisticRegressionCV(scoring='bad-scorer', cv=2).fit(X, Y1)
9191

9292
for LR in [LogisticRegression, LogisticRegressionCV]:
9393
msg = "Tolerance for stopping criteria must be positive"
94-
assert_raise_message(ValueError, msg, LR(tol=-1).fit, X, Y1)
95-
assert_raise_message(ValueError, msg, LR(tol="test").fit, X, Y1)
94+
95+
with pytest.raises(ValueError, match=msg):
96+
LR(tol=-1).fit(X, Y1)
97+
98+
with pytest.raises(ValueError, match=msg):
99+
LR(tol="test").fit(X, Y1)
96100

97101
msg = "Maximum number of iteration must be positive"
98-
assert_raise_message(ValueError, msg, LR(max_iter=-1).fit, X, Y1)
99-
assert_raise_message(ValueError, msg, LR(max_iter="test").fit, X, Y1)
102+
103+
with pytest.raises(ValueError, match=msg):
104+
LR(max_iter=-1).fit(X, Y1)
105+
106+
with pytest.raises(ValueError, match=msg):
107+
LR(max_iter="test").fit(X, Y1)
100108

101109

102110
def test_logistic_cv_mock_scorer():
@@ -196,39 +204,46 @@ def test_predict_iris():
196204
@pytest.mark.parametrize('solver', ['lbfgs', 'newton-cg', 'sag', 'saga'])
197205
def test_multinomial_validation(solver):
198206
lr = LogisticRegression(C=-1, solver=solver, multi_class='multinomial')
199-
assert_raises(ValueError, lr.fit, [[0, 1], [1, 0]], [0, 1])
207+
208+
with pytest.raises(ValueError):
209+
lr.fit([[0, 1], [1, 0]], [0, 1])
200210

201211

202212
@pytest.mark.parametrize('LR', [LogisticRegression, LogisticRegressionCV])
203213
def test_check_solver_option(LR):
204214
X, y = iris.data, iris.target
205215

206-
msg = ("Logistic Regression supports only solvers in ['liblinear', "
207-
"'newton-cg', 'lbfgs', 'sag', 'saga'], got wrong_name.")
216+
msg = (r"Logistic Regression supports only solvers in \['liblinear', "
217+
r"'newton-cg', 'lbfgs', 'sag', 'saga'\], got wrong_name.")
208218
lr = LR(solver="wrong_name", multi_class="ovr")
209-
assert_raise_message(ValueError, msg, lr.fit, X, y)
219+
with pytest.raises(ValueError, match=msg):
220+
lr.fit(X, y)
210221

211222
msg = ("multi_class should be 'multinomial', 'ovr' or 'auto'. "
212223
"Got wrong_name")
213224
lr = LR(solver='newton-cg', multi_class="wrong_name")
214-
assert_raise_message(ValueError, msg, lr.fit, X, y)
225+
with pytest.raises(ValueError, match=msg):
226+
lr.fit(X, y)
215227

216228
# only 'liblinear' solver
217229
msg = "Solver liblinear does not support a multinomial backend."
218230
lr = LR(solver='liblinear', multi_class='multinomial')
219-
assert_raise_message(ValueError, msg, lr.fit, X, y)
231+
with pytest.raises(ValueError, match=msg):
232+
lr.fit(X, y)
220233

221234
# all solvers except 'liblinear' and 'saga'
222235
for solver in ['newton-cg', 'lbfgs', 'sag']:
223236
msg = ("Solver %s supports only 'l2' or 'none' penalties," %
224237
solver)
225238
lr = LR(solver=solver, penalty='l1', multi_class='ovr')
226-
assert_raise_message(ValueError, msg, lr.fit, X, y)
239+
with pytest.raises(ValueError, match=msg):
240+
lr.fit(X, y)
227241
for solver in ['newton-cg', 'lbfgs', 'sag', 'saga']:
228242
msg = ("Solver %s supports only dual=False, got dual=True" %
229243
solver)
230244
lr = LR(solver=solver, dual=True, multi_class='ovr')
231-
assert_raise_message(ValueError, msg, lr.fit, X, y)
245+
with pytest.raises(ValueError, match=msg):
246+
lr.fit(X, y)
232247

233248
# only saga supports elasticnet. We only test for liblinear because the
234249
# error is raised before for the other solvers (solver %s supports only l2
@@ -237,12 +252,14 @@ def test_check_solver_option(LR):
237252
msg = ("Only 'saga' solver supports elasticnet penalty, got "
238253
"solver={}.".format(solver))
239254
lr = LR(solver=solver, penalty='elasticnet')
240-
assert_raise_message(ValueError, msg, lr.fit, X, y)
255+
with pytest.raises(ValueError, match=msg):
256+
lr.fit(X, y)
241257

242258
# liblinear does not support penalty='none'
243259
msg = "penalty='none' is not supported for the liblinear solver"
244260
lr = LR(penalty='none', solver='liblinear')
245-
assert_raise_message(ValueError, msg, lr.fit, X, y)
261+
with pytest.raises(ValueError, match=msg):
262+
lr.fit(X, y)
246263

247264

248265
@pytest.mark.parametrize('solver', ['lbfgs', 'newton-cg', 'sag', 'saga'])
@@ -318,11 +335,13 @@ def test_inconsistent_input():
318335

319336
# Wrong dimensions for training data
320337
y_wrong = y_[:-1]
321-
assert_raises(ValueError, clf.fit, X, y_wrong)
338+
339+
with pytest.raises(ValueError):
340+
clf.fit(X, y_wrong)
322341

323342
# Wrong dimensions for test data
324-
assert_raises(ValueError, clf.fit(X_, y_).predict,
325-
rng.random_sample((3, 12)))
343+
with pytest.raises(ValueError):
344+
clf.fit(X_, y_).predict(rng.random_sample((3, 12)))
326345

327346

328347
def test_write_parameters():
@@ -340,7 +359,9 @@ def test_nan():
340359
Xnan = np.array(X, dtype=np.float64)
341360
Xnan[0, 1] = np.nan
342361
logistic = LogisticRegression(random_state=0)
343-
assert_raises(ValueError, logistic.fit, Xnan, Y1)
362+
363+
with pytest.raises(ValueError):
364+
logistic.fit(Xnan, Y1)
344365

345366

346367
def test_consistency_path():
@@ -422,8 +443,8 @@ def test_liblinear_dual_random_state():
422443
assert_array_almost_equal(lr1.coef_, lr2.coef_)
423444
# different results for different random states
424445
msg = "Arrays are not almost equal to 6 decimals"
425-
assert_raise_message(AssertionError, msg,
426-
assert_array_almost_equal, lr1.coef_, lr3.coef_)
446+
with pytest.raises(AssertionError, match=msg):
447+
assert_array_almost_equal(lr1.coef_, lr3.coef_)
427448

428449

429450
def test_logistic_loss_and_grad():
@@ -1042,7 +1063,8 @@ def test_logreg_intercept_scaling():
10421063
msg = ('Intercept scaling is %r but needs to be greater than 0.'
10431064
' To disable fitting an intercept,'
10441065
' set fit_intercept=False.' % clf.intercept_scaling)
1045-
assert_raise_message(ValueError, msg, clf.fit, X, Y1)
1066+
with pytest.raises(ValueError, match=msg):
1067+
clf.fit(X, Y1)
10461068

10471069

10481070
def test_logreg_intercept_scaling_zero():
@@ -1616,14 +1638,15 @@ def test_LogisticRegressionCV_elasticnet_attribute_shapes():
16161638
@pytest.mark.parametrize('l1_ratio', (-1, 2, None, 'something_wrong'))
16171639
def test_l1_ratio_param(l1_ratio):
16181640

1619-
msg = "l1_ratio must be between 0 and 1; got (l1_ratio=%r)" % l1_ratio
1620-
assert_raise_message(ValueError, msg,
1621-
LogisticRegression(penalty='elasticnet',
1622-
solver='saga',
1623-
l1_ratio=l1_ratio).fit, X, Y1)
1641+
msg = r"l1_ratio must be between 0 and 1; got \(l1_ratio=%r\)" % l1_ratio
1642+
with pytest.raises(ValueError, match=msg):
1643+
LogisticRegression(penalty='elasticnet', solver='saga',
1644+
l1_ratio=l1_ratio).fit(X, Y1)
1645+
16241646
if l1_ratio is not None:
16251647
msg = ("l1_ratio parameter is only used when penalty is 'elasticnet'."
16261648
" Got (penalty=l1)")
1649+
16271650
assert_warns_message(UserWarning, msg,
16281651
LogisticRegression(penalty='l1', solver='saga',
16291652
l1_ratio=l1_ratio).fit, X, Y1)
@@ -1634,11 +1657,12 @@ def test_l1_ratios_param(l1_ratios):
16341657

16351658
msg = ("l1_ratios must be a list of numbers between 0 and 1; got "
16361659
"(l1_ratios=%r)" % l1_ratios)
1637-
assert_raise_message(ValueError, msg,
1638-
LogisticRegressionCV(penalty='elasticnet',
1639-
solver='saga',
1640-
l1_ratios=l1_ratios, cv=2).fit,
1641-
X, Y1)
1660+
1661+
with pytest.raises(ValueError, match=re.escape(msg)):
1662+
LogisticRegressionCV(penalty='elasticnet',
1663+
solver='saga',
1664+
l1_ratios=l1_ratios, cv=2).fit(X, Y1)
1665+
16421666
if l1_ratios is not None:
16431667
msg = ("l1_ratios parameter is only used when penalty is "
16441668
"'elasticnet'. Got (penalty=l1)")
@@ -1756,12 +1780,12 @@ def test_penalty_none(solver):
17561780
assert_array_equal(pred_none, pred_l2_C_inf)
17571781

17581782
lr = LogisticRegressionCV(penalty='none')
1759-
assert_raise_message(
1760-
ValueError,
1783+
err_msg = (
17611784
"penalty='none' is not useful and not supported by "
1762-
"LogisticRegressionCV",
1763-
lr.fit, X, y
1785+
"LogisticRegressionCV"
17641786
)
1787+
with pytest.raises(ValueError, match=err_msg):
1788+
lr.fit(X, y)
17651789

17661790

17671791
@pytest.mark.parametrize(

‎sklearn/linear_model/tests/test_passive_aggressive.py

Copy file name to clipboardExpand all lines: sklearn/linear_model/tests/test_passive_aggressive.py
+13-8Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,6 @@
66
from sklearn.utils._testing import assert_array_almost_equal
77
from sklearn.utils._testing import assert_array_equal
88
from sklearn.utils._testing import assert_almost_equal
9-
from sklearn.utils._testing import assert_raises
10-
119
from sklearn.base import ClassifierMixin
1210
from sklearn.utils import check_random_state
1311
from sklearn.datasets import load_iris
@@ -130,7 +128,8 @@ def test_classifier_correctness(loss):
130128
def test_classifier_undefined_methods():
131129
clf = PassiveAggressiveClassifier(max_iter=100)
132130
for meth in ("predict_proba", "predict_log_proba", "transform"):
133-
assert_raises(AttributeError, lambda x: getattr(clf, x), meth)
131+
with pytest.raises(AttributeError):
132+
getattr(clf, meth)
134133

135134

136135
def test_class_weights():
@@ -158,7 +157,8 @@ def test_class_weights():
158157
def test_partial_fit_weight_class_balanced():
159158
# partial_fit with class_weight='balanced' not supported
160159
clf = PassiveAggressiveClassifier(class_weight="balanced", max_iter=100)
161-
assert_raises(ValueError, clf.partial_fit, X, y, classes=np.unique(y))
160+
with pytest.raises(ValueError):
161+
clf.partial_fit(X, y, classes=np.unique(y))
162162

163163

164164
def test_equal_class_weight():
@@ -189,7 +189,8 @@ def test_wrong_class_weight_label():
189189
y2 = [1, 1, 1, -1, -1]
190190

191191
clf = PassiveAggressiveClassifier(class_weight={0: 0.5}, max_iter=100)
192-
assert_raises(ValueError, clf.fit, X2, y2)
192+
with pytest.raises(ValueError):
193+
clf.fit(X2, y2)
193194

194195

195196
def test_wrong_class_weight_format():
@@ -199,10 +200,12 @@ def test_wrong_class_weight_format():
199200
y2 = [1, 1, 1, -1, -1]
200201

201202
clf = PassiveAggressiveClassifier(class_weight=[0.5], max_iter=100)
202-
assert_raises(ValueError, clf.fit, X2, y2)
203+
with pytest.raises(ValueError):
204+
clf.fit(X2, y2)
203205

204206
clf = PassiveAggressiveClassifier(class_weight="the larch", max_iter=100)
205-
assert_raises(ValueError, clf.fit, X2, y2)
207+
with pytest.raises(ValueError):
208+
clf.fit(X2, y2)
206209

207210

208211
def test_regressor_mse():
@@ -265,7 +268,9 @@ def test_regressor_correctness(loss):
265268
def test_regressor_undefined_methods():
266269
reg = PassiveAggressiveRegressor(max_iter=100)
267270
for meth in ("transform",):
268-
assert_raises(AttributeError, lambda x: getattr(reg, x), meth)
271+
with pytest.raises(AttributeError):
272+
getattr(reg, meth)
273+
269274

270275
# TODO: remove in 1.0
271276
@pytest.mark.parametrize('klass', [PassiveAggressiveClassifier,

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.