Using gtest in jenkins - jenkins

I successfully run my unit test with google test in Jenkins, but I don't know how to show the .xml file generated by gtest. It is said that gtest satisfies the JUnit format, so what I set is as follows:
But it ends up with errors after a building.
No test report files were found. Configuration error?
Build step 'Publish JUnit test result report' changed build result to FAILURE
Finished: FAILURE

Fraser's answer is good and you need some extra processing to convert the gtest XML to proper JTest format.
First you ask gtest to output the result to XML using:
mygtestapp --gtest_output=xml:gtestresults.xml
Then in a script you need to add extra elements to properly flag skipped tests as such. Jenkin's JTest processor requires that a skipped test contains the <skipped> element and not just setting status to "notrun":
awk '{ if ($1 == "<testcase" && match($0, "notrun")) print substr($0,0,length($0)-2) "><skipped/></testcase>"; else print $0;}' gtestresults.xml > gtestresults-skipped.xml
mv gtestresults.xml gtestresults.off
If running this on a windows batch file, put the awk action inside a file to avoid problems with the quotes. awk.progfile:
{ if ($1 == "<testcase" && match($0, "notrun")) print substr($0,0,length($0)-2) "><skipped/></testcase>"; else print $0;}
And create add in your bat file:
awk -f awk.progfile gtestresults.xml > gtestresults-skipped.xml
Lastly you point the JTest processor as a Post-Build step to read the converted XML:
# Publish JUnit Test Result Report
Test Report XMLs: gtestresults-skipped.xml

Are you running your test executable with the correct flags (i.e. --gtest_output=xml[:DIRECTORY_PATH\|:FILE_PATH])?
From the --help output:
--gtest_output=xml[:DIRECTORY_PATH\|:FILE_PATH]
Generate an XML report in the given directory or with the given file
name. FILE_PATH defaults to test_details.xml.

The error on the Jenkins configuration page is a bit of a red herring.
Essentially, what's happening is that the test report xml file hasn't been generated by the build job. So, you then get this error:
Recording test results
No test report files were found. Configuration error?
Of course, the location must be configured correctly. For that, see this post:
How to configure test-reports on Jenkins CI working with grails?
So, how to fix the error? The key is to study the console output to check whether the tests did successfully run. Chances are they didn't, and that's why the error has happened.
Once you get the tests running successfully, assuming that you correctly configured the location, you should be ok.
You're using JUnit so it'll be a Java project. I'll note here in case it may help others, that we were running Xcode. The tests weren't being run.
Buried in Jenkins console output just above the error was this note:
note: RunUnitTests exited without running tests because TEST_AFTER_BUILD was set to NO.
Popping back into Xcode, and setting the UnitTests target's Test After Build flag to YES did the trick. That's under the Unit Testing section. You can also of course set the flag at the Project level, and change the target's to 'Other', setting a value of $(inherited).

Your results file is not stored at correct location and Jenkins plugin cannot find it. After your tests are executed and XML file is generated do you store it anywhere?
I suggest try make it working by replacing result.xml with '*' (assuming this is the only XML file that is supposed to be stored there) and if this is going to work then start working on correct file name.
We had the same issue in our configuration. Making sure that generated result XML is stored where the plugin expect it was the key. You can determine workspace root from your project config.

Jenkins has xunit plugin that converts googletest xml to junit format: https://plugins.jenkins.io/xunit/.
Example of pipeline
pipeline {
agent any
stages {
stage('Test'){
steps {
sh "run_tests.bash"
}
}
}
post {
always{
xunit (
thresholds: [ skipped(failureThreshold: '0'), failed(failureThreshold: '0') ],
tools: [ GoogleTest(pattern: 'reports/*.xml') ]
)
}
}
}
Other useful links:
https://jenkins.io/doc/pipeline/steps/xunit/
https://jenkins.io/blog/2016/10/31/xunit-reporting/

