Run Python test with Azure DevOps pipeline

The beauty of Azure DevOps is it support to many technologies and all of major language.s I have a simple git repository where I’m experimenting Python code, in that repository I have several directories like 020_xxxx 010_yyy where I’m playing with Python code.

Each folder contains some code and some unit tests written in Pytest, my goal is creating an Azure Pipeline that can automatically run all pytest for me automatically each time I push some code to the repository.

Even if Phyton is a script languages, it has several Unit Testing frameworks that can be used to verify that the code you wrote works as expected

Creating a build in Azure DevOps is really simple, just create a build that points to a yaml file in your repository that contains the definition.

queue:
  name: Hosted Linux Preview

trigger:
- master
- develop
- features/*
- hotfix/*
- release/*

steps:

- task: UsePythonVersion@0
  displayName: 'Use Python 3.x'

- bash: |
   pip install pytest 
   pip install pytest-cov 
   pip install pytest-xdist 
   pip install pytest-bdd 

  displayName: 'Install a bunch of pip packages.'


- bash: 'pytest --junitxml=$(Build.StagingDirectory)/010.xml' 
  workingDirectory: '010_CrackingCodeBasic'
  displayName: 'Run test 010'

- bash: 'pytest --junitxml=$(Build.StagingDirectory)/020.xml' 
  workingDirectory: '020_CrackingIntermediate'
  displayName: 'Run test 020'

- task: PublishTestResults@2
  displayName: 'Publish test result /010.xml'
  inputs:
    testResultsFiles: '$(Build.StagingDirectory)/010.xml'
    testRunTitle: 010

- task: PublishTestResults@2
  displayName: 'Publish test result /020.xml'
  inputs:
    testResultsFiles: '$(Build.StagingDirectory)/020.xml'
    testRunTitle: 020





This is a real simple yaml buid definition where I’m simply requiring the usage of python 3.x, then install some packages with pip and finally a series of pytest tests run for each folder. As you can see I specified also the trigger to automatically build all branches typical of GitFlow naming convention.

The trick to have the result of the tests published directly in your build result is using a Pytest option to create a result file with JUNIT xml file format; once you have test result as a JUNIT xml files you can use standard PublishTestResults task to publish results in the build.

After the build completed you can simply looks at the output, if everything is ok the build is Green.

image

Figure 1: Test results in my build that shows results of my python unit tests.

The build will run all python tests in all of my source code folder, thanks to Pytest that does everything for you, both discovering and run all tests in the folder.

If code does not compile, unit test will fail and you have a failing build.

image

Figure 2: Not compiling code will lead to a failing build.

The problem with this approach is that the build stops at the very first error, so if an error happens in 010 directory my 020 directory will not be tested because at the very first failed test the execution of the build stopped.

This condition is usually too strict, for unit testing it is usually a better approach to configure the build to continue even if run test failed. To accomplish this, just add continueOnError: true after each bash task used to run tests. With continueOnError equal to true, the build will continue and if some of the test task fails, the build is marked as Partially Failed, and from the summary you can easily check the run that generates the error.

image

Figure 3: Continue on error true will make the build continue on test error, in the summary you can verify what failed,

The reason why I choose to launch a different Pytest run for each folder and upload each result with a different task is to have separate run in build result.

image

Figure 4: Test runs are distinct for each folder.

Even if this will force me to add two task for each folder (one for the run and the other for the publish) this approach will give me a different result for each folder so I can immediately understand where is the error.

Gian Maria.

Analyze your GitHub project for free with Azure DevOps and SonarCloud

I’ve blogged some weeks ago on how to analyze OS code with SonarCloud, but it is time to update the post, because if you want to use SonarCloud you have a dedicated extension in the marketplace.

image 

Figure 1: Official SonarCloud extension in the marketplace.

One of the great feature of Azure DevOps is its extendibility, that allows people external to Microsoft to create extensions to expand the possibility of the tool. Once you’ve added the SonarCloud extension to your account, you have a whole bunch new build templates you can use:

image

Figure 2: Build template based on Sonar Cloud

Having a template make super easy to create a build, you just choose .NET Desktop with SonarCloud and you are ready to go. As you can see in Figure 2 you can also use Azure DevOps pipeline to build with Gradle, maven or .NET core, so you are not confined to microsoft tooling.

In Figure 3 there is the build created by .NET desktop project template (remember that this template can be used also for web application, and for every .NET application).

image

Figure 3: .NET Sonar Cloud analysis template.

The only task you need to configure for Sonar Cloud analysis is the Prepare analysis on Sonar Cloud. As you can see in Figure 4, you should first create an endpoint that connect Azure DevOps to your SonarCloud account.

SNAGHTML1d1ca3

Figure 4: In task configuration you have a nice button to create the connection to your SonarCloud account

Configuring the connection is really simple, just give a name to the connection and specify the access token (you should first generate a token in SonarCloud). Then, as shown in Figure 5, press Verify Connection to check that everything is ok.

image

Figure 5: Configuration and test of the connection between Azure DevOps and SonarCloud.

Thanks to the concept of external services, you can configure one or more connection to SonarCloud and having it available in the build without disclosing tokens.

Once you’ve selected the connection, just specify name and key of the project, and other optional parameters if you need to do a custom analysis. In less than a couple of minutes you have a build up and running. Just configure the agent to use Hosted VS2017 pipeline and queue a first build to verify that everything is ok.

Once you have configured the build with the visual web designer, you can convert to Yaml build with few steps.

Clearly I prefer to have a YAML build for a lot of reasons, once the build is up and running simply press the YAML button in the build definition to have your build converted to YAML.

# .NET Desktop
# Build and run tests for .NET Desktop or Windows classic desktop solutions.
# Add steps that publish symbols, save build artifacts, and more:
# https://docs.microsoft.com/azure/devops/pipelines/apps/windows/dot-net

pool:
  vmImage: 'VS2017-Win2016'

trigger:
- master
- develop
- release/*
- hotfix/*
- feature/*

variables:
  solution: 'migration/MigrationPlayground.sln'
  buildPlatform: 'Any CPU'
  buildConfiguration: 'Release'

steps:

- task: GitVersion@1
  displayName: GitVersion 
  inputs:
    BuildNamePrefix: 'MigrationCI'

- task: SonarSource.sonarcloud.14d9cde6-c1da-4d55-aa01-2965cd301255.SonarCloudPrepare@1
  displayName: 'Prepare analysis on SonarCloud'
  inputs:
    SonarCloud: 'SonarCloud'
    organization: 'alkampfergit-github'
    projectKey: MigrationPlayground
    projectName: MigrationPlayground
    projectVersion: '$(AssemblyVersion)'

- task: NuGetToolInstaller@0

- task: NuGetCommand@2
  inputs:
    restoreSolution: '$(solution)'

- task: VSBuild@1
  inputs:
    solution: '$(solution)'
    platform: '$(buildPlatform)'
    configuration: '$(buildConfiguration)'

- task: VSTest@2
  inputs:
    platform: '$(buildPlatform)'
    configuration: '$(buildConfiguration)'

- task: SonarSource.sonarcloud.ce096e50-6155-4de8-8800-4221aaeed4a1.SonarCloudAnalyze@1
  displayName: 'Run Code Analysis'

- task: SonarSource.sonarcloud.38b27399-a642-40af-bb7d-9971f69712e8.SonarCloudPublish@1
  displayName: 'Publish Quality Gate Result'




Finally, if you still have not installed Azure Devops Pipeline in your GitHub account, I strongly suggest you to do so, just follow the instruction of this article, it is free and gives you free hosted pipelines to run your build for free.

Gian Maria

Azure DevOps pipelines and Sonar Cloud gives free analysis to your OS project

In previous post I’ve shown how easy is to create a YAML definition to create a build definition to build your GitHub Open Source project in Azure DevOps, without the need to spend any money nor installing anything on you server.

Once you create a default build that compile and run tests, it would be super nice to create a free account in SonarCloud to have your project code to be analyzed automatically from the Azure Pipeline you’ve just created. I’ve already blogged on how to setup SonarCloud analysis for OS project with VSTS build and the very same technique can be used in YAML build.

Once you have free YAML Azure DevOps pipeline, it makes sense to enable analysis with SonarCloud

First of all you need to register to SonarCloud, create a project, setup key and create a token to access the account. Once everything is in place you can simply modify YAML build to perform the analysis.

image

Figure 1: Task to start sonar cloud analysis.

The above task definition can be obtained simply creating a build with standard graphical editor, then press the YAML build to have the  UI generate the YAML for the task.

Actually YAML build does not have an editor, but it is super easy to just create a fake build with standard editor, drop a task into the definition, populate properties then let the UI to generate YAML that can be copied into the definition.

Once the analysis task is in place, you can simply place the “Run code analysis task” after build and test tasks. The full code of the build is the following.

# .NET Desktop
# Build and run tests for .NET Desktop or Windows classic desktop solutions.
# Add steps that publish symbols, save build artifacts, and more:
# https://docs.microsoft.com/azure/devops/pipelines/apps/windows/dot-net

pool:
  vmImage: 'VS2017-Win2016'

trigger:
- master
- develop
- release/*
- hotfix/*
- feature/*

variables:
  solution: 'migration/MigrationPlayground.sln'
  buildPlatform: 'Any CPU'
  buildConfiguration: 'Release'

steps:

- task: GitVersion@1
  displayName: GitVersion 
  inputs:
    BuildNamePrefix: 'MigrationCI'

- task: SonarSource.sonarqube.15B84CA1-B62F-4A2A-A403-89B77A063157.SonarQubePrepare@4
  displayName: 'Prepare analysis on SonarQube'
  inputs:
    SonarQube: 'SonarCloud'
    projectKey: xxxxxxxxxxxxxxxxxxx
    projectName: MigrationPlayground
    projectVersion: '$(AssemblyVersion)'
    extraProperties: |
     sonar.organization=alkampfergit-github
     sonar.branch.name=$(Build.SourceBranchName)

- task: NuGetToolInstaller@0

- task: NuGetCommand@2
  inputs:
    restoreSolution: '$(solution)'

- task: VSBuild@1
  inputs:
    solution: '$(solution)'
    platform: '$(buildPlatform)'
    configuration: '$(buildConfiguration)'

- task: VSTest@2
  inputs:
    platform: '$(buildPlatform)'
    configuration: '$(buildConfiguration)'

- task: SonarSource.sonarqube.6D01813A-9589-4B15-8491-8164AEB38055.SonarQubeAnalyze@4
  displayName: 'Run Code Analysis'




Once you changed the build just push the code and let the build run, you should check if the build completes without error, then verify if analysis is present in SonarCloud dashboard.

A couple of suggestion are useful at this point: first of all you can encounter problem with endpoint authorization, if you have such problem check this link. Another issue is that you should analyze master branch for the first analysis for SonarCloud to work properly. Until you do not analyze master branch, no analysis will be shown to SonarCloud.

If everything is green you should start seeing analysis data on SonarCloud UI.

image

Figure 2: Analysis in SonarCloud after a successful master build

As you can see just a few lines of YAML and I have my code automatically analyzed in SonarCloud, thanks to Azure DevOps pipelines that already have tasks related to SonarCube integration.

A nice finishing touch is to grab the badge link for SonarCloud analysis and add it to your github readme.md.

image

Figure 3: SonarCloud badge added to readme.md of the project.

Gian Maria.

Code in GitHub, Build in Azure DevOps and for FREE

When you create a new open source project in GitHub, one of the first step is to setup continuous integration; the usual question is: What CI engine should I use? Thanks to Azure Dev Ops, you can use free build pipelines to build projects even if they are in GitHub (not hosted in Azure Dev Ops)

Azure Dev Ops, formerly known as VSTS, allows to define free build pipelines to build projects in GitHub

After you created a new project in GitHub, you can simply login to your Azure Dev Ops account (https://dev.azure.com/yourname) then go to azure pipelines and start creating a new pipeline.

image

Figure 1: Wizard to create a new pipeline in Azure DevOps

As you can see, you can choose GitHub repository or Azure Repositories. This is the latest UI available for azure pipelines and allows you to create a pipeline with YAML (definition with Code). Since I really prefer this approach than the usual graphical editor, I choose to create my new pipeline with YAML, so I simply press Git Hub to specify that I want to build a project hosted in GitHub.

Pressing Authorize button you can authorize with OAuth in GitHub, if you prefer you can use a token or install the azure devops app from the GitHub Marketplace, but for this example I’m using OAuth, because is the simpler approach.

image

Figure 2: Authorize button allows you to authorize in GitHub to allows Azure DevOps pipeline to access your code

Once logged in, I can browse and search for the repository I want to build.

image

Figure 3: I’ve chosen the repository I want to build.

When you choose the repository, the wizard analyze the code in the repository, suggesting you the template that best suites your need, in my example code is a standard .NET Desktop application (it is a console app).

image

Figure 4: Template suggestion from the wizard.

You can choose other template or you can start from an empty template. Whatever is your choice, you can always change the template later, so I choose .NET Desktop and move on.

Thanks to the new Wizard, you can start with a template and a YAML definition that contains basic steps to use as starting point.

Once I’ve chosen the template, the wizard generates a YAML Build definition based on that template, like shown in Figure 5.

image

Figure  5: Generated YAML template

Clearly YAML code for the build should be in the repository, so I press the Save and Run button, then choose to create the file in another special branch.

image

Figure 6: Create the YAML build directly in GitHub repository, but in a different branch.

Once the wizard commits the YAML definition, the build immediately starts so you can verify if everything is ok. The nice aspect is that you do not need to configure any build agent, because the build will be executed by Hosted Agent, an agent automatically managed by Microsoft that is hosted in azure. For open source project Azure Dev Ops gives you 10 conccurent builds with unlimited minutes per month, this is really cool.

Azure Pipelines gives you free minutes month and 10 concurrent build for open source projects.

image

Figure 7: Build is running on hosted agent.

The yaml definition is created on the root folder of the repository, if you do not like the position you can simply manually change location and name of the file, then update the build definition to use the new location. Usually I change the location, add the list of branches I want to monitor with continuous integration and add my GitVersion task to assign build number with GitVersion

image

Figure 8: Small modification of the build definition, triggers and GitVersion task.

Just push with the new definition and now you define triggers that automatically builds every push to standard master, develop, feature, release and hotfix branches. Thanks to YAML definition everything regarding the build is defined in YAML file.

Once the build is up and running, you can go to summary of the pipeline definition and you can grab the link for the badge, to use in readme in GitHub.

image

Figure 9: Status badge menu allows you to get the link for the status badge of selected pipeline.

Pressing Status Badge will show you links to render build badges. Usually you can put these links to Readme.md of your repository. If you look at badge Url you can verify that you can specify any branch name; for a gitflow enabled repository at least I’m going to show status for master and develop branches.

Et voilà, badges can be included in GitHub readme.

image

Figure 10: Badges in GitHub readme can show the status of the continuous integration for your project.

Thanks to Azure Pipelines I’ve setup with few minutes of work a Continuous integration pipeline; absolutely for free, without the need to install any agent and directly with YAML code.

Gian Maria.

VSTS Name change in Azure DevOps effects on Git repositories

As I blogged in the past, it is super easy to build a VSTS Build (Now Azure DevOps Pipeline) to keep two repositories in sync. In that article one of the step is pushing the new code to the destination repositories with an url like: https://$(token)@myaddress.visualstudio.com/DefaultCollection, to automatically include a token to authenticate in the destination repository.

Now some of my build started to fail due to timeout and I immediately suspected the reason: the name change from VSTS to Azure DevOps changed the base url from accountname.visualstudio.com to dev.azure.com/accountname, and this in some way broke the bulid.

Due to rebranding of VSTS into Azure DevOps and change of Url you need to pay attention if some extension or build broke due to usage of the old url.

The solution is Super Simple, you need to go to the Repository page of your account using new dev.azure.com address and find the new address of the repository, something like: https://accountname@dev.azure.com/accountname/teamproject/_git/repositoryName. You just need to change adding a semicolon and valid auth token after the accountname, so it is now like this: https://organization:$(Token)/dev.azure…..

image 

Figure 1: New string format to push force to a destination repository

Since I have many mirror build, I want a centralized way to securely store thetoken value to have all the build take this value from a centralized location; the obvious solution is a variable group linked to this build.

image

Figure 2: Variable group linked to this build.

In the variable group I have a single variable called Token, that is secure and it is used by many builds, so each time the token expire, I can change this and all the builds will use the new value.

image

Figure 1: A simple variable group that contains a single secure variable.

That’s all.

Gian Maria.