Test if two strings are equal. If the given strings are equal, `assert_string_equal` does nothing. If they are not equal, an AssertionError is raised, and the diff between the strings is shown. Parameters ---------- actual : str The string to test for equality
(actual, desired)
| 1353 | |
| 1354 | |
| 1355 | def assert_string_equal(actual, desired): |
| 1356 | """ |
| 1357 | Test if two strings are equal. |
| 1358 | |
| 1359 | If the given strings are equal, `assert_string_equal` does nothing. |
| 1360 | If they are not equal, an AssertionError is raised, and the diff |
| 1361 | between the strings is shown. |
| 1362 | |
| 1363 | Parameters |
| 1364 | ---------- |
| 1365 | actual : str |
| 1366 | The string to test for equality against the expected string. |
| 1367 | desired : str |
| 1368 | The expected string. |
| 1369 | |
| 1370 | Examples |
| 1371 | -------- |
| 1372 | >>> np.testing.assert_string_equal('abc', 'abc') |
| 1373 | >>> np.testing.assert_string_equal('abc', 'abcd') |
| 1374 | Traceback (most recent call last): |
| 1375 | File "<stdin>", line 1, in <module> |
| 1376 | ... |
| 1377 | AssertionError: Differences in strings: |
| 1378 | - abc+ abcd? + |
| 1379 | |
| 1380 | """ |
| 1381 | # delay import of difflib to reduce startup time |
| 1382 | __tracebackhide__ = True # Hide traceback for py.test |
| 1383 | import difflib |
| 1384 | |
| 1385 | if not isinstance(actual, str): |
| 1386 | raise AssertionError(repr(type(actual))) |
| 1387 | if not isinstance(desired, str): |
| 1388 | raise AssertionError(repr(type(desired))) |
| 1389 | if desired == actual: |
| 1390 | return |
| 1391 | |
| 1392 | diff = list(difflib.Differ().compare(actual.splitlines(True), |
| 1393 | desired.splitlines(True))) |
| 1394 | diff_list = [] |
| 1395 | while diff: |
| 1396 | d1 = diff.pop(0) |
| 1397 | if d1.startswith(' '): |
| 1398 | continue |
| 1399 | if d1.startswith('- '): |
| 1400 | l = [d1] |
| 1401 | d2 = diff.pop(0) |
| 1402 | if d2.startswith('? '): |
| 1403 | l.append(d2) |
| 1404 | d2 = diff.pop(0) |
| 1405 | if not d2.startswith('+ '): |
| 1406 | raise AssertionError(repr(d2)) |
| 1407 | l.append(d2) |
| 1408 | if diff: |
| 1409 | d3 = diff.pop(0) |
| 1410 | if d3.startswith('? '): |
| 1411 | l.append(d3) |
| 1412 | else: |
searching dependent graphs…