Here is a windows batch version for converting the google-test "notRun" to junit "skipped" via windows batch. I know that there are more elegant ways, but this one only requires windows batch and does the job
rem convert gtest xml to junit compatible format (replace notRun by skipped)
IF EXIST %INTEXTFILE% (
IF EXIST %OUTTEXTFILE% (
del %OUTTEXTFILE%
waitfor fileSystemToDoItsStuff /t 1
)
FOR /f "tokens=1,* delims=¶" %%A IN ( '"type %INTEXTFILE%"') DO (
ECHO."%%A" | findstr /C:"DISABLED_">nul & IF ERRORLEVEL 1 (
SET modified=%%A
) ELSE (
SET string=%%A
SET modified=!string:/^>=^>^<skipped /^>^</testcase^>!
)
ECHO !modified!>> %OUTTEXTFILE%
)
del %INTEXTFILE%
waitfor fileSystemToDoItsStuff /t 1
move %OUTTEXTFILE% %INTEXTFILE%
)

Related

Jenkins (2.297) build fails because an "output.xml" file could not be parsed

i set up an Jenkins-> robot framework chain where the robot tasks are stimulated by Jenkins.
The example robot tasks (some simple shell scripts) are executed without errors, but Jenkind fails because it is not able to parse some "output.xml" file which has nothing to do with the robot framework tasks.
Error message:
[ ERROR ] Reading XML source '/var/lib/jenkins/workspace/Test/output.xml' failed:ParseError: junk after document element: line 188, column 0
When i investigate the "output.xml" there is indeed an error:
...
rrors>
</errors>
</robot>
This behavior is already known and active and is described in https://issues.jenkins.io/browse/JENKINS-62359?attachmentViewMode=list
in 2020, but the error is still appearing.
Is there a solution or workaround? It is curious that sometimes the build is executing without an error when nothing changed.

how to build cc_test for android using bazel

I am trying to use bazel as build system.
My project looks like this:
a static library which contains a bunch of classes and functions
a dynamic library (so/dll) using the same code as the static library (need to have it because of windows, cc_library rule does not automatically build a dll on windows)
a cc_test rule which build an executable. it contains unit tests based on google test framework
It works when running on Windows and Linux.
The test rule fails when trying to build Android like this
bazel build //unit:unit --crosstool_top=#androidndk//:default_crosstool --cpu=armeabi-v7a
INFO: Invocation ID: b7c88128-3448-4eb7-bf25-ce8269895956 ERROR: ../yg32wcuz/external/androidndk/BUILD.bazel:39:1: in cc_toolchain_suite rule #androidndk//:toolchain-gnu-libstdcpp: cc_toolchain_suite '#androidndk//:toolchain-gnu-libstdcpp' does not contain a toolchain for cpu 'x64_windows'
ERROR: Analysis of target '//unit:unit' failed; build aborted: Analysis of target '#androidndk//:toolchain-gnu-libstdcpp' failed; build aborted
It looks like that bazel seems to have problem with cc_test and android toolchain
Is there any way to build and run an executable for android using bazel? Maybe I missed some command line arguments
Edit:
tried the solution below and added a sh_test rule but it fails again
using #androidsdk//:adb and leads to the following error
ERROR: missing input file '#androidsdk//:platform-tools/adb'
ERROR: unit/BUILD:61:1: //unit:unit_android: missing input file '#androidsdk//:platform-tools/adb' Target //unit:unit_android failed to build
ERROR: unit/BUILD:61:1 1 input file(s) do not exist
I also need to use $ANDROID_HOME/platform-tools/adb to get the adb binary. external/androidsdk/platform-tools/adb does not work. my BUILD file is in a sub folder of the workspace, maybe this is the issue.
removing #androidsdk//:adb fixes this error. there are some adjustments needed in sh_test rule like:
sh_test(
name = "unit_android",
srcs = ["unit_android.sh"],
data = [
":unit",
#"#androidsdk//:adb",
],
deps = [
"#bazel_tools//tools/bash/runfiles", # to access the manifest
],
)
using runfiles dependency allows me to access the binary via $(rlocation ..) in shell script. but now there seems to be another issue:
when using 'bazel run':
It looks like that bazel is trying to upload the file to msys shell (i am using windows) and not to the device:
adb: error: failed to copy '.../_bazel_exb_a/yg32wcuz/execroot/test/bazel-out/armeabi-v7a-fastbuild/bin/unit/unit' to 'C:/Development/msys2/data/local/tmp/unit'
when using 'bazel test':
it just states an error and the content of test log is
unknown parameter - /users
Edit 2:
WORKSPACE file about android sdk/ndk
android_ndk_repository(
name = "androidndk", # Required. Name *must* be "androidndk".
api_level = 26
)
android_sdk_repository(
name = "androidsdk", # Required. Name *must* be "androidsdk".
api_level = 26
)
In both case I assume env var ANDROID_NDK_HOME (points to ndk), ANDROID_SDK_HOME (points to sdk) and ANDROID_HOME (points to sdk) are set. I also checked the external dir, sdk is in there. Removing "#androidsdk//:adb" seem to work but the bazel shell environment now tries to add a prefix before "/data/local/tmp" and tries to upload to a non existing folder.
forget about the issue with "/users" (windows path issue ...)
--crosstool_top by itself sets both the target and host crosstool, so you may just need to set --host_crosstool_top back to the default: --host_crosstool_top=#bazel_tools//tools/cpp:toolchain
Edit:
Running the test on a device is unfortunately not supported out of the box by bazel test. There needs to be some test runner that knows how to put the test on the device, run it, and collect the results. A very simple version of that might look like:
test.cc:
int main(int argc, char** argv) {
// Test always passes.
// Return non-zero for test failure.
return 0;
}
example_android_cc_test.sh:
adb=external/androidsdk/platform-tools/adb
# The test requires a running emulator or connected device.
# The name of the cc_test binary can be passed in using the
# args attribute of sh_test to make this script generic.
$adb push example_test /data/local/tmp
# adb shell returns the exit code of the command
# that was executed, and the exit code of the
# test shell script determines if the sh_test target
# passes or fails.
$adb shell "/data/local/tmp/example_test"
BUILD:
cc_test(
name = "example_test",
srcs = ["test.cc"],
linkopts = ["-pie"],
linkstatic = 1,
)
sh_test(
name = "example_android_cc_test",
srcs = ["example_android_cc_test.sh"],
data = [
":example_test",
"#androidsdk//:adb",
],
)
Note that this approach is not hermetic because it relies on an emulator to already be running, or a device to be already connected. It's possible to start an emulator as part of the test, but that's more involved.

