I'm setting up a very basic build pipeline in Azure Pipelines that simply builds the solution and runs all unit tests every time a commit is made to the target branch. My application code is using preprocessor directives to check for an environment variable that I'm setting as part of the build pipeline, but so far I don't seem to be doing that correctly. The section of code that should be excluded in the pipeline is always being run.
I created a very simple unit test to troubleshoot this:
[Fact]
public void PipelineTest()
{
#if AZURE_PIPELINE
// Return immediately when in the pipeline
return;
#endif
// Intentionally fail when not in the pipeline
true.Should().BeFalse();
}
My pipeline's YML file is about as simple as it gets:
trigger:
- develop
pool:
vmImage: 'windows-latest'
variables:
solution: '**/*.sln'
buildPlatform: 'Any CPU'
buildConfiguration: 'Release'
workspace:
clean: 'all'
steps:
# Restore and Build the solution
- task: DotNetCoreCLI@2
displayName: 'Build Solution'
inputs:
command: 'build'
projects: '$(solution)'
arguments: '/m'
# Run unit tests
- task: DotNetCoreCLI@2
displayName: 'Run Unit Tests'
inputs:
command: 'test'
projects: '$(solution)'
I've tried a few different ways to set the AZURE_PIPELINE
variable in the pipeline configuration, but each time the pipeline is run the test fails. My understanding is that the preprocessor directive should ensure the return
at the top gets compiled into the test, which should allow it to pass.
I've tried adding that in as an argument to the build task:
- task: DotNetCoreCLI@2
displayName: 'Build Solution'
inputs:
command: 'build'
projects: '$(solution)'
arguments: '/m /p:DefineConstants=AZURE_PIPELINE'
I've also tried specifying the environment variable directly in the task. Another post mentioned that environment variables have to be set to the task in which they're being referenced, so I tried setting that explicitly to both my build and test tasks:
- task: DotNetCoreCLI@2
displayName: 'Build Solution'
env:
AZURE_PIPELINE: true
inputs:
command: 'build'
projects: '$(solution)'
arguments: '/m'
- task: DotNetCoreCLI@2
displayName: 'Run Unit Tests'
env:
AZURE_PIPELINE: true
inputs:
command: 'test'
projects: '$(solution)'
Regardless of what I've tried, that test always fails in the pipeline:
What am I missing? Am I misunderstanding how this should work, either the preprocessor directive or my pipeline's variable configuration?