# Copyright (c) Facebook, Inc. and its affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from xplat.build_infra.buck_api.buck_repo import BuckRepo
from xplat.build_infra.buck_e2e import asserts
from xplat.build_infra.buck_e2e.repo_workspace import buck_test, exec_path


# TODO: Add decorator to run this with and without buckd
@buck_test(data="testdata/cxx")
async def test_should_build_and_run_successfully(repo: BuckRepo):
    result = await repo.build(
        "//simple_successful_helloworld:simple_successful_helloworld", "--show-output"
    ).wait()
    asserts.success(result)

    target_to_build_output = result.get_target_to_build_output()
    assert len(target_to_build_output) == 1

    build_output = next(iter(target_to_build_output.values()))
    process = await exec_path(repo.cwd / build_output)
    assert process.returncode == 0


@buck_test(data="testdata/cxx")
async def test_successful_env_empty_file(repo: BuckRepo):
    result = await repo.build(
        "//simple_parse_error_helloworld:simple_parse_error_helloworld"
    ).wait()
    asserts.parse_error(result)


@buck_test(data="testdata/cxx")
async def test_should_not_build_successfully(repo: BuckRepo):
    result = await repo.build(
        "//simple_failed_helloworld:simple_failed_helloworld"
    ).wait()
    asserts.failure(result, f"Should fail to compile: {result.stdout}")

@@ -680,16 +680,24 @@
 buck_e2e
+.asserts
  import 
@@ -702,17 +702,44 @@
 t assert
-s
+_parse_error, expect_failure
 %0Afrom xp
@@ -785,16 +785,22 @@
  import 
+(%0A    
 buck_tes
@@ -801,16 +801,20 @@
 ck_test,
+%0A   
  exec_pa
@@ -815,16 +815,19 @@
 xec_path
+,%0A)
 %0A%0A%0A# TOD
@@ -1110,36 +1110,8 @@
 it()
-%0A    asserts.success(result)
 %0A%0A  
@@ -1471,43 +1471,65 @@
     
-result = await repo.build(%0A        
+build_failure = await expect_failure(%0A        repo.build(
 %22//s
@@ -1583,37 +1583,31 @@
 _helloworld%22
+)
 %0A    )
-.wait()
 %0A    asserts
@@ -1605,18 +1605,17 @@
   assert
-s.
+_
 parse_er
@@ -1618,22 +1618,29 @@
 e_error(
-result
+build_failure
 )%0A%0A%0A@buc
@@ -1737,43 +1737,49 @@
     
-result = await repo.build(%0A        
+await expect_failure(%0A        repo.build(
 %22//s
@@ -1831,90 +1831,12 @@
 rld%22
+)
 %0A    
-).wait()%0A    asserts.failure(result, f%22Should fail to compile: %7Bresult.stdout%7D%22
 )%0A

Change command failures to raise Exceptions