allure-results does not exists in Jenkins

Allure results are generated (xmls) and can be viewed by running allure serve outside the allure-results directory but when configured in Jenkins using the allure results directory with relative path from Jenkins workspace, the allure results are not found. Presumably there is something wrong with the path
[allure_test] $ /Users/me/.jenkins/tools/ru.yandex.qatools.allure.jenkins.tools.AllureCommandlineInstallation/Allure_2.7.0/bin/allure generate -c -o /Users/me/.jenkins/workspace/allure_test/allure-report
allure-results does not exists
Report successfully generated to /Users/me/.jenkins/workspace/allure_test/allure-report
Allure report was successfully generated.
Relative Path defined for allure report is
../../repos/partner-portal/target/allure-results
The report is generated but with no results
Here is the solution:
1. Inside your work space (For me it is D:\m\Automation Project\Tests), Create a folder named "target" containing two subfolders "allure-results" and "allure-reports".
In Post Build Actions of Jenkins Project provide these entries.
Results: target/allure-results
Report Path: target/allure-reports
Now run your tests and allure reports will be generated without any issues.
I struggled for over 24 hours and could not sleep whole night just because of this issue. There were no clear instructions related to this and how it works. Finally, I figured it out.
May be its little too late for this answer but could you please create the "allure-results" folder in your workspace (like /Users/me/.jenkins/workspace/allure_test/allure-results)?
After I configure Allure report in jenkins, and using behave command, I finally see following output and saw the working report in my jenkins build plan:
.
.
.
.
D:\PythonProject\PythonBehave>behave -f allure_behave.formatter:AllureFormatter -o C:\Users\Alex\.jenkins\workspace\PythonAllure\allure-results D:\PythonProject\PythonBehave\features
Failing scenarios:
features/example.feature:17 user can search text in google -- #2.2 Incorrect
features/github_login.feature:13 User attempt to login with wrong username and password -- #1.1 InCorrect
features/github_login.feature:14 User attempt to login with wrong username and password -- #1.2 InCorrect
features/github_login.feature:18 User attempt to login with correct username and password
0 features passed, 2 failed, 0 skipped
3 scenarios passed, 4 failed, 0 skipped
12 steps passed, 4 failed, 8 skipped, 0 undefined
Took 3m24.651s
D:\PythonProject\PythonBehave>exit 1
Build step 'Custom Python Builder' marked build as failure
[PythonAllure] $ C:\Users\Alex\.jenkins\tools\ru.yandex.qatools.allure.jenkins.tools.AllureCommandlineInstallation\Allure_2.13.1\bin\allure.bat generate C:\Users\Alex\.jenkins\workspace\PythonAllure\allure-results -c -o C:\Users\Alex\.jenkins\workspace\PythonAllure\allure-report
Report successfully generated to C:\Users\Alex\.jenkins\workspace\PythonAllure\allure-report
Allure report was successfully generated.
Creating artifact for the build.
Artifact was added to the build.
Finished: FAILURE
And before I used to get this output when there was no allure-results folder in my workspace:
[PythonAllure] $ C:\Users\Alex\.jenkins\tools\ru.yandex.qatools.allure.jenkins.tools.AllureCommandlineInstallation\Allure_2.13.1\bin\allure.bat generate -c -o C:\Users\Alex\.jenkins\workspace\PythonAllure\allure-report
we are not using any post-build steps on UI but using jenkins pipeline groovy script as below:
def allureReportsGenerationTask() {
try {
allure([includeProperties: false, jdk: '', properties: [], reportBuildPolicy: 'ALWAYS', results: [[path: 'target/allure-results']]])
} catch(Exception error) {
println("Caught Exception: ${error}")
}
}
The project structure was like that only
ProjectRepo
- src
- target
-alure-results
- pom.xml
- testng.xml
In this case, we are getting the allure-results getting generated but it was not getting picked in the Jenkins pipeline allure plugin. ON UI below command was running always
/opt/jenkins/tools/ru.yandex.qatools.allure.jenkins.tools.AllureCommandlineInstallation/allure/bin/allure generate -c -o /opt/jenkins/workspace/ProjectRepoPipeline/allure-report
you can see Jenkins was not able to find allure-results for generating parameters in the above Jenkins pipeline command
We added the below parameter in pom.xml maven-surefire-plugin
<systemPropertyVariables>
<allure.results.directory>../target/allure-results</allure.results.directory>
</systemPropertyVariables>
Now project structure becomes
-ProjectRepo
- src
- pom.xml
- testng.xml
target
-allure-results
Now on running the same via pipeline script, we were able to run the below command
/opt/jenkins/tools/ru.yandex.qatools.allure.jenkins.tools.AllureCommandlineInstallation/allure/bin/allure generate /opt/jenkins/workspace/ProjectRepoPipeline/target/allure-results -c -o /opt/jenkins/workspace/ProjectRepoPipeline/allure-report
ProjectRepoPipeline - This is the Jenkins pipeline name that is running CI/CD

