<commit_before>/*
 * Copyright 2016 the original author or authors.
 *
 * 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.
 */

package org.gradle.api.tasks

import org.gradle.api.logging.configuration.ShowStacktrace
import org.gradle.caching.internal.controller.DefaultBuildCacheController
import org.gradle.integtests.fixtures.AbstractIntegrationSpec
import org.gradle.integtests.fixtures.DirectoryBuildCacheFixture
import org.gradle.integtests.fixtures.ToBeFixedForInstantExecution
import org.gradle.test.fixtures.file.TestFile
import spock.lang.Unroll

class CachedTaskExecutionErrorHandlingIntegrationTest extends AbstractIntegrationSpec implements DirectoryBuildCacheFixture {

    def setup() {
        settingsFile << """
            class FailingBuildCache extends AbstractBuildCache {
                String shouldFail
            }
            
            class FailingBuildCacheServiceFactory implements BuildCacheServiceFactory<FailingBuildCache> {
                FailingBuildCacheService createBuildCacheService(FailingBuildCache configuration, Describer describer) {
                    return new FailingBuildCacheService(configuration.shouldFail)
                }
            }
            
            class FailingBuildCacheService implements BuildCacheService {
                String shouldFail
                
                FailingBuildCacheService(String shouldFail) {
                    this.shouldFail = shouldFail
                }
                
                @Override
                boolean load(BuildCacheKey key, BuildCacheEntryReader reader) throws BuildCacheException {
                    println "> Attempting load for \$key"
                    if (shouldFail == "load") {
                        shouldFail = null
                        throw new BuildCacheException("Unable to read " + key)
                    } else {
                        return false
                    }
                }
    
                @Override
                void store(BuildCacheKey key, BuildCacheEntryWriter writer) throws BuildCacheException {
                    println "> Attempting store for \$key"
                    if (shouldFail == "store") {
                        shouldFail = null
                        throw new BuildCacheException("Unable to write " + key)
                    }
                }
    
                @Override
                void close() throws IOException {
                }
            }
            
            buildCache {
                registerBuildCacheService(FailingBuildCache, FailingBuildCacheServiceFactory)
                
                local {
                    enabled = false
                }
                
                remote(FailingBuildCache) {
                    shouldFail = gradle.startParameter.systemPropertiesArgs.get("failOn")
                    push = true
                }
            }
        """

        executer.beforeExecute {
            executer.withBuildCacheEnabled()
        }
    }

    @Unroll
    def "remote cache #failEvent error stack trace is printed when requested (#showStacktrace)"() {
        // Need to do it like this because stacktraces are always enabled for integration tests
        settingsFile << """
            gradle.startParameter.setShowStacktrace(org.gradle.api.logging.configuration.ShowStacktrace.$showStacktrace)
        """

        buildFile << """
            task customTask {
                outputs.cacheIf { true }
                outputs.file("build/output.txt")
                doLast {
                    file("build/output.txt").text = "Done"
                }
            }
        """

        if (expectStacktrace) {
            executer.withStackTraceChecksDisabled()
        }

        when:
        succeeds "customTask", "-DfailOn=$failEvent"
        then:
        output.count("> Attempting $failEvent") == 1
        output.count("Could not $failEvent entry") == 1
        output.count("The remote build cache was disabled during the build due to errors.") == 1
        if (expectStacktrace) {
            assert stackTraceContains(DefaultBuildCacheController)
        }

        where:
        failEvent | showStacktrace                     | expectStacktrace
        "load"    | ShowStacktrace.INTERNAL_EXCEPTIONS | false
        "load"    | ShowStacktrace.ALWAYS              | true
        "load"    | ShowStacktrace.ALWAYS_FULL         | true
        "store"   | ShowStacktrace.INTERNAL_EXCEPTIONS | false
        "store"   | ShowStacktrace.ALWAYS              | true
        "store"   | ShowStacktrace.ALWAYS_FULL         | true
    }

