spaCy/spacy/tests
Raphael Mitsch 304b9331e6
Modify EL batching to doc-wise streaming approach (#12367)
* Convert Candidate from Cython to Python class.

* Format.

* Fix .entity_ typo in _add_activations() usage.

* Change type for mentions to look up entity candidates for to SpanGroup from Iterable[Span].

* Update docs.

* Update spacy/kb/candidate.py

Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>

* Update doc string of BaseCandidate.__init__().

* Update spacy/kb/candidate.py

Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>

* Rename Candidate to InMemoryCandidate, BaseCandidate to Candidate.

* Adjust Candidate to support and mandate numerical entity IDs.

* Format.

* Fix docstring and docs.

* Update website/docs/api/kb.mdx

Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>

* Rename alias -> mention.

* Refactor Candidate attribute names. Update docs and tests accordingly.

* Refacor Candidate attributes and their usage.

* Format.

* Fix mypy error.

* Update error code in line with v4 convention.

* Modify EL batching system.

* Update leftover get_candidates() mention in docs.

* Format docs.

* Format.

* Update spacy/kb/candidate.py

Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>

* Updated error code.

* Simplify interface for int/str representations.

* Update website/docs/api/kb.mdx

Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>

* Rename 'alias' to 'mention'.

* Port Candidate and InMemoryCandidate to Cython.

* Remove redundant entry in setup.py.

* Add abstract class check.

* Drop storing mention.

* Update spacy/kb/candidate.pxd

Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>

* Fix entity_id refactoring problems in docstrings.

* Drop unused InMemoryCandidate._entity_hash.

* Update docstrings.

* Move attributes out of Candidate.

* Partially fix alias/mention terminology usage. Convert Candidate to interface.

* Remove prior_prob from supported properties in Candidate. Introduce KnowledgeBase.supports_prior_probs().

* Update docstrings related to prior_prob.

* Update alias/mention usage in doc(strings).

* Update spacy/ml/models/entity_linker.py

Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>

* Update spacy/ml/models/entity_linker.py

Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>

* Mention -> alias renaming. Drop Candidate.mentions(). Drop InMemoryLookupKB.get_alias_candidates() from docs.

* Update docstrings.

* Fix InMemoryCandidate attribute names.

* Update spacy/kb/kb.pyx

Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>

* Update spacy/ml/models/entity_linker.py

Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>

* Update W401 test.

* Update spacy/errors.py

Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>

* Update spacy/kb/kb.pyx

Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>

* Use Candidate output type for toy generators in the test suite to mimick best practices

* fix docs

* fix import

* Fix merge leftovers.

* Update spacy/kb/kb.pyx

Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>

* Update spacy/kb/kb.pyx

Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>

* Update website/docs/api/kb.mdx

Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>

* Update website/docs/api/entitylinker.mdx

Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>

* Update spacy/kb/kb_in_memory.pyx

Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>

* Update website/docs/api/inmemorylookupkb.mdx

Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>

* Update get_candidates() docstring.

* Reformat imports in entity_linker.py.

* Drop valid_ent_idx_per_doc.

* Update docs.

* Format.

* Simplify doc loop in predict().

* Remove E1044 comment.

* Fix merge errors.

* Format.

* Format.

* Format.

* Fix merge error & tests.

* Format.

* Apply suggestions from code review

Co-authored-by: Madeesh Kannan <shadeMe@users.noreply.github.com>

* Use type alias.

* isort.

* isort.

* Lint.

* Add typedefs.pyx.

* Fix typedef import.

* Fix type aliases.

* Format.

* Update docstring and type usage.

* Add info on get_candidates(), get_candidates_batched().

* Readd get_candidates info to v3 changelog.

* Update website/docs/api/entitylinker.mdx

Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>

* Update factory functions for backwards compatibility.

* Format.

* Ignore mypy error.

* Fix mypy error.

* Format.

* Add test for multiple docs with multiple entities.

---------

Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>
Co-authored-by: Madeesh Kannan <shadeMe@users.noreply.github.com>
Co-authored-by: svlandeg <svlandeg@github.com>
2024-04-09 11:39:18 +02:00
..
doc Merge remote-tracking branch 'upstream/master' into maintenance/v4-merge-master-20240119 2024-01-19 12:34:29 +01:00
lang Merge remote-tracking branch 'upstream/master' into maintenance/v4-merge-master-20240119 2024-01-19 12:34:29 +01:00
matcher Merge remote-tracking branch 'upstream/master' into maintenance/v4-merge-master-20240119 2024-01-19 12:34:29 +01:00
morphology isort all the things 2023-06-26 11:41:03 +02:00
package Fix up requirements test 2024-01-24 17:18:49 +01:00
parser Py_UNICODE is not compatible with 3.12 2024-01-24 13:08:56 +01:00
pipeline Modify EL batching to doc-wise streaming approach (#12367) 2024-04-09 11:39:18 +02:00
serialize Merge pull request #13299 from danieldk/copy/master 2024-02-04 15:40:55 +01:00
tokenizer Merge remote-tracking branch 'upstream/master' into maintenance/v4-merge-master-20240119 2024-01-19 12:34:29 +01:00
training Merge remote-tracking branch 'upstream/master' into maintenance/v4-merge-master-20240119 2024-01-19 12:34:29 +01:00
vocab_vectors Merge branch 'upstream_master' into sync_v4 2023-07-19 16:37:31 +02:00
__init__.py Revert #4334 2019-09-29 17:32:12 +02:00
conftest.py Merge remote-tracking branch 'upstream/master' into maintenance/v4-merge-master-20240119 2024-01-19 12:34:29 +01:00
enable_gpu.py Set up GPU CI testing (#7293) 2021-04-22 14:58:29 +02:00
README.md Rename language codes (Icelandic, multi-language) (#12149) 2023-01-31 17:30:43 +01:00
test_architectures.py isort all the things 2023-06-26 11:41:03 +02:00
test_cli_app.py Merge remote-tracking branch 'upstream/master' into maintenance/v4-merge-master-20240119 2024-01-19 12:34:29 +01:00
test_cli.py Temporily xfail local remote storage test 2024-01-17 10:20:40 +01:00
test_displacy.py Fix displacy span stacking (#13068) 2023-11-02 12:02:18 +01:00
test_errors.py use metaclass to decorate errors (#9593) 2021-11-03 15:29:32 +01:00
test_language.py isort all the things 2023-06-26 11:41:03 +02:00
test_misc.py test_find_available_port: use port 5001 (#13255) 2024-01-23 20:11:16 +01:00
test_models.py Add TextCatReduce.v1 (#13181) 2023-12-21 11:00:06 +01:00
test_pickles.py isort all the things 2023-06-26 11:41:03 +02:00
test_scorer.py isort all the things 2023-06-26 11:41:03 +02:00
test_symbols.py isort all the things 2023-06-26 11:41:03 +02:00
test_ty.py Custom component types in spacy.ty (#9469) 2021-10-21 15:31:06 +02:00
util.py isort all the things 2023-06-26 11:41:03 +02:00

spaCy tests

spaCy uses the pytest framework for testing. For more info on this, see the pytest documentation.

Tests for spaCy modules and classes live in their own directories of the same name. For example, tests for the Tokenizer can be found in /tests/tokenizer. All test modules (i.e. directories) also need to be listed in spaCy's setup.py. To be interpreted and run, all test files and test functions need to be prefixed with test_.

⚠️ Important note: As part of our new model training infrastructure, we've moved all model tests to the spacy-models repository. This allows us to test the models separately from the core library functionality.

Table of contents

  1. Running the tests
  2. Dos and don'ts
  3. Parameters
  4. Fixtures
  5. Helpers and utilities
  6. Contributing to the tests

Running the tests

To show print statements, run the tests with py.test -s. To abort after the first failure, run them with py.test -x.

py.test spacy                        # run basic tests
py.test spacy --slow                 # run basic and slow tests

You can also run tests in a specific file or directory, or even only one specific test:

py.test spacy/tests/tokenizer  # run all tests in directory
py.test spacy/tests/tokenizer/test_exceptions.py # run all tests in file
py.test spacy/tests/tokenizer/test_exceptions.py::test_tokenizer_handles_emoji # run specific test

Dos and don'ts

To keep the behavior of the tests consistent and predictable, we try to follow a few basic conventions:

  • Test names should follow a pattern of test_[module]_[tested behaviour]. For example: test_tokenizer_keeps_email.
  • If you're testing for a bug reported in a specific issue, always create a regression test. Regression tests should be named test_issue[ISSUE NUMBER] and live in the regression directory.
  • Only use @pytest.mark.xfail for tests that should pass, but currently fail. To test for desired negative behavior, use assert not in your test.
  • Very extensive tests that take a long time to run should be marked with @pytest.mark.slow. If your slow test is testing important behavior, consider adding an additional simpler version.
  • If tests require loading the models, they should be added to the spacy-models tests.
  • Before requiring the models, always make sure there is no other way to test the particular behavior. In a lot of cases, it's sufficient to simply create a Doc object manually. See the section on helpers and utility functions for more info on this.
  • Avoid unnecessary imports. There should never be a need to explicitly import spaCy at the top of a file, and many components are available as fixtures. You should also avoid wildcard imports (from module import *).
  • If you're importing from spaCy, always use absolute imports. For example: from spacy.language import Language.
  • Try to keep the tests readable and concise. Use clear and descriptive variable names (doc, tokens and text are great), keep it short and only test for one behavior at a time.

Parameters

If the test cases can be extracted from the test, always parametrize them instead of hard-coding them into the test:

@pytest.mark.parametrize('text', ["google.com", "spacy.io"])
def test_tokenizer_keep_urls(tokenizer, text):
    tokens = tokenizer(text)
    assert len(tokens) == 1

This will run the test once for each text value. Even if you're only testing one example, it's usually best to specify it as a parameter. This will later make it easier for others to quickly add additional test cases without having to modify the test.

You can also specify parameters as tuples to test with multiple values per test:

@pytest.mark.parametrize('text,length', [("U.S.", 1), ("us.", 2), ("(U.S.", 2)])

To test for combinations of parameters, you can add several parametrize markers:

@pytest.mark.parametrize('text', ["A test sentence", "Another sentence"])
@pytest.mark.parametrize('punct', ['.', '!', '?'])

This will run the test with all combinations of the two parameters text and punct. Use this feature sparingly, though, as it can easily cause unnecessary or undesired test bloat.

Fixtures

Fixtures to create instances of spaCy objects and other components should only be defined once in the global conftest.py. We avoid having per-directory conftest files, as this can easily lead to confusion.

These are the main fixtures that are currently available:

Fixture Description
tokenizer Basic, language-independent tokenizer. Identical to the mul language class.
en_tokenizer, de_tokenizer, ... Creates an English, German etc. tokenizer.
en_vocab Creates an instance of the English Vocab.

The fixtures can be used in all tests by simply setting them as an argument, like this:

def test_module_do_something(en_tokenizer):
    tokens = en_tokenizer("Some text here")

If all tests in a file require a specific configuration, or use the same complex example, it can be helpful to create a separate fixture. This fixture should be added at the top of each file. Make sure to use descriptive names for these fixtures and don't override any of the global fixtures listed above. From looking at a test, it should immediately be clear which fixtures are used, and where they are coming from.

Helpers and utilities

Our new test setup comes with a few handy utility functions that can be imported from util.py.

Constructing a Doc object manually

Loading the models is expensive and not necessary if you're not actually testing the model performance. If all you need is a Doc object with annotations like heads, POS tags or the dependency parse, you can construct it manually.

def test_doc_token_api_strings(en_vocab):
    words = ["Give", "it", "back", "!", "He", "pleaded", "."]
    pos = ['VERB', 'PRON', 'PART', 'PUNCT', 'PRON', 'VERB', 'PUNCT']
    heads = [0, 0, 0, 0, 5, 5, 5]
    deps = ['ROOT', 'dobj', 'prt', 'punct', 'nsubj', 'ROOT', 'punct']

    doc = Doc(en_vocab, words=words, pos=pos, heads=heads, deps=deps)
    assert doc[0].text == 'Give'
    assert doc[0].lower_ == 'give'
    assert doc[0].pos_ == 'VERB'
    assert doc[0].dep_ == 'ROOT'

Other utilities

Name Description
apply_transition_sequence(parser, doc, sequence) Perform a series of pre-specified transitions, to put the parser in a desired state.
add_vecs_to_vocab(vocab, vectors) Add list of vector tuples ([("text", [1, 2, 3])]) to given vocab. All vectors need to have the same length.
get_cosine(vec1, vec2) Get cosine for two given vectors.
assert_docs_equal(doc1, doc2) Compare two Doc objects and assert that they're equal. Tests for tokens, tags, dependencies and entities.

Contributing to the tests

There's still a long way to go to finally reach 100% test coverage and we'd appreciate your help! 🙌 You can open an issue on our issue tracker and label it tests, or make a pull request to this repository.

📖 For more information on contributing to spaCy in general, check out our contribution guidelines.