示例工程 33-numpy-vectorization

33-numpy-vectorization/03-view-vs-copy/test_view_vs_copy.py

python · 0.7 KB

"""test_view_vs_copy.py"""
 
from __future__ import annotations
 
import pytest
 
pytest.importorskip("numpy")
 
import numpy as np
from view_vs_copy import main
 
 
def test_slice_is_view() -> None:
    arr = np.arange(5)
    view = arr[1:3]
    view[0] = 99
    assert arr.tolist() == [0, 99, 2, 3, 4]
    assert np.shares_memory(view, arr)
 
 
def test_copy_is_independent() -> None:
    arr = np.arange(5)
    copied = arr[1:3].copy()
    copied[0] = 99
    assert arr.tolist() == [0, 1, 2, 3, 4]
    assert not np.shares_memory(copied, arr)
 
 
def test_main_runs(capsys: pytest.CaptureFixture[str]) -> None:
    main()
    out = capsys.readouterr().out
    assert "view shares: True" in out
    assert "copy shares: False" in out