    @Unroll
    @ToBeFixedForInstantExecution
    def "remote cache is disabled after first #failEvent error for the current build"() {
        // Need to do it like this because stacktraces are always enabled for integration tests
        settingsFile << """
            gradle.startParameter.setShowStacktrace(org.gradle.api.logging.configuration.ShowStacktrace.INTERNAL_EXCEPTIONS)
        """

        buildFile << """
            task firstTask {
                outputs.cacheIf { true }
                outputs.file("build/first.txt")
                doLast {
                    file("build/first.txt").text = "Done"
                }
            }

            task secondTask {
                dependsOn firstTask
                outputs.cacheIf { true }
                outputs.file("build/second.txt")
                doLast {
                    file("build/second.txt").text = "Done"
                }
            }
        """

        executer.withStackTraceChecksDisabled()

        when:
        succeeds "secondTask", "-DfailOn=$failEvent"
        then:
        attemptsBeforeFailure.each { event, count ->
            assert output.count("> Attempting $failEvent") == count
        }
        output.count("Could not $failEvent entry") == 1
        output.count("The remote build cache was disabled during the build due to errors.") == 1<commit_msg>Document ToBeFixed cause in CachedTaskExecutionErrorHandlingIntegrationTest<commit_after>/*
 * Copyright 2016 the original author or authors.
 *
 * 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.
 */

package org.gradle.api.tasks

import org.gradle.api.logging.configuration.ShowStacktrace
import org.gradle.caching.internal.controller.DefaultBuildCacheController
import org.gradle.integtests.fixtures.AbstractIntegrationSpec
import org.gradle.integtests.fixtures.DirectoryBuildCacheFixture
import org.gradle.integtests.fixtures.ToBeFixedForInstantExecution
import org.gradle.test.fixtures.file.TestFile
import spock.lang.Unroll

class CachedTaskExecutionErrorHandlingIntegrationTest extends AbstractIntegrationSpec implements DirectoryBuildCacheFixture {

    def setup() {
        settingsFile << """
            class FailingBuildCache extends AbstractBuildCache {
                String shouldFail
            }
            
            class FailingBuildCacheServiceFactory implements BuildCacheServiceFactory<FailingBuildCache> {
                FailingBuildCacheService createBuildCacheService(FailingBuildCache configuration, Describer describer) {
                    return new FailingBuildCacheService(configuration.shouldFail)
                }
            }
            
            class FailingBuildCacheService implements BuildCacheService {
                String shouldFail
                
                FailingBuildCacheService(String shouldFail) {
                    this.shouldFail = shouldFail
                }
                
                @Override
                boolean load(BuildCacheKey key, BuildCacheEntryReader reader) throws BuildCacheException {
                    println "> Attempting load for \$key"
                    if (shouldFail == "load") {
                        shouldFail = null
                        throw new BuildCacheException("Unable to read " + key)
                    } else {
                        return false
                    }
                }
    
                @Override
                void store(BuildCacheKey key, BuildCacheEntryWriter writer) throws BuildCacheException {
                    println "> Attempting store for \$key"
                    if (shouldFail == "store") {
                        shouldFail = null
                        throw new BuildCacheException("Unable to write " + key)
                    }
                }
    
                @Override
                void close() throws IOException {
                }
            }
            
            buildCache {
                registerBuildCacheService(FailingBuildCache, FailingBuildCacheServiceFactory)
                
                local {
                    enabled = false
                }
                
                remote(FailingBuildCache) {
                    shouldFail = gradle.startParameter.systemPropertiesArgs.get("failOn")
                    push = true
                }
            }
        """

        executer.beforeExecute {
            executer.withBuildCacheEnabled()
        }
    }

    @Unroll
    def "remote cache #failEvent error stack trace is printed when requested (#showStacktrace)"() {
        // Need to do it like this because stacktraces are always enabled for integration tests
        settingsFile << """
            gradle.startParameter.setShowStacktrace(org.gradle.api.logging.configuration.ShowStacktrace.$showStacktrace)
        """

        buildFile << """
            task customTask {
                outputs.cacheIf { true }
                outputs.file("build/output.txt")
                doLast {
                    file("build/output.txt").text = "Done"
                }
            }
        """

        if (expectStacktrace) {
            executer.withStackTraceChecksDisabled()
        }

        when:
        succeeds "customTask", "-DfailOn=$failEvent"
        then:
        output.count("> Attempting $failEvent") == 1
        output.count("Could not $failEvent entry") == 1
        output.count("The remote build cache was disabled during the build due to errors.") == 1
        if (expectStacktrace) {
            assert stackTraceContains(DefaultBuildCacheController)
        }

        where:
        failEvent | showStacktrace                     | expectStacktrace
        "load"    | ShowStacktrace.INTERNAL_EXCEPTIONS | false
        "load"    | ShowStacktrace.ALWAYS              | true
        "load"    | ShowStacktrace.ALWAYS_FULL         | true
        "store"   | ShowStacktrace.INTERNAL_EXCEPTIONS | false
        "store"   | ShowStacktrace.ALWAYS              | true
        "store"   | ShowStacktrace.ALWAYS_FULL         | true
    }

    @Unroll
    @ToBeFixedForInstantExecution(because = "FailingBuildCache has not been registered.")
    def "remote cache is disabled after first #failEvent error for the current build"() {
        // Need to do it like this because stacktraces are always enabled for integration tests
        settingsFile << """
            gradle.startParameter.setShowStacktrace(org.gradle.api.logging.configuration.ShowStacktrace.INTERNAL_EXCEPTIONS)
        """

        buildFile << """
            task firstTask {
                outputs.cacheIf { true }
                def outTxt = file("build/first.txt")
                outputs.file(outTxt)
                doLast {
                    outTxt.text = "Done"
                }
            }

            task secondTask {
                dependsOn firstTask
                outputs.cacheIf { true }
                def outTxt = file("build/second.txt")
                outputs.file(outTxt)
                doLast {
                    outTxt.text = "Done"
                }
            }
        """

        executer.withStackTraceChecksDisabled()

        when:
        succeeds "secondTask", "-DfailOn=$failEvent"
        then:
        attemptsBeforeFailure.each { event, count ->
            assert output.count("> Attempting $failEvent") == count
        }
        output.count("Could not $failEvent entry") == 1
        output.count("The remote build cache was disabled during the build due to errors.") == 1
{'fraction_non_alphanumeric': 0.07130368681109844, 'fraction_numerical': 0.001976434815659445, 'mean_word_length': 1.7170590665014456, 'pattern_counts': {'":': 0, '<': 25, '<?xml version=': 0, '>': 15, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6993452', 'n_tokens_mistral': 3171, 'n_tokens_neox': 2956, 'n_words': 782}