Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Infer test assembly from solution and project files #6

Merged
merged 6 commits into from
May 27, 2011
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
151 changes: 151 additions & 0 deletions src/Giles.Core/Configuration/MsBuildProject.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml;

namespace Giles.Core.Configuration
{
public class MsBuildProject
{
private readonly XmlDocument document;

public MsBuildProject(XmlDocument document)
{
this.document = document;
}

public static MsBuildProject Load(Stream projectFile)
{
var document = new XmlDocument();
document.Load(projectFile);

return new MsBuildProject(document);
}

public IEnumerable<string> GetLocalAssemblyRefs()
{
return (from XmlNode itemGroup in ProjectNode.ChildNodes
where itemGroup.Name == "ItemGroup"
from XmlNode refNode in itemGroup.ChildNodes
where refNode.Name == "Reference"
from XmlNode hintNode in refNode.ChildNodes
where hintNode.Name == "HintPath"
select hintNode.InnerText).ToArray();
}

public string GetAssemblyName()
{
var platformConfig = GetDefaultPlatformConfig();
return GetPropertyValue(platformConfig, "AssemblyName");
}

/// <summary>
/// Gets the output assembly file path relative to the
/// project files directory. Uses the project default
/// plaftorm configuration.
/// </summary>
/// <returns></returns>
public string GetAssemblyFilePath(string projectFilePath)
{
var platformConfig = GetDefaultPlatformConfig();
var dir = GetPropertyValue(platformConfig, "OutputPath");
var outtype = GetPropertyValue(platformConfig, "OutputType");

// FIXME: DLL or EXE
var assemblyName = GetPropertyValue(platformConfig, "AssemblyName");
switch(outtype.ToUpper())
{
case "LIBRARY":
assemblyName += ".dll";
break;
case "EXE":
assemblyName += ".exe";
break;
}

var projectPath = Path.GetDirectoryName(projectFilePath);
if (projectPath == null)
throw new ArgumentException("Invalid project file path", "projectFilePath");

return Path.Combine (projectPath, Path.Combine(dir, assemblyName));
}

public string GetPropertyValue(string platformConfig, string property)
{
var condition = "'" + platformConfig + "'";
var specific = (
from XmlNode propertyGroup in ProjectNode.ChildNodes
where propertyGroup.Name == "PropertyGroup" &&
propertyGroup.Attributes != null &&
propertyGroup.Attributes["Condition"] != null &&
propertyGroup.Attributes["Condition"].InnerText.Contains(condition)

from XmlNode outputNode in propertyGroup.ChildNodes
where outputNode.Name == property
select outputNode.InnerText).ToArray();

var defaultConfig = (
from XmlNode propertyGroup in ProjectNode.ChildNodes
where propertyGroup.Name == "PropertyGroup" && (
propertyGroup.Attributes == null ||
propertyGroup.Attributes["Condition"] == null)

from XmlNode outputNode in propertyGroup.ChildNodes
where outputNode.Name == property
select outputNode.InnerText).ToArray();

switch (specific.Length)
{
case 1:
return specific[0];
case 0:
switch (defaultConfig.Length)
{
case 1:
return defaultConfig[0];
case 0:
throw new InvalidOperationException(
string.Format("No value found for property '{0}' using "
+ "platform configuration '{1}'", property, platformConfig));
}
break;
}
throw new InvalidOperationException(
string.Format("The property '{0}' had multiple values "
+ "applicable for the same platform configuration '{1}'",
property, platformConfig));
}

public string GetDefaultPlatformConfig()
{
var config = GetDefaultPropertyValue("Configuration");
var platform = GetDefaultPropertyValue("Platform");
return config + "|" + platform;
}

private string GetDefaultPropertyValue(string property)
{
return (from XmlNode propertyGroup in ProjectNode.ChildNodes
where propertyGroup.Name == "PropertyGroup" &&
(propertyGroup.Attributes == null ||
propertyGroup.Attributes["Condition"] == null)
from XmlNode configNode in propertyGroup.ChildNodes
where configNode.Name == property &&
configNode.Attributes != null &&
configNode.Attributes["Condition"] != null &&
configNode.Attributes["Condition"].InnerText.Contains("'$(" + property + ")' == ''")
select configNode.InnerText).Single();
}

private XmlNode ProjectNode
{
get
{
return (from XmlNode node in document.ChildNodes
where node.Name.Equals("Project", StringComparison.OrdinalIgnoreCase)
select node).First();
}
}
}
}
97 changes: 97 additions & 0 deletions src/Giles.Core/Configuration/TestAssemblyFinder.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Giles.Core.IO;

