Add more tests and some reading logic

This commit is contained in:
Pavel Krymets 2016-03-01 15:11:52 -08:00
parent 3f4c263670
commit 9bd9ca1512
10 changed files with 433 additions and 120 deletions

View file

@ -28,10 +28,11 @@ namespace Microsoft.Extensions.DependencyModel
.Select(export => new Dependency(export.Library.Identity.Name, export.Library.Identity.Version.ToString()))
.ToDictionary(dependency => dependency.Name);
return new DependencyContext(target.DotNetFrameworkName, runtime,
return new DependencyContext(target.DotNetFrameworkName, runtime, false,
GetCompilationOptions(compilerOptions),
GetLibraries(dependencies, dependencyLookup, target, configuration, runtime: false).Cast<CompilationLibrary>().ToArray(),
GetLibraries(dependencies, dependencyLookup, target, configuration, runtime: true).Cast<RuntimeLibrary>().ToArray());
GetLibraries(dependencies, dependencyLookup, target, configuration, runtime: true).Cast<RuntimeLibrary>().ToArray(),
new KeyValuePair<string, string[]>[0]);
}
private static CompilationOptions GetCompilationOptions(CommonCompilerOptions compilerOptions)
@ -115,6 +116,7 @@ namespace Microsoft.Extensions.DependencyModel
export.Library.Identity.Version.ToString(),
export.Library.Hash,
assemblies,
new RuntimeTarget[0],
libraryDependencies.ToArray(),
serviceable
);

View file

@ -46,7 +46,7 @@ namespace Microsoft.Extensions.DependencyModel
public IReadOnlyList<RuntimeLibrary> RuntimeLibraries { get; }
public IReadOnlyList<KeyValuePair<string, string[]>> RuntimeGraph { get; }
public IReadOnlyList<KeyValuePair<string, string[]>> RuntimeGraph { get; }
private static DependencyContext LoadDefault()
{

View file

@ -47,6 +47,7 @@ namespace Microsoft.Extensions.DependencyModel
version: identity.Item3,
hash: identity.Item4,
assemblies: packageGroup.Select(l => l.AssetPath).ToArray(),
subTargets: new RuntimeTarget[0],
dependencies: new Dependency[] { },
serviceable: false
));
@ -55,9 +56,11 @@ namespace Microsoft.Extensions.DependencyModel
return new DependencyContext(
target: string.Empty,
runtime: string.Empty,
isPortable: false,
compilationOptions: CompilationOptions.Default,
compileLibraries: new CompilationLibrary[] {},
runtimeLibraries: runtimeLibraries.ToArray());
runtimeLibraries: runtimeLibraries.ToArray(),
runtimeGraph: new KeyValuePair<string, string[]>[0]);
}
private Tuple<string, string, string, string> PackageIdentity(DepsFileLine line)

View file

