|
| 1 | +@eval module $(gensym()) |
| 2 | +using NDTensors: NDTensors |
| 3 | +using Test: @test, @test_throws, @testset |
| 4 | + |
| 5 | +@testset "NDTensors.with_auto_fermion" begin |
| 6 | + @testset "starting state $start" for start in (false, true) |
| 7 | + start ? NDTensors.enable_auto_fermion() : NDTensors.disable_auto_fermion() |
| 8 | + @test NDTensors.using_auto_fermion() == start |
| 9 | + |
| 10 | + @testset "default enables auto-fermion" begin |
| 11 | + inside = Ref(false) |
| 12 | + NDTensors.with_auto_fermion() do |
| 13 | + return inside[] = NDTensors.using_auto_fermion() |
| 14 | + end |
| 15 | + @test inside[] == true |
| 16 | + @test NDTensors.using_auto_fermion() == start |
| 17 | + end |
| 18 | + |
| 19 | + @testset "explicit enable=false disables auto-fermion" begin |
| 20 | + inside = Ref(true) |
| 21 | + NDTensors.with_auto_fermion(false) do |
| 22 | + return inside[] = NDTensors.using_auto_fermion() |
| 23 | + end |
| 24 | + @test inside[] == false |
| 25 | + @test NDTensors.using_auto_fermion() == start |
| 26 | + end |
| 27 | + |
| 28 | + @testset "return value is propagated" begin |
| 29 | + @test NDTensors.with_auto_fermion(() -> 42) == 42 |
| 30 | + @test NDTensors.with_auto_fermion(() -> 42, false) == 42 |
| 31 | + @test NDTensors.using_auto_fermion() == start |
| 32 | + end |
| 33 | + |
| 34 | + @testset "restores previous state after exception" begin |
| 35 | + @test_throws ErrorException NDTensors.with_auto_fermion() do |
| 36 | + return error("boom") |
| 37 | + end |
| 38 | + @test NDTensors.using_auto_fermion() == start |
| 39 | + @test_throws ErrorException NDTensors.with_auto_fermion(false) do |
| 40 | + return error("boom") |
| 41 | + end |
| 42 | + @test NDTensors.using_auto_fermion() == start |
| 43 | + end |
| 44 | + |
| 45 | + @testset "nested scopes" begin |
| 46 | + inner_state = Ref{Bool}(start) |
| 47 | + NDTensors.with_auto_fermion(true) do |
| 48 | + @test NDTensors.using_auto_fermion() == true |
| 49 | + NDTensors.with_auto_fermion(false) do |
| 50 | + return inner_state[] = NDTensors.using_auto_fermion() |
| 51 | + end |
| 52 | + @test NDTensors.using_auto_fermion() == true |
| 53 | + end |
| 54 | + @test inner_state[] == false |
| 55 | + @test NDTensors.using_auto_fermion() == start |
| 56 | + end |
| 57 | + |
| 58 | + @testset "nested scope restores after inner exception" begin |
| 59 | + NDTensors.with_auto_fermion(true) do |
| 60 | + @test NDTensors.using_auto_fermion() == true |
| 61 | + @test_throws ErrorException NDTensors.with_auto_fermion(false) do |
| 62 | + return error("boom") |
| 63 | + end |
| 64 | + @test NDTensors.using_auto_fermion() == true |
| 65 | + end |
| 66 | + @test NDTensors.using_auto_fermion() == start |
| 67 | + end |
| 68 | + end |
| 69 | + |
| 70 | + # Leave the auto-fermion state as we found it for the rest of the suite. |
| 71 | + NDTensors.disable_auto_fermion() |
| 72 | +end |
| 73 | +end |
0 commit comments