namespace Giles.Core.Configuration
{
public class TestAssemblyFinder
{
private readonly IFileSystem fileSystem;

//Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Giles.Specs", "Giles.Specs\Giles.Specs.csproj", "{8FAE1516-9D4A-4575-83BF-515BC6AF8AC3}"
private static readonly Regex SolutionFileRegex = new Regex(
@"Project\(""{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC\}""\)" +
@"[^""]*""[^""]*""" +
@"[^""]*""([^""]*)""", RegexOptions.Compiled);

public TestAssemblyFinder(IFileSystem fileSystem)
{
this.fileSystem = fileSystem;
}

public IEnumerable<string> FindTestAssembliesIn(string solutionFilePath)
{
var projectFiles = GetProjectFilePaths(solutionFilePath);
var testAssemblies = new List<Tuple<int, string>>();
foreach (var file in projectFiles)
{
using (var stream = fileSystem.OpenFile(file, FileMode.Open,
FileAccess.Read, FileShare.ReadWrite))
{
var project = MsBuildProject.Load(stream);
var isTestProjectScore = GetIsTestProjectScore(project);
if (isTestProjectScore > 0)
{
var assemblyFilePath = project.GetAssemblyFilePath(file);
testAssemblies.Add(new Tuple<int, string>(
isTestProjectScore, assemblyFilePath));
}
}
}

// return assemblies with highest score first
return (from tuple in testAssemblies
orderby tuple.Item1 descending,
tuple.Item2 ascending // keep things deterministic for testing
select tuple.Item2).ToArray();
}

private IEnumerable<String> GetProjectFilePaths(string solutionFilePath)
{
var solutionContents = fileSystem.ReadAllText(solutionFilePath);
var solutionFileDir = Path.GetDirectoryName(solutionFilePath);
var match = SolutionFileRegex.Match(solutionContents);
while (match.Success)
{
var relativePath = match.Groups[1].Value;
match = match.NextMatch();
var path = Path.Combine(solutionFileDir, relativePath);
yield return path;
}
}

private int GetIsTestProjectScore(MsBuildProject project)
{
// TODO: may want to group this information with other info about supported test frameworks
int score = 0;
if (IsTestFrameworkReferenced(project, "Machine.Specifications.dll"))
score += 10;
if (IsTestFrameworkReferenced(project, "nunit.framework.dll"))
score += 10;

// no supported test framework, abort
if (score == 0)
return 0;

var assemblyName = project.GetAssemblyName();
if (assemblyName.Contains("UnitTest"))
score += 5;
else if (assemblyName.Contains("Test"))
score += 3;

if (assemblyName.Contains("Spec"))
score += 2; // more likely to have non-test project with Spec in it?

return score;
}

private bool IsTestFrameworkReferenced(MsBuildProject project, string frameworkAssemblyFilename)
{
return project.GetLocalAssemblyRefs().Any(info =>
info.EndsWith(frameworkAssemblyFilename, StringComparison.OrdinalIgnoreCase));
}
}
}
3 changes: 3 additions & 0 deletions src/Giles.Core/Giles.Core.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,10 @@
<Compile Include="AppDomains\GilesAppDomainRunner.cs" />
<Compile Include="Configuration\GilesConfig.cs" />
<Compile Include="Configuration\GilesConfigFactory.cs" />
<Compile Include="Configuration\MsBuildProject.cs" />
<Compile Include="Configuration\RunnerAssembly.cs" />
<Compile Include="Configuration\Settings.cs" />
<Compile Include="Configuration\TestAssemblyFinder.cs" />
<Compile Include="Encryption\EncryptionHelper.cs" />
<Compile Include="IO\IFileSystem.cs" />
<Compile Include="IO\FileWatcherFactory.cs" />
Expand Down Expand Up @@ -92,6 +94,7 @@
<Reference Include="System.Configuration" />
<Reference Include="System.Core" />
<Reference Include="System.Security" />
<Reference Include="System.Xml" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Expand Down
57 changes: 57 additions & 0 deletions src/Giles.Specs/Core/Configuration/MsBuildProjectSpecs.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
using System;
using System.Linq;
using Giles.Core.Configuration;
using Machine.Specifications;

namespace Giles.Specs.Core.Configuration
{
public class an_msbuild_project
{
protected static string projectPath;
protected static MsBuildProject project;

private Establish context = () => {
projectPath = "Giles.Specs.Core.Configuration.Resources.Giles.Specs.csproj";
};
}

public class when_an_msbuild_project_is_loaded : an_msbuild_project
{
Because of = () => {
project = MsBuildProject.Load(TestResources.Read(projectPath));
};

It returns_referenced_assemblies_with_local_paths = () => {
project.GetLocalAssemblyRefs()
.Any(x => x == @"..\..\lib\NSubstitute.1.0.0.0\lib\35\NSubstitute.dll")
.ShouldEqual(true);
project.GetLocalAssemblyRefs()
.Any(x => x == @"..\..\tools\mspec\Machine.Specifications.dll")
.ShouldEqual(true);
project.GetLocalAssemblyRefs().Count().ShouldEqual(2);
};

It returns_the_default_platform_configuration = () =>
project.GetDefaultPlatformConfig().ShouldEqual("Debug|AnyCPU");

It returns_property_values_based_on_platform_configuration = () => {
project.GetPropertyValue("Release|AnyCPU", "OutputPath").ShouldEqual(@"bin\Release\");
project.GetPropertyValue("Debug|AnyCPU", "OutputPath").ShouldEqual(@"bin\Debug\");
project.GetPropertyValue("Debug|AnyCPU", "DefineConstants").ShouldEqual("DEBUG;TRACE");
};

It returns_the_default_property_value_if_platform_specific_not_found = () =>
project.GetPropertyValue("Release|AnyCPU", "AssemblyName").ShouldEqual(@"Giles.Specs");

It should_not_return_property_value_for_other_platform_configurations = () =>
typeof(InvalidOperationException).ShouldBeThrownBy(
() => project.GetPropertyValue("Release|AnyCPU", "DebugSymbols"));

It returns_the_output_assembly_path = () =>
project.GetAssemblyFilePath(@"C:\projects\Giles\src\Giles.Specs\Giles.Specs.csproj")
.ShouldEqual(@"C:\projects\Giles\src\Giles.Specs\bin\Debug\Giles.Specs.dll");

private It returns_the_assembly_name = () =>
project.GetAssemblyName().ShouldEqual(@"Giles.Specs");
}
}
Loading