How to check the Console Output for a specific string and raise an error on the Build?

I have Hudson configured for building a project.
And the console output, after building is, as follows:
Compiling ./main.py ...
Sorry: IndentationError: ('expected an indented block', ('./main.py', 8, 6, 'thread.start_new_thread( foo.FooThread, () )\n'))
Compiling ./udpReceiver.py ...
<<<<< build finished!
POST BUILD TASK : SUCCESS
END OF POST BUILD TASK : 0
Deleting project workspace...
done
Finished: SUCCESS
As you can see, I have an Indentation Error....and Hudson says that the build job finished with success.
What I want is something like this:
Check if the string "IndentationError" is presented on the console output text ... if so, than the build should be:
Finished: FAILED!!!!!!!!
How can I accomplish this?
I confirm that the Log Parser plugin can do the job to change the build status to failure.
Install the plugin and create a rule set for your Python build for example:
In the create the /var/lib/jenkins/logParserRules/python-error file:
error /IndentationError/
Next, update the Python build with these settings:
The build status will be changed to FAILURE:
Compiling ./udpReceiver.py ...'
Sorry: IndentationError: ('expected an indented block', ('./main.py', 8, 6, 'thread.start_new_thread( foo.FooThread, () )\n'))
Compiling ./udpReceiver.py ...
Build step 'Console output (build log) parsing' changed build result to FAILURE

Sonar and TFS 2013 : No ProjectInfo.xml files were found