@ -28,23 +28,88 @@ namespace Microsoft.Extensions.DependencyModel
private DependencyContext Read(JObject root)
{
string runtime = null;
string target = null;
var runtimeTargetInfo = ReadRuntimeTargetInfo(root);
var libraryStubs = ReadLibraryStubs((JObject) root[DependencyContextStrings.LibrariesPropertyName]);
var targetsObject = (IEnumerable<KeyValuePair<string, JToken>>) root[DependencyContextStrings.TargetsPropertyName];
var runtimeTargetProperty = targetsObject.First(target => IsRuntimeTarget(target.Key));
var compileTargetProperty = targetsObject.First(target => !IsRuntimeTarget(target.Key));
JObject runtimeTarget = null;
JObject compileTarget = null;
if (targetsObject != null)
{
var compileTargetProperty = targetsObject.FirstOrDefault(t => !IsRuntimeTarget(t.Key));
compileTarget = (JObject) compileTargetProperty.Value;
target = compileTargetProperty.Key;
if (!string.IsNullOrEmpty(runtimeTargetInfo.Name))
{
runtimeTarget = (JObject) targetsObject.FirstOrDefault(t => t.Key == runtimeTargetInfo.Name).Value;
if (runtimeTarget == null)
{
throw new FormatException($"Target with name {runtimeTargetInfo.Name} not found");
}
runtime = runtimeTargetInfo.Name.Substring(target.Length + 1);
}
else
{
runtimeTarget = compileTarget;
}
}
return new DependencyContext(
compileTargetProperty.Key,
runtimeTargetProperty.Key.Substring(compileTargetProperty.Key.Length + 1),
target,
runtime,
runtimeTargetInfo.Portable,
ReadCompilationOptions((JObject)root[DependencyContextStrings.CompilationOptionsPropertName]),
ReadLibraries((JObject)compileTargetProperty.Value, false, libraryStubs).Cast<CompilationLibrary>().ToArray(),
ReadLibraries((JObject)runtimeTargetProperty.Value, true, libraryStubs).Cast<RuntimeLibrary>().ToArray()
ReadLibraries(compileTarget, false, libraryStubs).Cast<CompilationLibrary>().ToArray(),
ReadLibraries(runtimeTarget, true, libraryStubs).Cast<RuntimeLibrary>().ToArray(),
ReadRuntimeGraph((JObject)root[DependencyContextStrings.RuntimesPropertyName]).ToArray()
);
}
private IEnumerable<KeyValuePair<string, string[]>> ReadRuntimeGraph(JObject runtimes)
{
if (runtimes == null)
{
yield break;
}
var targets = runtimes.Children();
var runtime = (JProperty)targets.Single();
foreach (var pair in (JObject)runtime.Value)
{
yield return new KeyValuePair<string, string[]>(pair.Key, pair.Value.Values<string>().ToArray());
}
}
private RuntimeTargetInfo ReadRuntimeTargetInfo(JObject root)
{
var runtimeTarget = (JObject)root[DependencyContextStrings.RuntimeTargetPropertyName];
if (runtimeTarget != null)
{
return new RuntimeTargetInfo()
{
Name = runtimeTarget[DependencyContextStrings.RuntimeTargetNamePropertyName]?.Value<string>(),
Portable = runtimeTarget[DependencyContextStrings.PortablePropertyName]?.Value<bool>() == true
};
}
return new RuntimeTargetInfo()
{
Portable = true
};
}
private CompilationOptions ReadCompilationOptions(JObject compilationOptionsObject)
{
if (compilationOptionsObject == null)
{
return CompilationOptions.Default;
}
return new CompilationOptions(
compilationOptionsObject[DependencyContextStrings.DefinesPropertyName]?.Values<string>(),
compilationOptionsObject[DependencyContextStrings.LanguageVersionPropertyName]?.Value<string>(),
@ -63,6 +128,10 @@ namespace Microsoft.Extensions.DependencyModel
private IEnumerable<Library> ReadLibraries(JObject librariesObject, bool runtime, Dictionary<string, LibraryStub> libraryStubs)
{
if (librariesObject == null)
{
return Enumerable.Empty<Library>();
}
return librariesObject.Properties().Select(property => ReadLibrary(property, runtime, libraryStubs));
}
@ -88,7 +157,7 @@ namespace Microsoft.Extensions.DependencyModel
if (runtime)
{
return new RuntimeLibrary(stub.Type, name, version, stub.Hash, assemblies, dependencies, stub.Serviceable);
return new RuntimeLibrary(stub.Type, name, version, stub.Hash, assemblies, new RuntimeTarget[0], dependencies, stub.Serviceable);
}
else
{
@ -98,7 +167,7 @@ namespace Microsoft.Extensions.DependencyModel
private static string[] ReadAssemblies(JObject libraryObject, bool runtime)
{
var assembliesObject = (JObject) libraryObject[runtime ? DependencyContextStrings.RunTimeAssembliesKey : DependencyContextStrings.CompileTimeAssembliesKey];
var assembliesObject = (JObject) libraryObject[runtime ? DependencyContextStrings.RuntimeAssembliesKey : DependencyContextStrings.CompileTimeAssembliesKey];
if (assembliesObject == null)
{
@ -110,7 +179,7 @@ namespace Microsoft.Extensions.DependencyModel
private static Dependency[] ReadDependencies(JObject libraryObject)
{
var dependenciesObject = ((JObject) libraryObject[DependencyContextStrings.DependenciesPropertyName]);
var dependenciesObject = (JObject) libraryObject[DependencyContextStrings.DependenciesPropertyName];
if (dependenciesObject == null)
{
@ -124,21 +193,31 @@ namespace Microsoft.Extensions.DependencyModel
private Dictionary<string, LibraryStub> ReadLibraryStubs(JObject librariesObject)
{
var libraries = new Dictionary<string, LibraryStub>();
foreach (var libraryProperty in librariesObject)
if (librariesObject != null)
{
var value = (JObject) libraryProperty.Value;
var stub = new LibraryStub
foreach (var libraryProperty in librariesObject)
{
Name = libraryProperty.Key,
Hash = value[DependencyContextStrings.Sha512PropertyName]?.Value<string>(),
Type = value[DependencyContextStrings.TypePropertyName].Value<string>(),
Serviceable = value[DependencyContextStrings.ServiceablePropertyName]?.Value<bool>() == true
};
libraries.Add(stub.Name, stub);
var value = (JObject) libraryProperty.Value;
var stub = new LibraryStub
{
Name = libraryProperty.Key,
Hash = value[DependencyContextStrings.Sha512PropertyName]?.Value<string>(),
Type = value[DependencyContextStrings.TypePropertyName].Value<string>(),
Serviceable = value[DependencyContextStrings.ServiceablePropertyName]?.Value<bool>() == true
};
libraries.Add(stub.Name, stub);
}
}
return libraries;
}
private struct RuntimeTargetInfo
{
public string Name;
public bool Portable;
}
private struct LibraryStub
{
public string Name;

View file

@ -9,7 +9,9 @@ namespace Microsoft.Extensions.DependencyModel
internal const string CompileTimeAssembliesKey = "compile";
internal const string RunTimeAssembliesKey = "runtime";
internal const string RuntimeAssembliesKey = "runtime";
internal const string RuntimeTargetPropertyName = "runtimeTarget";
internal const string LibrariesPropertyName = "libraries";
@ -48,5 +50,11 @@ namespace Microsoft.Extensions.DependencyModel
internal const string EmitEntryPointPropertyName = "emitEntryPoint";
internal const string GenerateXmlDocumentationPropertyName = "xmlDoc";
internal const string PortablePropertyName = "portable";
internal const string RuntimeTargetNamePropertyName = "name";
internal const string RuntimesPropertyName = "runtimes";
}
}
}

View file

@ -5,6 +5,7 @@ using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.Extensions.PlatformAbstractions;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
@ -26,9 +27,31 @@ namespace Microsoft.Extensions.DependencyModel
private JObject Write(DependencyContext context)
{
return new JObject(
new JProperty(DependencyContextStrings.RuntimeTargetPropertyName, WriteRuntimeTargetInfo(context)),
new JProperty(DependencyContextStrings.CompilationOptionsPropertName, WriteCompilationOptions(context.CompilationOptions)),
new JProperty(DependencyContextStrings.TargetsPropertyName, WriteTargets(context)),
new JProperty(DependencyContextStrings.LibrariesPropertyName, WriteLibraries(context))
new JProperty(DependencyContextStrings.LibrariesPropertyName, WriteLibraries(context)),
new JProperty(DependencyContextStrings.RuntimesPropertyName, WriteRuntimeGraph(context))
);
}
private JObject WriteRuntimeTargetInfo(DependencyContext context)
{
return new JObject(
new JProperty(DependencyContextStrings.RuntimeTargetNamePropertyName,
context.Target + DependencyContextStrings.VersionSeperator + context.Runtime),
new JProperty(DependencyContextStrings.PortablePropertyName, context.IsPortable)
);
}
private JObject WriteRuntimeGraph(DependencyContext context)
{
return new JObject(
new JProperty(context.Target,
new JObject(
context.RuntimeGraph.Select(g => new JProperty(g.Key, new JArray(g.Value)))
)
)
);
}
@ -106,7 +129,7 @@ namespace Microsoft.Extensions.DependencyModel
var runtimeLibrary = library as RuntimeLibrary;
if (runtimeLibrary != null)
{
propertyName = DependencyContextStrings.RunTimeAssembliesKey;
propertyName = DependencyContextStrings.RuntimeAssembliesKey;
assemblies = runtimeLibrary.Assemblies.Select(assembly => assembly.Path).ToArray();
}
else

View file

@ -0,0 +1,141 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FluentAssertions;
using Xunit;
namespace Microsoft.Extensions.DependencyModel.Tests
{
public class DependencyContextJsonReaderTest
{
private DependencyContext Read(string text)
{
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(text)))
{
return new DependencyContextJsonReader().Read(stream);
}
}
[Fact]
public void ReadsRuntimeTargetInfo()
{
var context = Read(
@"{
""runtimeTarget"": {
""portable"": false,
""name"": "".NETStandardApp,Version=v1.5/osx.10.10-x64"",
},
""targets"": {
"".NETStandardApp,Version=v1.5"": {},
"".NETStandardApp,Version=v1.5/osx.10.10-x64"": {},
}
}");
context.IsPortable.Should().BeFalse();
context.Target.Should().Be(".NETStandardApp,Version=v1.5");
context.Runtime.Should().Be("osx.10.10-x64");
}
[Fact]
public void DefaultsToPortable()
{
var context = Read(
@"{
}");
context.IsPortable.Should().BeTrue();
}
[Fact]
public void ReadsMainTarget()
{
var context = Read(
@"{
""targets"": {
"".NETStandardApp,Version=v1.5"": {}
}
}");
context.Target.Should().Be(".NETStandardApp,Version=v1.5");
}
[Fact]
public void ReadsRuntimeGraph()
{
var context = Read(
@"{
""runtimes"": {
"".NETStandardApp,Version=v1.5"": {
""osx.10.10-x64"": [ ],
""osx.10.11-x64"": [ ""osx"" ],
""rhel.7-x64"": [ ""linux-x64"", ""unix"" ]
}
}
}");
context.RuntimeGraph.Should().Contain(p => p.Key == "osx.10.10-x64").Which
.Value.Should().BeEquivalentTo();
context.RuntimeGraph.Should().Contain(p => p.Key == "osx.10.11-x64").Which
.Value.Should().BeEquivalentTo("osx");
context.RuntimeGraph.Should().Contain(p => p.Key == "rhel.7-x64").Which
.Value.Should().BeEquivalentTo("linux-x64", "unix");
}
[Fact]
public void ReadsCompilationTarget()
{
var context = Read(
@"{
""targets"": {
"".NETStandardApp,Version=v1.5"": {
""MyApp/1.0.1"": {
""dependencies"": {
""AspNet.Mvc"": ""1.0.0""
},
""compile"": {
""MyApp.dll"": { }
}
},
""System.Banana/1.0.0"": {
""dependencies"": {
""System.Foo"": ""1.0.0""
},
""compile"": {
""ref/dotnet5.4/System.Banana.dll"": { }
}
}
}
},
""libraries"":{
""MyApp/1.0.1"": {
""type"": ""project"",
""serviceable"": true,
""sha512"": ""HASH-MyApp""
},
""System.Banana/1.0.0"": {
""type"": ""package"",
""serviceable"": false,
""sha512"": ""HASH-System.Banana""
},
}
}");
context.CompileLibraries.Should().HaveCount(2);
var project = context.CompileLibraries.Should().Contain(l => l.PackageName == "MyApp").Subject;
project.Version.Should().Be("1.0.1");
project.Assemblies.Should().BeEquivalentTo("MyApp.dll");
project.Hash.Should().Be("HASH-MyApp");
project.LibraryType.Should().Be("project");
project.Serviceable.Should().Be(true);
project.Hash.Should().BeEquivalentTo("HASH-MyApp");
var package = context.CompileLibraries.Should().Contain(l => l.PackageName == "System.Banana").Subject;
package.Version.Should().Be("1.0.0");
package.Assemblies.Should().BeEquivalentTo("ref/dotnet5.4/System.Banana.dll");
package.Hash.Should().Be("HASH-System.Banana");
package.LibraryType.Should().Be("package");
package.Serviceable.Should().Be(false);
}
}
}

View file

@ -0,0 +1,102 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Xunit;
using FluentAssertions;
namespace Microsoft.Extensions.DependencyModel.Tests
{
public class DependencyContextJsonWriterTests
{
public JObject Save(DependencyContext dependencyContext)
{
using (var memoryStream = new MemoryStream())
{
new DependencyContextWriter().Write(dependencyContext, memoryStream);
using (var readStream = new MemoryStream(memoryStream.ToArray()))
{
using (var textReader = new StreamReader(readStream))
{
using (var reader = new JsonTextReader(textReader))
{
return JObject.Load(reader);
}
}
}
}
}
[Fact]
public void SavesRuntimeGraph()
{
var result = Save(new DependencyContext(
"Target",
"Target/runtime",
false,
CompilationOptions.Default,
new CompilationLibrary[0],
new RuntimeLibrary[0],
new[]
{
new KeyValuePair<string, string[]>("win7-x64", new [] { "win6", "win5"}),
new KeyValuePair<string, string[]>("win8-x64", new [] { "win7-x64"}),
}));
var runtimes = result.Should().HaveProperty("runtimes")
.Subject.Should().BeOfType<JObject>().Subject;
var rids = runtimes.Should().HaveProperty("Target")
.Subject.Should().BeOfType<JObject>().Subject;
rids.Should().HaveProperty("win7-x64")
.Subject.Should().BeOfType<JArray>()
.Which.Values<string>().ShouldBeEquivalentTo(new[] { "win6", "win5" });
rids.Should().HaveProperty("win8-x64")
.Subject.Should().BeOfType<JArray>()
.Which.Values<string>().ShouldBeEquivalentTo(new[] { "win7-x64" });
}
[Fact]
public void WritesRuntimeTargetPropertyIfNotPortable()
{
var result = Save(new DependencyContext(
"Target",
"runtime",
false,
CompilationOptions.Default,
new CompilationLibrary[0],
new RuntimeLibrary[0],
new KeyValuePair<string, string[]>[0])
);
var runtimeTarget = result.Should().HaveProperty("runtimeTarget")
.Subject.Should().BeOfType<JObject>().Subject;
runtimeTarget.Should().HaveProperty("name")
.Subject.Value<string>().Should().Be("Target/runtime");
runtimeTarget.Should().HaveProperty("portable")
.Subject.Value<bool>().Should().Be(false);
}
[Fact]
public void DoesNotWritesRuntimeTargetPropertyIfPortable()
{
var result = Save(new DependencyContext(
"Target",
"runtime",
false,
CompilationOptions.Default,
new CompilationLibrary[0],
new RuntimeLibrary[0],
new KeyValuePair<string, string[]>[0])
);
result.Should().NotHaveProperty("runtimeTarget");
}
}
}

View file

@ -1,94 +0,0 @@
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Linq;
using System.Collections.Generic;
using System.IO;
using Microsoft.Extensions.EnvironmentAbstractions;
namespace Microsoft.Extensions.DependencyModel.Tests
{
class FileSystemMockBuilder
{
private Dictionary<string, string> _files = new Dictionary<string, string>();
public static IFileSystem Empty { get; } = Create().Build();
public static FileSystemMockBuilder Create()
{
return new FileSystemMockBuilder();
}
public FileSystemMockBuilder AddFile(string name, string content = "")
{
_files.Add(name, content);
return this;
}
public FileSystemMockBuilder AddFiles(string basePath, params string[] files)
{
foreach (var file in files)
{
AddFile(Path.Combine(basePath, file));
}
return this;
}
public IFileSystem Build()
{
return new FileSystemMock(_files);
}
private class FileSystemMock : IFileSystem
{
public FileSystemMock(Dictionary<string, string> files)
{
File = new FileMock(files);
Directory = new DirectoryMock(files);
}
public IFile File { get; }
public IDirectory Directory { get; }
}
private class FileMock : IFile
{
private Dictionary<string, string> _files;
public FileMock(Dictionary<string, string> files)
{
_files = files;
}
public bool Exists(string path)
{
return _files.ContainsKey(path);
}
public string ReadAllText(string path)
{
string text;
if (!_files.TryGetValue(path, out text))
{
throw new FileNotFoundException(path);
}
return text;
}
}
private class DirectoryMock : IDirectory
{
private Dictionary<string, string> _files;
public DirectoryMock(Dictionary<string, string> files)
{
_files = files;
}
public bool Exists(string path)
{
return _files.Keys.Any(k => k.StartsWith(path));
}
}
}
}

View file

@ -0,0 +1,49 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using FluentAssertions;
using FluentAssertions.Execution;
using FluentAssertions.Primitives;
using Newtonsoft.Json.Linq;
namespace Microsoft.Extensions.DependencyModel.Tests
{
public static class JsonAssertionExtensions
{
public static JsonAssetions Should(this JToken jToken)
{
return new JsonAssetions(jToken);
}
}
public class JsonAssetions: ReferenceTypeAssertions<JToken, JsonAssetions>
{
public JsonAssetions(JToken token)
{
Subject = token;
}
protected override string Context => nameof(JToken);
public AndWhichConstraint<JsonAssetions, JToken> HaveProperty(string expected)
{
var token = Subject[expected];
Execute.Assertion
.ForCondition(token != null)
.FailWith($"Expected {Subject} to have property '" + expected + "'");
return new AndWhichConstraint<JsonAssetions, JToken>(this, token);
}
public AndConstraint<JsonAssetions> NotHaveProperty(string expected)
{
var token = Subject[expected];
Execute.Assertion
.ForCondition(token == null)
.FailWith($"Expected {Subject} not to have property '" + expected + "'");
return new AndConstraint<JsonAssetions>(this);
}
}
}