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