When I run TFS 2013 with sonar I get the following error: No ProjectInfo.xml files were found. Check that the analysis targets are referenced by the MSBuild projects being built.
Message: TF270015: 'SonarQube.MSBuild.Runner.exe' returned an unexpected exit code. Expected '0'; actual '1'.
I use :
sonarqube-5.1.zip
sonar-csharp-plugin-4.0.jar
SonarQube.MSBuild.Runner-0.9.zip
sonar-runner-dist-2.4.zip
I've followed instructions found in "SonarQube Installation Guide for Existing TFS Environment.pdf".
Any help ?
Thank you.
Log :
SonarQube Analysis Summary
Analysis failed for SonarQube project "WpfApplication2", version 1.0
Product projects: 0, test projects: 0
Invalid projects: 0, skipped projects: 0, excluded projects: 0
Résumé
Debug | x86
0 erreur(s), 1 avertissement(s)
$/Essai2/WpfApplication2/WpfApplication2.sln - 0 erreur(s), 1 avertissement(s),
Afficher le fichier journal
C:\Builds\1\Essai2\WpfApplication2\src\documents\visual studio 2013\Projects\WpfApplication2\WpfApplication2.sln.metaproj : The specified solution configuration "Debug|x86" is invalid. Please specify a valid solution configuration using the Configuration and Platform properties (e.g. MSBuild.exe Solution.sln /p:Configuration=Debug /p:Platform="Any CPU") or leave those properties blank to use the default solution configuration.
$/Essai2/WpfApplication2/WpfApplication2.sln compilé
Aucun résultat des tests
Aucun résultat de couverture du code
Autres erreurs et avertissements
2 erreur(s), 0 avertissement(s)
01:45:52: No ProjectInfo.xml files were found. Check that the analysis targets are referenced by the MSBuild projects being built.
Exception Message: TF270015: 'SonarQube.MSBuild.Runner.exe' returned an unexpected exit code. Expected '0'; actual '1'. See the build logs for more details. (type UnexpectedExitCodeException)
Exception Stack Trace: at System.Activities.Statements.Throw.Execute(CodeActivityContext context)
at System.Activities.CodeActivity.InternalExecute(ActivityInstance instance, ActivityExecutor executor, BookmarkManager bookmarkManager)
at System.Activities.Runtime.ActivityExecutor.ExecuteActivityWorkItem.ExecuteBody(ActivityExecutor executor, BookmarkManager bookmarkManager, Location resultLocation)
Here is the Diagnostic (I truncated the source check out part) :
Compile, Test and Publish00:00:46
Run optional script before MSBuild00:00:08
InputsEnvironmentVariables:
Enabled: True
Arguments: /key:WpfApplication2 /name:WpfApplication2 /version:1.0
FilePath: C:\sonarqube\bin\SonarQube.MSBuild.Runner.exe
OutputsResult: 0
C:\sonarqube\bin\SonarQube.MSBuild.Runner.exe /key:WpfApplication2 /name:WpfApplication2 /version:1.0
Pre-processing (3 arguments passed)
Using environment variables to determine the download directory...
Using environment variable 'TF_BUILD_BUILDDIRECTORY', value 'C:\Builds\1\Essai2\WpfApplication2'
Creating the analysis bin directory: C:\Builds\1\Essai2\WpfApplication2\sqtemp\bin
SonarQube server url: http://localhost:9000
Downloading SonarQube.MSBuild.Runner.Implementation.zip from http://localhost:9000/static/csharp/SonarQube.MSBuild.Runner.Implementation.zip to C:\Builds\1\Essai2\WpfApplication2\sqtemp\bin\SonarQube.MSBuild.Runner.Implementation.zip
Executing file C:\Builds\1\Essai2\WpfApplication2\sqtemp\bin\SonarQube.MSBuild.PreProcessor.exe
Args: "/key:WpfApplication2" "/name:WpfApplication2" "/version:1.0"
Working directory: C:\Builds\1\Essai2\WpfApplication2\sqtemp\bin
Timeout (ms):300000
Process id: 4168
01:45:11: The path to the sonar-runner.properties file was not supplied on the command line. Attempting to locate the file...
01:45:11: Located the runner properties file: C:\sonar-runner-2.4\conf\sonar-runner.properties
01:45:11: Legacy TeamBuild environment detected
01:45:11: Creating config and output folders...
01:45:11: Removing the existing directory: C:\Builds\1\Essai2\WpfApplication2\sqtemp\conf
01:45:11: Creating directory: C:\Builds\1\Essai2\WpfApplication2\sqtemp\conf
01:45:11: Removing the existing directory: C:\Builds\1\Essai2\WpfApplication2\sqtemp\out
01:45:11: Creating directory: C:\Builds\1\Essai2\WpfApplication2\sqtemp\out
Generating the FxCop ruleset...
01:45:14: Saving the config file to C:\Builds\1\Essai2\WpfApplication2\sqtemp\conf\SonarQubeAnalysisConfig.xml
Process returned exit code 0
Run MSBuild00:00:12
InputsProjectsToBuild: String[] Array
MSBuildMultiProc: True
Verbosity: Normal
ToolPlatform: Auto
Targets:
RunCodeAnalysis: AsConfigured
CommandLineArguments: /p:SkipInvalidConfigurations=true /p:Configuration=Debug /p:Platform="Any CPU"
ConfigurationsToBuild: String[] Array
OutputLocation: SingleFolder
Enabled: True
ToolVersion:
CleanBuild: True
OutDir:
RestoreNuGetPackages: True
C:\Program Files\Microsoft Team Foundation Server 12.0\Tools\nuget.exe restore "C:\Builds\1\Essai2\WpfApplication2\src\documents\visual studio 2013\Projects\WpfApplication2\WpfApplication2.sln" -NonInteractive
C:\Program Files (x86)\MSBuild\12.0\bin\amd64\MSBuild.exe /nologo /noconsolelogger "C:\Builds\1\Essai2\WpfApplication2\src\documents\visual studio 2013\Projects\WpfApplication2\WpfApplication2.sln" /nr:False /fl /flp:"logfile=C:\Builds\1\Essai2\WpfApplication2\src\documents\visual studio 2013\Projects\WpfApplication2\WpfApplication2.log;encoding=Unicode;verbosity=normal" /p:SkipInvalidConfigurations=true /p:Configuration=Debug /p:Platform="Any CPU" /m /p:OutDir="C:\Builds\1\Essai2\WpfApplication2\bin\\" /p:Configuration="Debug" /p:Platform="x86" /p:VCBuildOverride="C:\Builds\1\Essai2\WpfApplication2\src\documents\visual studio 2013\Projects\WpfApplication2\WpfApplication2.sln.x86.Debug.vsprops" /dl:WorkflowCentralLogger,"C:\Program Files\Microsoft Team Foundation Server 12.0\Tools\Microsoft.TeamFoundation.Build.Server.Logger.dll";"Verbosity=Normal;BuildUri=vstfs:///Build/Build/52;IgnoreDuplicateProjects=False;InformationNodeId=12;TargetsNotLogged=GetNativeManifest,GetCopyToOutputDirectoryItems,GetTargetPath;LogProjectNodes=True;LogWarnings=True;TFSUrl=http://localhost:8080/tfs/DefaultCollection;"*WorkflowForwardingLogger,"C:\Program Files\Microsoft Team Foundation Server 12.0\Tools\Microsoft.TeamFoundation.Build.Server.Logger.dll";"Verbosity=Normal;" /p:BuildId="dbda6e4d-d5bc-4eed-8b3e-6cc79e3721cc,vstfs:///Build/Build/52" /p:BuildLabel="WpfApplication2_20150615.3" /p:BuildTimestamp="Mon, 15 Jun 2015 11:44:59 GMT" /p:BuildSourceVersion="LWpfApplication2_20150615.3#$/Essai2" /p:BuildDefinition="WpfApplication2"
Run optional script after MSBuild00:00:00
InputsEnvironmentVariables:
Enabled: True
Arguments:
FilePath:
OutputsResult: 0
Run optional script before Test Runner00:00:00
InputsEnvironmentVariables:
Enabled: True
Arguments:
FilePath:
OutputsResult: 0
Run VS Test Runner00:00:00
InputsTestSpecs: BuildParameter[] Array
Enabled: False
ConfigurationsToTest: String[] Array
OutDir:
This activity was not run since its Enabled property was set to False.
Run optional script after Test Runner00:00:25
InputsEnvironmentVariables:
Enabled: True
Arguments:
FilePath: C:\sonarqube\bin\SonarQube.MSBuild.Runner.exe
OutputsResult: 0
C:\sonarqube\bin\SonarQube.MSBuild.Runner.exe
Post-processing (no arguments passed)
Using environment variables to determine the download directory...
Using environment variable 'TF_BUILD_BUILDDIRECTORY', value 'C:\Builds\1\Essai2\WpfApplication2'
Executing file C:\Builds\1\Essai2\WpfApplication2\sqtemp\bin\SonarQube.MSBuild.PostProcessor.exe
Args:
Working directory: C:\Builds\1\Essai2\WpfApplication2\sqtemp\bin
Timeout (ms):3600000
Process id: 6548
01:45:28: Legacy TeamBuild environment detected
01:45:28: Loading the SonarQube analysis config from C:\Builds\1\Essai2\WpfApplication2\sqtemp\conf\SonarQubeAnalysisConfig.xml
01:45:28: Legacy TeamBuild environment detected
01:45:28: Attempting to locate the CodeCoverage.exe tool...
01:45:28: Code coverage command line tool: C:\Program Files (x86)\Microsoft Visual Studio 12.0\Team Tools\Dynamic Code Coverage Tools\CodeCoverage.exe
01:45:28: Fetching code coverage report information from TFS...
01:45:28: Connecting to TFS...
01:45:29: Fetching build information...
01:45:30: Fetch code coverage report info...
01:45:52: Operation timed out, Elapsed time (ms): 20358
01:45:52: ...done.
01:45:52: No code coverage reports were found for the current build.
01:45:52: Generating SonarQube project properties file to C:\Builds\1\Essai2\WpfApplication2\sqtemp\out\sonar-project.properties
01:45:52: No ProjectInfo.xml files were found. Check that the analysis targets are referenced by the MSBuild projects being built.
01:45:52: Writing processing summary to C:\Builds\1\Essai2\WpfApplication2\sqtemp\out\ProjectInfo.log
01:45:52: Generation of the sonar-properties file failed. Unable to complete SonarQube analysis.
01:45:52: Updating the TeamBuild summary...
Process returned exit code 1
Exception Message: TF270015: 'SonarQube.MSBuild.Runner.exe' returned an unexpected exit code. Expected '0'; actual '1'. See the build logs for more details. (type UnexpectedExitCodeException) Exception Stack Trace: at System.Activities.Statements.Throw.Execute(CodeActivityContext context) at System.Activities.CodeActivity.InternalExecute(ActivityInstance instance, ActivityExecutor executor, BookmarkManager bookmarkManager) at System.Activities.Runtime.ActivityExecutor.ExecuteActivityWorkItem.ExecuteBody(ActivityExecutor executor, BookmarkManager bookmarkManager, Location resultLocation)
Handle Exception
Troubleshooting issues with the MSBuild.Runner v0.9
The following information is provided to help troubleshooting issues with version 0.9 of the MSBuild.Runner. The behaviour may change in later versions.
Most serious configuration issues will result in warnings or errors that will appear on the Build Summary page. In cases in which there are no errors or warnings reported, check the TFS TeamBuild diagnostic output (click on "Diagnostics" link at the top of the build summary report in Visual Studio). Both the pre- and post-processor steps log quite a lot of information to help diagnose issues.
1. Check the SonarQube Analysis Summary section appears in the Build Summary Report
The section should look like this:
SonarQube Analysis Summary
Analysis failed for SonarQube project "Simple console app", version 1.0
Product projects: 4, test projects: 2
Invalid projects: 0, skipped projects: 0, excluded projects: 0
If the section does not appear on the build summary page then there are configuration issues with the build agent, build definition, or both. Read the steps below to diagnose these further.
1.1 Check the number of projects that are reported in the summary
If no projects were found then it suggests that the integration targets are not being imported and used during the build.
If all of the projects are marked as invalid, it is likely that you are building more than one configuration e.g. [release or debug] | [x86 or x64]. You should also get an error saying no ProjectInfo.xml files could be found.
You can only analyse one configuration at a time. If you want to analyze both release and debug builds, then you will need to create a separate build definition for each, using different SonarQube project ids.
The diagnostic log will contain more infomation about why a project was invalid, which is normally because the project doesn't have a guid, or the guid is not unique. The normal reason for a non-unique guid is that you are building multiple configurations e.g. release and debug.
2. Check that the pre-build step is being executed
The diagnostic output should contain output similar to the following:
Run optional script before MSBuild
C:\SonarQube\bin\SonarQube.MSBuild.Runner.exe /key:MyProject /name:"My Project" /version:1.0
Pre-processing (3 arguments passed)
If it doesn't, check that the you are correctly calling SonarQube.MSBuild.Runner.exe in the "Pre-build script" step in the build definition. An easy mistake is to put the script parameters in the wrong box by setting the "Post-build" properties instead (unhelpfully, the Post-build fields in the UI appear before the Pre-build fields).
2. Check that the post-build step is being executed
The diagnostic output should contain output similar to the following:
Run optional script after Test Runner
C:\SonarQube\bin\SonarQube.MSBuild.Runner.exe
Post-processing (no arguments passed)
If it doesn't, check that the you are correctly calling SonarQube.MSBuild.Runner.exe in the "Post-test script" step in the build definition.
3. Check the rest of the diagnostic log
If the pre- and post- build steps are being executed correctly, check the rest of the diagnostic output for any clues as to what isn't working. Pay particular attention to messages from the pre- and post-processor about the directories and files they are writing to.
4. Check the files that have been created on the build agent
The analysis process creates temporary files under the build directory under a folder called SQTemp in v0.9.
Examining the contents of the folders can help determine the stage at which the analysis is failing.
The expected folders are as follows:
bin: this folder contains the analysis targets and binaries. It is created by the SonarQube.MSBuild.Runner.exe which downloads the files from the SonarQube server. If this folder does not exist or is empty then the analysis failed at a very early stage and there should warnings or errors. Check that the C# plugin v4 is installed correctly on the SonarQube server, and that the SonarQube has been restarted since the plugin was installed.
conf: this folder is created during pre-processing and contains the settings downloaded from the SonarQube server. If there are any FxCop rules active in the SonarQube the folder should contain an FxCop ruleset.
out: this folder is populated during the MSBuild phase. It should contain one folder per project being built. It will also contain the generated sonar-project.properties file that is passed to the sonar-runner. If the folder is empty then it is possible the SonarQube.Integration.targets are not being imported correctly.
The error message "No ProjectInfo.xml files were found" will normally appear in this case. The ProjectInfo.xml files are generated by the target "WriteSonarQubeData" in the SonarQube.Integration.targets, so the next thing to check is that SonarQube.Integration.targets are being imported correctly and the expected targets are being executed.
5. Checking the SonarQube.Integration.targets are imported and called
Firstly, double-check the installation of the SonarQube.Integration.ImportBefore.targets file:
check it is in the correct folder for the version of MSBuild you are using i.e. %ProgramFiles(x86)%\MSBuild\[12.0 or 14.0]\Microsoft.Common.Targets\ImportBefore
check for typos in the folder name "ImportBefore" (should be singular, not plural)
(Thanks to Richard from BlackMarble for this tip).
If the targets are installed correctly then you will need to increase the verbosity of the MSBuild logging to diagnostic and build again so you can check the detailed MSBuild output. Unfortunately, there doesn't seem to be a simple way to increase the verbosity of the MSBuild logs when running under TeamBuild 2013. You can produce an additional log file with more detail, but you will need access to the build agent machine to pick up the log file.
To create an MSBuild log with more detailed info:
select "Queue New Build" from the BUILD menu in Visual Studio
click on the "Parameters" tab.
Expand the "2. Build" section and the "5. Advanced" sections
Set the "MSBuild arguments" property to the following:
/m:1 /fl2 /flp2:"verbosity=diagnostic"
The "/m:1" tells MSBuild not to build in parallel which can make the log easier to read. The other two parameters tell MSBuild to log to a file. See the MSBuild command line help for more info.
Click "Queue" and wait for the build to finish.
Find and open the log on the build agent. It should be called msbuild2.log and be under the source directory for your build definition.
If the SonarQube.Intergration.ImportBefore.targets are being executed, there will be a log entry saying the "SonarQubeImportBeforeInfo" target was executed. There should be some output message saying whether the file "SonarQube.Integration.targets" was located or not.
The ProjectInfo.xml files are written by the target "WriteSonarQubeProjectData". The log should show that this target has been executed, and the "WriteProjectInfoFile" task has executed. If not, the log should give an idea of why the targets were skipped.

Resources