microsoft/qdk
Publicmirrored fromhttps://github.com/microsoft/qdkAvailable
samples/testing/classical_values/test_classical_values.py
42lines · modecode
| 1 | from pathlib import Path |
| 2 | from random import randint |
| 3 | import pytest |
| 4 | import qsharp |
| 5 | |
| 6 | |
| 7 | @pytest.fixture(autouse=True) |
| 8 | def setup(): |
| 9 | """Fixture to execute before a test is run""" |
| 10 | # Setting the project root to current folder. |
| 11 | this_dir = Path(__file__).parent |
| 12 | qsharp.init(project_root=this_dir) |
| 13 | yield # this is where the testing happens |
| 14 | |
| 15 | |
| 16 | def test_classical_computation() -> None: |
| 17 | """Test that Q# code computes f(x) = x^2 correctly using Python test code.""" |
| 18 | for x in range(-10, 11): |
| 19 | res = qsharp.eval(f"ClassicalFunction.Square({x})") |
| 20 | assert res == x**2 |
| 21 | |
| 22 | |
| 23 | def test_classical_computation_qsharp() -> None: |
| 24 | """Test that Q# code computes f(x) = x^2 correctly using Q# test code.""" |
| 25 | qsharp.eval("TestCode.TestSquare()") |
| 26 | |
| 27 | |
| 28 | def test_measurement_results() -> None: |
| 29 | """Test that measuring a basis state returns correct measurement results using Python test code.""" |
| 30 | for _ in range(10): |
| 31 | n = randint(2, 10) |
| 32 | bits = [bool(randint(0, 1)) for _ in range(n)] |
| 33 | # When passing Boolean values to Q#, remember to convert them to lowercase |
| 34 | # (Python uses True and False, while Q# uses true and false) |
| 35 | res = qsharp.eval(f"Measurement.MeasureBasisState({str(bits).lower()})") |
| 36 | for i in range(n): |
| 37 | assert (res[i] == qsharp.Result.One) == bits[i] |
| 38 | |
| 39 | |
| 40 | def test_measurement_results_qsharp() -> None: |
| 41 | """Test that measuring a basis state returns correct measurement results using Q# test code.""" |
| 42 | qsharp.eval("TestCode.TestMeasurement()") |
| 43 | |