1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
|
# Examples
Here are some common testing patterns where testbook can help.
## Mocking requests library
**Notebook:**

**Test:**
```python
from testbook import testbook
@testbook('/path/to/notebook.ipynb', execute=True)
def test_get_details(tb):
with tb.patch('requests.get') as mock_get:
get_details = tb.get('get_details') # get reference to function
get_details('https://my-api.com')
mock_get.assert_called_with('https://my-api.com')
```
## Asserting dataframe manipulations
**Notebook:**

**Test:**
```python
from testbook import testbook
@testbook('/path/to/notebook.ipynb')
def test_dataframe_manipulation(tb):
tb.execute_cell('imports')
# Inject a dataframe with code
tb.inject(
"""
df = pandas.DataFrame([[1, None, 3], [4, 5, 6]], columns=['a', 'b', 'c'], dtype='float')
"""
)
# Perform manipulation
tb.execute_cell('manipulation')
# Inject assertion into notebook
tb.inject("assert len(df) == 1")
```
## Asserting STDOUT of a cell
**Notebook:**

**Test:**
```python
from testbook import testbook
@testbook('stdout.ipynb', execute=True)
def test_stdout(tb):
assert tb.cell_output_text(1) == 'hello world!'
assert 'The current time is' in tb.cell_output_text(2)
```
|