Imported Upstream version 3.6.0

Former-commit-id: da6be194a6b1221998fc28233f2503bd61dd9d14
This commit is contained in:
Jo Shields
2014-08-13 10:39:27 +01:00
commit a575963da9
50588 changed files with 8155799 additions and 0 deletions

View File

@@ -0,0 +1,399 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Specialized;
using System.IO;
using System.Text;
using System.Web.Helpers;
using System.Web.Hosting;
using System.Web.Security;
using Moq;
using Xunit;
using Assert = Microsoft.TestCommon.AssertEx;
namespace System.Web.WebPages.Administration.Test
{
public class AdminPackageTest
{
[Fact]
public void GetAdminVirtualPathThrowsIfPathIsNull()
{
// Act & Assert
Assert.ThrowsArgumentNull(() => SiteAdmin.GetVirtualPath(null), "virtualPath");
}
[Fact]
public void GetAdminVirtualPathDoesNotAppendAdminVirtualPathIfPathStartsWithAdminVirtualPath()
{
// Act
string vpath = SiteAdmin.GetVirtualPath("~/_Admin/Foo");
// Assert
Assert.Equal("~/_Admin/Foo", vpath);
}
[Fact]
public void GetAdminVirtualPathAppendsAdminVirtualPath()
{
// Act
string vpath = SiteAdmin.GetVirtualPath("~/Foo");
// Assert
Assert.Equal("~/_Admin/Foo", vpath);
}
[Fact]
public void SetAuthCookieAddsAuthCookieToResponseCollection()
{
// Arrange
var mockResponse = new Mock<HttpResponseBase>();
var cookies = new HttpCookieCollection();
mockResponse.Setup(m => m.Cookies).Returns(cookies);
// Act
AdminSecurity.SetAuthCookie(mockResponse.Object);
// Assert
Assert.NotNull(cookies[".ASPXADMINAUTH"]);
}
[Fact]
public void GetAuthAdminCookieCreatesAnAuthTicketWithUserDataSetToAdmin()
{
// Arrange
var cookie = AdminSecurity.GetAuthCookie();
// Act
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
// Assert
Assert.Equal(".ASPXADMINAUTH", cookie.Name);
Assert.True(cookie.HttpOnly);
Assert.Equal(2, ticket.Version);
Assert.Equal("ADMIN", ticket.UserData);
}
[Fact]
public void IsAuthenticatedReturnsFalseIfAuthCookieNotInCollection()
{
// Arrange
var mockRequest = new Mock<HttpRequestBase>();
var cookies = new HttpCookieCollection();
mockRequest.Setup(m => m.Cookies).Returns(cookies);
// Act
bool authorized = AdminSecurity.IsAuthenticated(mockRequest.Object);
// Assert
Assert.False(authorized);
}
[Fact]
public void IsAuthenticatedReturnsFalseIfAuthCookieInCollectionAndIsNotAValidAdminAuthCookie()
{
// Arrange
var mockRequest = new Mock<HttpRequestBase>();
var cookies = new HttpCookieCollection();
mockRequest.Setup(m => m.Cookies).Returns(cookies);
cookies.Add(new HttpCookie(".ASPXADMINAUTH", "test"));
// Act
bool authorized = AdminSecurity.IsAuthenticated(mockRequest.Object);
// Assert
Assert.False(authorized);
}
[Fact]
public void IsAuthenticatedReturnsTrueIfAuthCookieIsValid()
{
// Arrange
var mockRequest = new Mock<HttpRequestBase>();
var cookies = new HttpCookieCollection();
mockRequest.Setup(m => m.Cookies).Returns(cookies);
cookies.Add(AdminSecurity.GetAuthCookie());
// Act
bool authorized = AdminSecurity.IsAuthenticated(mockRequest.Object);
// Assert
Assert.True(authorized);
}
[Fact]
public void GetRedirectUrlAppendsAppRelativePathAsReturnUrl()
{
// Arrange
var mockRequest = new Mock<HttpRequestBase>();
mockRequest.Setup(m => m.RawUrl).Returns("~/_Admin/foo/bar/baz");
mockRequest.Setup(m => m.QueryString).Returns(new NameValueCollection());
// Act
string redirectUrl = SiteAdmin.GetRedirectUrl(mockRequest.Object, "register", MakeAppRelative);
// Assert
Assert.Equal("~/_Admin/register?ReturnUrl=%7e%2f_Admin%2ffoo%2fbar%2fbaz", redirectUrl);
}
[Fact]
public void GetRedirectUrlDoesNotAppendsAppRelativePathAsReturnUrlIfAlreadyExists()
{
// Arrange
var mockRequest = new Mock<HttpRequestBase>();
mockRequest.Setup(m => m.RawUrl).Returns("~/_Admin/foo/bar/baz?ReturnUrl=~/foo");
var queryString = new NameValueCollection();
queryString["ReturnUrl"] = "~/foo";
mockRequest.Setup(m => m.QueryString).Returns(queryString);
// Act
string redirectUrl = SiteAdmin.GetRedirectUrl(mockRequest.Object, "register", MakeAppRelative);
// Assert
Assert.Equal("~/_Admin/register?ReturnUrl=%7e%2ffoo", redirectUrl);
}
[Fact]
public void GetReturnUrlReturnsNullIfNotSet()
{
// Arrange
var mockRequest = new Mock<HttpRequestBase>();
mockRequest.Setup(m => m.QueryString).Returns(new NameValueCollection());
// Act
string returlUrl = SiteAdmin.GetReturnUrl(mockRequest.Object);
// Assert
Assert.Null(returlUrl);
}
[Fact]
public void GetReturnUrlThrowsIfReturnUrlIsNotAppRelative()
{
// Arrange
var mockRequest = new Mock<HttpRequestBase>();
var queryString = new NameValueCollection();
queryString["ReturnUrl"] = "http://www.bing.com";
mockRequest.Setup(m => m.QueryString).Returns(queryString);
// Act & Assert
Assert.Throws<InvalidOperationException>(() => SiteAdmin.GetReturnUrl(mockRequest.Object), "The return URL specified for request redirection is invalid.");
}
[Fact]
public void GetReturnUrlReturnsReturlUrlQueryStringParameterIfItIsAppRelative()
{
// Arrange
var mockRequest = new Mock<HttpRequestBase>();
var queryString = new NameValueCollection();
queryString["ReturnUrl"] = "~/_Admin/bar?foo=1";
mockRequest.Setup(m => m.QueryString).Returns(queryString);
// Act
string returnUrl = SiteAdmin.GetReturnUrl(mockRequest.Object);
// Assert
Assert.Equal("~/_Admin/bar?foo=1", returnUrl);
}
[Fact]
public void SaveAdminPasswordUsesCryptoToWritePasswordAndSalt()
{
// Arrange
var password = "some-random-password";
MemoryStream ms = new MemoryStream();
// Act
bool passwordSaved = AdminSecurity.SaveTemporaryPassword(password, () => ms);
// Assert
Assert.True(passwordSaved);
string savedPassword = Encoding.Default.GetString(ms.ToArray());
// Trim everything after the new line. Cannot use the properties from the stream since it is already closed by the writer.
savedPassword = savedPassword.Substring(0, savedPassword.IndexOf(Environment.NewLine));
Assert.True(Crypto.VerifyHashedPassword(savedPassword, password));
}
[Fact]
public void SaveAdminPasswordReturnsFalseIfGettingStreamThrowsUnauthorizedAccessException()
{
// Act
bool passwordSaved = AdminSecurity.SaveTemporaryPassword("password", () => { throw new UnauthorizedAccessException(); });
// Assert
Assert.False(passwordSaved);
}
[Fact]
public void CheckPasswordReturnsTrueIfPasswordIsValid()
{
// Arrange
var ms = new MemoryStream();
var writer = new StreamWriter(ms);
writer.WriteLine(Crypto.HashPassword("password"));
writer.Flush();
ms.Seek(0, SeekOrigin.Begin);
// Act
bool passwordIsValid = AdminSecurity.CheckPassword("password", () => ms);
// Assert
Assert.True(passwordIsValid);
writer.Close();
}
[Fact]
public void HasAdminPasswordReturnsTrueIfAdminPasswordFileExists()
{
// Arrange
Mock<VirtualPathProvider> mockVpp = new Mock<VirtualPathProvider>();
mockVpp.Setup(m => m.FileExists("~/App_Data/Admin/Password.config")).Returns(true);
// Act
bool hasPassword = AdminSecurity.HasAdminPassword(mockVpp.Object);
// Assert
Assert.True(hasPassword);
}
[Fact]
public void HasAdminPasswordReturnsFalseIfAdminPasswordFileDoesNotExists()
{
// Arrange
Mock<VirtualPathProvider> mockVpp = new Mock<VirtualPathProvider>();
mockVpp.Setup(m => m.FileExists("~/App_Data/Admin/Password.config")).Returns(false);
// Act
bool hasPassword = AdminSecurity.HasAdminPassword(mockVpp.Object);
// Assert
Assert.False(hasPassword);
}
[Fact]
public void HasTemporaryPasswordReturnsTrueIfAdminPasswordFileExists()
{
// Arrange
Mock<VirtualPathProvider> mockVpp = new Mock<VirtualPathProvider>();
mockVpp.Setup(m => m.FileExists("~/App_Data/Admin/_Password.config")).Returns(true);
// Act
bool hasPassword = AdminSecurity.HasTemporaryPassword(mockVpp.Object);
// Assert
Assert.True(hasPassword);
}
[Fact]
public void HasTemporaryPasswordReturnsFalseIfAdminPasswordFileDoesNotExists()
{
// Arrange
Mock<VirtualPathProvider> mockVpp = new Mock<VirtualPathProvider>();
mockVpp.Setup(m => m.FileExists("~/App_Data/Admin/_Password.config")).Returns(false);
// Act
bool hasPassword = AdminSecurity.HasTemporaryPassword(mockVpp.Object);
// Assert
Assert.False(hasPassword);
}
[Fact]
public void NoPasswordOrTemporaryPasswordRedirectsToRegisterPage()
{
AssertSecure(requestUrl: "~/",
passwordExists: false,
temporaryPasswordExists: false,
expectedUrl: "~/_Admin/Register.cshtml?ReturnUrl=%7e%2f");
}
[Fact]
public void IfPasswordExistsRedirectsToLoginPage()
{
AssertSecure(requestUrl: "~/",
passwordExists: true,
temporaryPasswordExists: false,
expectedUrl: "~/_Admin/Login.cshtml?ReturnUrl=%7e%2f");
}
[Fact]
public void IfPasswordExistsRedirectsToLoginPageEvenIfTemporaryPasswordFileExists()
{
AssertSecure(requestUrl: "~/",
passwordExists: true,
temporaryPasswordExists: true,
expectedUrl: "~/_Admin/Login.cshtml?ReturnUrl=%7e%2f");
}
[Fact]
public void IfTemporaryPasswordExistsRedirectsToInstructionsPage()
{
AssertSecure(requestUrl: "~/",
passwordExists: false,
temporaryPasswordExists: true,
expectedUrl: "~/_Admin/EnableInstructions.cshtml?ReturnUrl=%7e%2f");
}
[Fact]
public void NoRedirectIfAlreadyGoingToRedirectPage()
{
AssertSecure(requestUrl: "~/_Admin/Register.cshtml",
passwordExists: false,
temporaryPasswordExists: false,
expectedUrl: null);
AssertSecure(requestUrl: "~/_Admin/Login.cshtml",
passwordExists: true,
temporaryPasswordExists: false,
expectedUrl: null);
AssertSecure(requestUrl: "~/_Admin/EnableInstructions.cshtml",
passwordExists: false,
temporaryPasswordExists: true,
expectedUrl: null);
}
private static void AssertSecure(string requestUrl, bool passwordExists, bool temporaryPasswordExists, string expectedUrl)
{
// Arrange
var vpp = new Mock<VirtualPathProvider>();
if (temporaryPasswordExists)
{
vpp.Setup(m => m.FileExists("~/App_Data/Admin/_Password.config")).Returns(true);
}
if (passwordExists)
{
vpp.Setup(m => m.FileExists("~/App_Data/Admin/Password.config")).Returns(true);
}
string redirectUrl = null;
var response = new Mock<HttpResponseBase>();
response.Setup(m => m.Redirect(It.IsAny<string>())).Callback<string>(url => redirectUrl = url);
var request = new Mock<HttpRequestBase>();
request.Setup(m => m.QueryString).Returns(new NameValueCollection());
request.Setup(m => m.RawUrl).Returns(requestUrl);
var cookies = new HttpCookieCollection();
request.Setup(m => m.Cookies).Returns(cookies);
var context = new Mock<HttpContextBase>();
context.Setup(m => m.Request).Returns(request.Object);
context.Setup(m => m.Response).Returns(response.Object);
var startPage = new Mock<StartPage>() { CallBase = true };
var page = new Mock<WebPageRenderingBase>();
page.Setup(m => m.VirtualPath).Returns(requestUrl);
startPage.Object.ChildPage = page.Object;
page.Setup(m => m.Context).Returns(context.Object);
// Act
AdminSecurity.Authorize(startPage.Object, vpp.Object, MakeAppRelative);
// Assert
Assert.Equal(expectedUrl, redirectUrl);
}
private static string MakeAppRelative(string path)
{
return path;
}
}
}

View File

@@ -0,0 +1,152 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Linq;
using System.Web.WebPages.Administration.PackageManager;
using Moq;
using Xunit;
namespace System.Web.WebPages.Administration.Test
{
public class PackageManagerModuleTest
{
[Fact]
public void InitSourceFileDoesNotAffectSourcesFileWhenFeedIsNotNull()
{
// Arrange
bool sourceFileCalled = false;
var sourceFile = GetPackagesSourceFile();
sourceFile.Setup(s => s.Exists()).Returns(false);
sourceFile.Setup(s => s.WriteSources(It.IsAny<IEnumerable<WebPackageSource>>())).Callback(() => sourceFileCalled = true);
sourceFile.Setup(c => c.ReadSources()).Callback(() => sourceFileCalled = true);
ISet<WebPackageSource> set = new HashSet<WebPackageSource>();
// Act
PackageManagerModule.InitPackageSourceFile(sourceFile.Object, ref set);
// Assert
Assert.False(sourceFileCalled);
}
[Fact]
public void InitSourceFileWritesToDiskIfSourcesFileDoesNotExist()
{
// Arrange
ISet<WebPackageSource> set = null;
var sourceFile = GetPackagesSourceFile();
sourceFile.Setup(s => s.Exists()).Returns(false);
sourceFile.Setup(s => s.WriteSources(It.IsAny<IEnumerable<WebPackageSource>>()));
// Act
PackageManagerModule.InitPackageSourceFile(sourceFile.Object, ref set);
Assert.NotNull(set);
Assert.Equal(set.Count(), 2);
Assert.Equal(set.First().Source, "http://go.microsoft.com/fwlink/?LinkID=226946");
Assert.Equal(set.Last().Source, "http://go.microsoft.com/fwlink/?LinkID=226948");
}
[Fact]
public void InitSourceFileReadsFromDiskWhenFileAlreadyExists()
{
// Arrange
var sourceFile = GetPackagesSourceFile();
sourceFile.Setup(s => s.Exists()).Returns(true);
ISet<WebPackageSource> set = null;
// Act
PackageManagerModule.InitPackageSourceFile(sourceFile.Object, ref set);
// Assert
Assert.NotNull(set);
Assert.Equal(set.Count(), 2);
}
[Fact]
public void AddFeedWritesSourceIfItDoesNotExist()
{
// Arrange
bool writeCalled = false;
var sourceFile = GetPackagesSourceFile();
sourceFile.Setup(c => c.WriteSources(It.IsAny<IEnumerable<WebPackageSource>>())).Callback(() => writeCalled = true);
ISet<WebPackageSource> set = new HashSet<WebPackageSource>(GetSources());
// Act
bool returnValue = PackageManagerModule.AddPackageSource(sourceFile.Object, set, new WebPackageSource(source: "http://www.microsoft.com/feed3", name: "Feed3"));
// Assert
Assert.Equal(set.Count(), 3);
Assert.True(writeCalled);
Assert.True(returnValue);
}
[Fact]
public void AddFeedDoesNotWritesSourceIfExists()
{
// Arrange
bool writeCalled = false;
var sourceFile = GetPackagesSourceFile();
sourceFile.Setup(c => c.WriteSources(It.IsAny<IEnumerable<WebPackageSource>>())).Callback(() => writeCalled = true);
ISet<WebPackageSource> set = new HashSet<WebPackageSource>(GetSources());
// Act
bool returnValue = PackageManagerModule.AddPackageSource(sourceFile.Object, set, new WebPackageSource(source: "http://www.microsoft.com/feed1", name: "Feed1"));
// Assert
Assert.Equal(set.Count(), 2);
Assert.False(writeCalled);
Assert.False(returnValue);
}
[Fact]
public void RemoveFeedRemovesSourceFromSet()
{
// Arrange
bool writeCalled = false;
var sourceFile = GetPackagesSourceFile();
sourceFile.Setup(c => c.WriteSources(It.IsAny<IEnumerable<WebPackageSource>>())).Callback(() => writeCalled = true);
ISet<WebPackageSource> set = new HashSet<WebPackageSource>(GetSources());
// Act
PackageManagerModule.RemovePackageSource(sourceFile.Object, set, "feed1");
// Assert
Assert.Equal(set.Count(), 1);
Assert.False(set.Any(s => s.Name == "Feed1"));
Assert.True(writeCalled);
}
[Fact]
public void RemoveFeedDoesNotAffectSourceFileIsFeedDoesNotExist()
{
// Arrange
bool writeCalled = false;
var sourceFile = GetPackagesSourceFile();
sourceFile.Setup(c => c.WriteSources(It.IsAny<IEnumerable<WebPackageSource>>())).Callback(() => writeCalled = true);
ISet<WebPackageSource> set = new HashSet<WebPackageSource>(GetSources());
// Act
PackageManagerModule.RemovePackageSource(sourceFile.Object, set, "feed3");
// Assert
Assert.Equal(set.Count(), 2);
Assert.False(writeCalled);
}
private static Mock<IPackagesSourceFile> GetPackagesSourceFile()
{
var sourceFile = new Mock<IPackagesSourceFile>();
sourceFile.Setup(c => c.ReadSources()).Returns(GetSources());
return sourceFile;
}
private static IEnumerable<WebPackageSource> GetSources()
{
return new[]
{
new WebPackageSource(name: "Feed1", source: "http://www.microsoft.com/feed1"),
new WebPackageSource(name: "Feed2", source: "http://www.microsoft.com/feed2")
};
}
}
}

View File

@@ -0,0 +1,147 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.IO;
using System.Linq;
using System.Text;
using System.Web.WebPages.Administration.PackageManager;
using System.Xml.Linq;
using Xunit;
namespace System.Web.WebPages.Administration.Test
{
public class PackagesSourceFileTest
{
[Fact]
public void PackagesSourceFileThrowsIfTheXmlElementDoesNotContainNameAndUrl()
{
// Arrange
var element = new XElement("source");
// Act and Assert
Assert.Throws<FormatException>(() => PackageSourceFile.ParsePackageSource(element));
}
[Fact]
public void PackagesSourceFileThrowsIfTheXmlElementDoesNotContainUrl()
{
// Arrange
var element = new XElement("source", new XAttribute("displayname", "foo"), new XAttribute("filterpreferred", false));
// Act and Assert
Assert.Throws<FormatException>(() => PackageSourceFile.ParsePackageSource(element));
}
[Fact]
public void PackagesSourceFileThrowsIfTheXmlElementDoesNotContainName()
{
// Arrange
var element = new XElement("source", new XAttribute("url", "http://microsoft.com"), new XAttribute("filterpreferred", false));
// Act and Assert
Assert.Throws<FormatException>(() => PackageSourceFile.ParsePackageSource(element));
}
[Fact]
public void PackagesSourceFileDoesNotThrowIfXmlElementDoesNotContainPreferred()
{
// Arrange
var element = new XElement("source", new XAttribute("displayname", "foo"), new XAttribute("url", "http://microsoft.com"));
// Act
var item = PackageSourceFile.ParsePackageSource(element);
// Assert
Assert.NotNull(item);
}
[Fact]
public void PackagesSourceFileThrowsIfTheFeedUrlIsMalformed()
{
// Arrange
var element = new XElement("source",
new XAttribute("displayname", "foo"),
new XAttribute("url", "bad-url.com"),
new XAttribute("filterpreferred", false)
);
// Act and Assert
Assert.Throws<FormatException>(() => PackageSourceFile.ParsePackageSource(element));
}
[Fact]
public void PackagesSourceFileParsesXElement()
{
// Arrange
var element = new XElement("source",
new XAttribute("displayname", "foo"),
new XAttribute("url", "http://www.microsoft.com"),
new XAttribute("filterpreferred", true)
);
// Act
var WebPackageSource = PackageSourceFile.ParsePackageSource(element);
// Assert
Assert.Equal("foo", WebPackageSource.Name);
Assert.Equal("http://www.microsoft.com", WebPackageSource.Source);
Assert.True(WebPackageSource.FilterPreferredPackages);
}
[Fact]
public void PackagesSourceFileReadsAllFeedsFromStream()
{
// Arrange
var document = new XDocument(
new XElement("sources",
new XElement("source", new XAttribute("displayname", "Feed1"), new XAttribute("url", "http://www.microsoft.com/feed1"), new XAttribute("filterpreferred", true)),
new XElement("source", new XAttribute("displayname", "Feed2"), new XAttribute("url", "http://www.microsoft.com/feed2"), new XAttribute("filterpreferred", true))
));
var stream = new MemoryStream();
document.Save(stream);
stream = new MemoryStream(stream.ToArray());
string xml = new StreamReader(stream).ReadToEnd().TrimEnd('\0');
// Act
var result = PackageSourceFile.ReadFeeds(() => new MemoryStream(Encoding.Default.GetBytes(xml)));
// Assert
Assert.Equal(2, result.Count());
Assert.Equal("Feed1", result.First().Name);
Assert.Equal("Feed2", result.Last().Name);
}
[Fact]
public void PackagesSourceFileWritesAllFeedsToStream()
{
// Arrange
var packagesSources = new[]
{
new WebPackageSource(name: "Feed1", source: "http://www.microsoft.com/Feed1"),
new WebPackageSource(name: "Feed2", source: "http://www.microsoft.com/Feed2") { FilterPreferredPackages = true }
};
var stream = new MemoryStream();
// Act
PackageSourceFile.WriteFeeds(packagesSources, () => stream);
stream = new MemoryStream(stream.ToArray());
string result = new StreamReader(stream).ReadToEnd().TrimEnd('\0');
// Assert
var document = XDocument.Parse(result);
Assert.Equal(document.Root.Name, "sources");
Assert.Equal(document.Root.Elements().Count(), 2);
var firstFeed = document.Root.Elements().First();
Assert.Equal(firstFeed.Name, "source");
Assert.Equal(firstFeed.Attribute("displayname").Value, "Feed1");
Assert.Equal(firstFeed.Attribute("url").Value, "http://www.microsoft.com/Feed1");
Assert.Equal(firstFeed.Attribute("filterpreferred").Value, "false");
var secondFeed = document.Root.Elements().Last();
Assert.Equal(secondFeed.Name, "source");
Assert.Equal(secondFeed.Attribute("displayname").Value, "Feed2");
Assert.Equal(secondFeed.Attribute("url").Value, "http://www.microsoft.com/Feed2");
Assert.Equal(secondFeed.Attribute("filterpreferred").Value, "true");
}
}
}

View File

@@ -0,0 +1,155 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Web.WebPages.Administration.PackageManager;
using Moq;
using Xunit;
namespace System.Web.WebPages.Administration.Test
{
public class PageUtilsTest
{
[Fact]
public void GetFilterValueReturnsNullIfValueWasNotFound()
{
// Arrange
var request = new Mock<HttpRequestBase>();
request.Setup(c => c.QueryString).Returns(new NameValueCollection());
request.Setup(c => c.Cookies).Returns(new HttpCookieCollection());
// Act
var value = PageUtils.GetFilterValue(request.Object, "foo", "my-key");
// Assert
Assert.Null(value);
}
[Fact]
public void GetFilterValueReturnsValueFromCookieIfQueryStringDoesNotContainKey()
{
// Arrange
const string key = "my-key";
const string value = "my-cookie-value";
var request = new Mock<HttpRequestBase>();
request.Setup(c => c.QueryString).Returns(new NameValueCollection());
var cookies = new HttpCookieCollection();
var cookie = new HttpCookie("foo");
cookie[key] = value;
cookies.Add(cookie);
request.Setup(c => c.Cookies).Returns(cookies);
// Act
var returnedValue = PageUtils.GetFilterValue(request.Object, "foo", key);
// Assert
Assert.Equal(value, returnedValue);
}
[Fact]
public void GetFilterValueReturnsValueFromQueryString()
{
// Arrange
const string key = "my-key";
const string requestValue = "my-request-value";
const string cookieValue = "my-cookie-value";
var request = new Mock<HttpRequestBase>();
var queryString = new NameValueCollection();
queryString[key] = requestValue;
request.Setup(c => c.QueryString).Returns(queryString);
var cookies = new HttpCookieCollection();
var cookie = new HttpCookie("foo");
cookie[key] = cookieValue;
request.Setup(c => c.Cookies).Returns(cookies);
// Act
var returnedValue = PageUtils.GetFilterValue(request.Object, "foo", key);
// Assert
Assert.Equal(requestValue, returnedValue);
}
[Fact]
public void PersistFilterCreatesCookieIfItDoesNotExist()
{
// Arrange
var cookies = new HttpCookieCollection();
var response = new Mock<HttpResponseBase>();
response.Setup(c => c.Cookies).Returns(cookies);
// Act
PageUtils.PersistFilter(response.Object, "my-cookie", new Dictionary<string, string>());
// Assert
Assert.NotNull(cookies["my-cookie"]);
}
[Fact]
public void PersistFilterUsesExistingCookie()
{
// Arrange
var cookieName = "my-cookie";
var cookies = new HttpCookieCollection();
cookies.Add(new HttpCookie(cookieName));
var response = new Mock<HttpResponseBase>();
response.Setup(c => c.Cookies).Returns(cookies);
// Act
PageUtils.PersistFilter(response.Object, "my-cookie", new Dictionary<string, string>());
// Assert
Assert.Equal(1, cookies.Count);
}
[Fact]
public void PersistFilterAddsDictionaryEntriesToCookie()
{
// Arrange
var cookies = new HttpCookieCollection();
var response = new Mock<HttpResponseBase>();
response.Setup(c => c.Cookies).Returns(cookies);
// Act
PageUtils.PersistFilter(response.Object, "my-cookie", new Dictionary<string, string>() { { "a", "b" }, { "x", "y" } });
// Assert
var cookie = cookies["my-cookie"];
Assert.Equal(cookie["a"], "b");
Assert.Equal(cookie["x"], "y");
}
[Fact]
public void IsValidLicenseUrlReturnsTrueForHttpUris()
{
// Arrange
var uri = new Uri("http://www.microsoft.com");
// Act and Assert
Assert.True(PageUtils.IsValidLicenseUrl(uri));
}
[Fact]
public void IsValidLicenseUrlReturnsTrueForHttpsUris()
{
// Arrange
var uri = new Uri("HTTPs://www.asp.net");
// Act and Assert
Assert.True(PageUtils.IsValidLicenseUrl(uri));
}
[Fact]
public void IsValidLicenseUrlReturnsFalseForNonHttpUris()
{
// Arrange
var jsUri = new Uri("javascript:alert('Hello world');");
var fileShareUri = new Uri(@"c:\windows\system32\notepad.exe");
var mailToUti = new Uri("mailto:invalid-email@microsoft.com");
// Act and Assert
Assert.False(PageUtils.IsValidLicenseUrl(jsUri));
Assert.False(PageUtils.IsValidLicenseUrl(fileShareUri));
Assert.False(PageUtils.IsValidLicenseUrl(mailToUti));
}
}
}

View File

@@ -0,0 +1,35 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Linq;
using System.Web.WebPages.TestUtils;
using Xunit;
namespace System.Web.WebPages.Administration.Test
{
public class PreApplicationStartCodeTest
{
[Fact]
public void StartTest()
{
AppDomainUtils.RunInSeparateAppDomain(() =>
{
var adminPackageAssembly = typeof(PreApplicationStartCode).Assembly;
AppDomainUtils.SetPreAppStartStage();
PreApplicationStartCode.Start();
// Call a second time to ensure multiple calls do not cause issues
PreApplicationStartCode.Start();
// TODO: Need a way to see if the module was actually registered
var registeredAssemblies = ApplicationPart.GetRegisteredParts().ToList();
Assert.Equal(1, registeredAssemblies.Count);
registeredAssemblies.First().Assembly.Equals(adminPackageAssembly);
});
}
[Fact]
public void TestPreAppStartClass()
{
PreAppStartTestHelper.TestPreAppStartClass(typeof(PreApplicationStartCode));
}
}
}

View File

@@ -0,0 +1,149 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Linq;
using System.Web.WebPages.Administration.PackageManager;
using Moq;
using NuGet.Runtime;
using Xunit;
namespace System.Web.WebPages.Administration.Test
{
public class RemoteAssemblyTest
{
[Fact]
public void GetAssembliesForBindingRedirectReturnsEmptySequenceIfNoBinAssembliesAreFound()
{
// Act
var assemblies = RemoteAssembly.GetAssembliesForBindingRedirect(AppDomain.CurrentDomain, @"x:\site\bin", (_, __) => Enumerable.Empty<IAssembly>());
// Assert
Assert.Empty(assemblies);
}
[Fact]
public void RemoteAssemblyComparesById()
{
// Arrange
var assemblyA = new RemoteAssembly("A", null, null, null);
var assemblyB = new Mock<IAssembly>(MockBehavior.Strict);
assemblyB.SetupGet(b => b.Name).Returns("Z").Verifiable();
// Act
var result = RemoteAssembly.Compare(assemblyA, assemblyB.Object);
// Assert
Assert.Equal(-25, result);
assemblyB.Verify();
}
[Fact]
public void RemoteAssemblyComparesByVersionIfIdsAreIdentical()
{
// Arrange
var assemblyA = new RemoteAssembly("A", new Version("2.0.0.0"), null, null);
var assemblyB = new Mock<IAssembly>(MockBehavior.Strict);
assemblyB.SetupGet(b => b.Name).Returns("A").Verifiable();
assemblyB.SetupGet(b => b.Version).Returns(new Version("1.0.0.0")).Verifiable();
// Act
var result = RemoteAssembly.Compare(assemblyA, assemblyB.Object);
// Assert
Assert.Equal(1, result);
assemblyB.Verify();
}
[Fact]
public void RemoteAssemblyComparesByPublicKeyIfIdsAndVersionAreIdentical()
{
// Arrange
var assemblyA = new RemoteAssembly("A", new Version("1.0.0.0"), "C", null);
var assemblyB = new Mock<IAssembly>(MockBehavior.Strict);
assemblyB.SetupGet(b => b.Name).Returns("A").Verifiable();
assemblyB.SetupGet(b => b.Version).Returns(new Version("1.0.0.0")).Verifiable();
assemblyB.SetupGet(b => b.PublicKeyToken).Returns("E").Verifiable();
// Act
var result = RemoteAssembly.Compare(assemblyA, assemblyB.Object);
// Assert
Assert.Equal(-2, result);
assemblyB.Verify();
}
[Fact]
public void RemoteAssemblyComparesByCultureIfIdVersionAndPublicKeyAreIdentical()
{
// Arrange
var assemblyA = new RemoteAssembly("A", new Version("1.0.0.0"), "public-key", "en-us");
var assemblyB = new Mock<IAssembly>(MockBehavior.Strict);
assemblyB.SetupGet(b => b.Name).Returns("A").Verifiable();
assemblyB.SetupGet(b => b.Version).Returns(new Version("1.0.0.0")).Verifiable();
assemblyB.SetupGet(b => b.PublicKeyToken).Returns("public-key").Verifiable();
assemblyB.SetupGet(b => b.Culture).Returns("en-uk").Verifiable();
// Act
var result = RemoteAssembly.Compare(assemblyA, assemblyB.Object);
// Assert
Assert.Equal(8, result);
assemblyB.Verify();
}
[Fact]
public void RemoteAssemblyReturns0IfAllValuesAreIdentical()
{
// Arrange
var assemblyA = new RemoteAssembly("A", new Version("1.0.0.0"), "public-key", "en-us");
var assemblyB = new RemoteAssembly("A", new Version("1.0.0.0"), "public-key", "en-us");
// Act
var result = RemoteAssembly.Compare(assemblyA, assemblyB);
// Assert
Assert.Equal(0, result);
}
[Fact]
public void RemoteAssemblyReturns1IfValueToBeComparedToIsNull()
{
// Arrange
RemoteAssembly assemblyA = new RemoteAssembly("A", new Version("1.0.0.0"), "public-key", "en-us");
RemoteAssembly assemblyB = null;
// Act
var result = assemblyA.CompareTo(assemblyB);
// Assert
Assert.Equal(1, result);
}
[Fact]
public void EqualReturnsTrueIfValuesAreIdentical()
{
// Arrange
var assemblyA = new RemoteAssembly("A", new Version("1.0.0.0"), "public-key", "en-us");
var assemblyB = new RemoteAssembly("A", new Version("1.0.0.0"), "public-key", "en-us");
// Act
var result = assemblyA.Equals(assemblyB);
// Assert
Assert.True(result);
}
[Fact]
public void EqualReturnsFalseIfValuesAreNotIdentical()
{
// Arrange
var assemblyA = new RemoteAssembly("A", new Version("1.0.0.0"), "public-key", "en-us");
var assemblyB = new RemoteAssembly("A", new Version("1.0.0.1"), "public-key", "en-us");
// Act
var result = assemblyA.Equals(assemblyB);
// Assert
Assert.False(result);
}
}
}

View File

@@ -0,0 +1,102 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),Runtime.sln))\tools\WebStack.settings.targets" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>9.0.30729</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{21C729D6-ECF8-47EF-A236-7C6A4272EAF0}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>System.Web.WebPages.Administration.Test</RootNamespace>
<AssemblyName>System.Web.WebPages.Administration.Test</AssemblyName>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>$(WebStackRootPath)\bin\Debug\Test\</OutputPath>
<DefineConstants>TRACE;DEBUG</DefineConstants>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>$(WebStackRootPath)\bin\Release\Test\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'CodeCoverage' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>$(WebStackRootPath)\bin\CodeCoverage\Test\</OutputPath>
<DefineConstants>TRACE;DEBUG</DefineConstants>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.CSharp" />
<Reference Include="Moq, Version=4.0.10827.0, Culture=neutral, PublicKeyToken=69f491c39445e920, processorArchitecture=MSIL">
<HintPath>..\..\packages\Moq.4.0.10827\lib\NET40\Moq.dll</HintPath>
</Reference>
<Reference Include="NuGet.Core">
<HintPath>..\..\packages\Nuget.Core.1.6.2\lib\net40\NuGet.Core.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Web" />
<Reference Include="System.XML" />
<Reference Include="System.Xml.Linq" />
<Reference Include="xunit">
<HintPath>..\..\packages\xunit.1.9.0.1566\lib\xunit.dll</HintPath>
</Reference>
<Reference Include="xunit.extensions">
<HintPath>..\..\packages\xunit.extensions.1.9.0.1566\lib\xunit.extensions.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<CodeAnalysisDependentAssemblyPaths Condition=" '$(VS100COMNTOOLS)' != '' " Include="$(VS100COMNTOOLS)..\IDE\PrivateAssemblies">
<Visible>False</Visible>
</CodeAnalysisDependentAssemblyPaths>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\System.Web.WebPages.Administration\System.Web.WebPages.Administration.csproj">
<Project>{C23F02FC-4538-43F5-ABBA-38BA069AEA8F}</Project>
<Name>System.Web.WebPages.Administration</Name>
</ProjectReference>
<ProjectReference Include="..\..\src\System.Web.Helpers\System.Web.Helpers.csproj">
<Project>{9B7E3740-6161-4548-833C-4BBCA43B970E}</Project>
<Name>System.Web.Helpers</Name>
</ProjectReference>
<ProjectReference Include="..\..\src\System.Web.WebPages\System.Web.WebPages.csproj">
<Project>{76EFA9C5-8D7E-4FDF-B710-E20F8B6B00D2}</Project>
<Name>System.Web.WebPages</Name>
</ProjectReference>
<ProjectReference Include="..\Microsoft.TestCommon\Microsoft.TestCommon.csproj">
<Project>{FCCC4CB7-BAF7-4A57-9F89-E5766FE536C0}</Project>
<Name>Microsoft.TestCommon</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<Compile Include="AdminPackageTest.cs" />
<Compile Include="PackageManagerModuleTest.cs" />
<Compile Include="PackagesSourceFileTest.cs" />
<Compile Include="PageUtilsTest.cs" />
<Compile Include="PreApplicationStartCodeTest.cs" />
<Compile Include="RemoteAssemblyTest.cs" />
<Compile Include="WebProjectManagerTest.cs" />
<Compile Include="WebProjectSystemTest.cs" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
</Project>

View File

@@ -0,0 +1,162 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Linq;
using System.Web.WebPages.Administration.PackageManager;
using Moq;
using NuGet;
using Xunit;
using Assert = Microsoft.TestCommon.AssertEx;
namespace System.Web.WebPages.Administration.Test
{
public class WebPackageManagerTest
{
[Fact]
public void ConstructorThrowsIfRemoteSourceIsNullOrEmpty()
{
// Act and Assert
Assert.ThrowsArgumentNullOrEmptyString(() => new WebProjectManager((string)null, "foo"), "remoteSource");
Assert.ThrowsArgumentNullOrEmptyString(() => new WebProjectManager("", @"D:\baz"), "remoteSource");
}
[Fact]
public void ConstructorThrowsIfSiteRootIsNullOrEmpty()
{
// Act and Assert
Assert.ThrowsArgumentNullOrEmptyString(() => new WebProjectManager("foo", null), "siteRoot");
Assert.ThrowsArgumentNullOrEmptyString(() => new WebProjectManager("foo", ""), "siteRoot");
}
[Fact]
public void AllowInstallingPackageWithToolsFolderDoNotThrow()
{
// Arrange
var projectManager = new Mock<IProjectManager>();
projectManager.Setup(p => p.AddPackageReference("A", new SemanticVersion("1.0"), false, false)).Verifiable();
var webProjectManager = new WebProjectManager(projectManager.Object, @"x:\")
{
DoNotAddBindingRedirects = true
};
var packageFile1 = new Mock<IPackageFile>();
packageFile1.Setup(p => p.Path).Returns("tools\\install.ps1");
var packageFile2 = new Mock<IPackageFile>();
packageFile2.Setup(p => p.Path).Returns("content\\A.txt");
var package = new Mock<IPackage>();
package.Setup(p => p.Id).Returns("A");
package.Setup(p => p.Version).Returns(new SemanticVersion("1.0"));
package.Setup(p => p.GetFiles()).Returns(new[] { packageFile1.Object, packageFile2.Object });
// Act
webProjectManager.InstallPackage(package.Object, appDomain: null);
// Assert
projectManager.Verify();
}
[Fact]
public void GetLocalRepositoryReturnsPackagesFolderUnderAppData()
{
// Arrange
var siteRoot = "my-site";
// Act
var repositoryFolder = WebProjectManager.GetWebRepositoryDirectory(siteRoot);
Assert.Equal(repositoryFolder, @"my-site\App_Data\packages");
}
[Fact]
public void GetPackagesReturnsAllItemsWhenNoSearchTermIsIncluded()
{
// Arrange
var repository = GetRepository();
// Act
var result = WebProjectManager.GetPackages(repository, String.Empty);
// Assert
Assert.Equal(3, result.Count());
}
[Fact]
public void GetPackagesReturnsItemsContainingSomeSearchToken()
{
// Arrange
var repository = GetRepository();
// Act
var result = WebProjectManager.GetPackages(repository, "testing .NET");
var package = result.SingleOrDefault();
// Assert
Assert.NotNull(package);
Assert.Equal(package.Id, "A");
}
[Fact]
public void GetPackagesWithLicenseReturnsAllDependenciesWithRequiresAcceptance()
{
// Arrange
var remoteRepository = GetRepository();
var localRepository = new Mock<IPackageRepository>().Object;
// Act
var package = remoteRepository.GetPackages().Find("C").SingleOrDefault();
var result = WebProjectManager.GetPackagesRequiringLicenseAcceptance(package, localRepository, remoteRepository);
// Assert
Assert.Equal(2, result.Count());
Assert.True(result.Any(c => c.Id == "C"));
Assert.True(result.Any(c => c.Id == "B"));
}
[Fact]
public void GetPackagesWithLicenseReturnsEmptyResultForPackageThatDoesNotRequireLicenses()
{
// Arrange
var remoteRepository = GetRepository();
var localRepository = new Mock<IPackageRepository>().Object;
// Act
var package = remoteRepository.GetPackages().Find("A").SingleOrDefault();
var result = WebProjectManager.GetPackagesRequiringLicenseAcceptance(package, localRepository, remoteRepository);
// Assert
Assert.False(result.Any());
}
private static IPackageRepository GetRepository()
{
Mock<IPackageRepository> repository = new Mock<IPackageRepository>();
var packages = new[]
{
GetPackage("A", desc: "testing"),
GetPackage("B", version: "1.1", requiresLicense: true),
GetPackage("C", requiresLicense: true, dependencies: new[]
{
new PackageDependency("B", new VersionSpec { MinVersion = new SemanticVersion("1.0") })
})
};
repository.Setup(c => c.GetPackages()).Returns(packages.AsQueryable());
return repository.Object;
}
private static IPackage GetPackage(string id, string version = "1.0", string desc = null, bool requiresLicense = false, IEnumerable<PackageDependency> dependencies = null)
{
Mock<IPackage> package = new Mock<IPackage>();
package.SetupGet(c => c.Id).Returns(id);
package.SetupGet(c => c.Version).Returns(SemanticVersion.Parse(version));
package.SetupGet(c => c.Description).Returns(desc ?? id);
package.SetupGet(c => c.RequireLicenseAcceptance).Returns(requiresLicense);
package.SetupGet(c => c.LicenseUrl).Returns(new Uri("http://www." + id + ".com"));
package.SetupGet(c => c.Dependencies).Returns(dependencies ?? Enumerable.Empty<PackageDependency>());
return package.Object;
}
}
}

View File

@@ -0,0 +1,255 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web.WebPages.Administration.PackageManager;
using System.Xml.Linq;
using Moq;
using NuGet;
using Xunit;
namespace System.Web.WebPages.Administration.Test
{
public class WebProjectSystemTest
{
[Fact]
public void ResolvePathReturnsAppCodePathIfPathIsSourceFile()
{
// Arrange
var path = "Foo.cs";
var webProjectSystem = new WebProjectSystem(@"x:\");
// Act
var resolvedPath = webProjectSystem.ResolvePath(path);
// Assert
Assert.Equal(@"App_Code\Foo.cs", resolvedPath);
}
[Fact]
public void ResolvePathReturnsOriginalPathIfSourceFilePathIsAlreadyUnderAppCode()
{
// Arrange
var path = @"App_Code\Foo.cs";
var webProjectSystem = new WebProjectSystem(@"x:\");
// Act
var resolvedPath = webProjectSystem.ResolvePath(path);
// Assert
Assert.Equal(path, resolvedPath);
}
[Fact]
public void ResolvePathReturnsOriginalPathIfFileIsNotSource()
{
// Arrange
var path = @"Foo.js";
var webProjectSystem = new WebProjectSystem(@"x:\");
// Act
var resolvedPath = webProjectSystem.ResolvePath(path);
// Assert
Assert.Equal(path, resolvedPath);
}
[Fact]
public void AddPackageWithFrameworkReferenceCreatesWebConfigIfItDoesNotExist()
{
// Arrange
string webConfigPath = @"x:\my-website\web.config";
MemoryStream memoryStream = new MemoryStream();
var fileSystem = new Mock<IFileSystem>();
fileSystem.SetupGet(f => f.Root).Returns("x:\\my-website");
fileSystem.Setup(f => f.FileExists(It.Is<string>(p => p.Equals(webConfigPath)))).Returns(false).Verifiable();
fileSystem.Setup(f => f.AddFile(It.Is<string>(p => p.Equals(webConfigPath)), It.IsAny<Stream>()))
.Callback<string, Stream>((_, s) => { s.CopyTo(memoryStream); });
var references = "System";
// Act
WebProjectSystem.AddReferencesToConfig(fileSystem.Object, references);
// Assert
memoryStream.Seek(0, SeekOrigin.Begin);
XDocument document = XDocument.Load(memoryStream);
var element = document.Root;
Assert.Equal(element.Name, "configuration");
// Use SingleOrDefault to ensure there's exactly one element with that name
var assemblies = document.Root
.Elements().SingleOrDefault(e => e.Name.ToString().Equals("system.web"))
.Elements().SingleOrDefault(e => e.Name.ToString().Equals("compilation"))
.Elements().SingleOrDefault(e => e.Name.ToString().Equals("assemblies"));
Assert.Equal(references, assemblies.Elements().First().Attribute("assembly").Value);
}
[Fact]
public void AddPackageWithFrameworkReferenceCreatesWebConfigIfItExistsWithoutAssembliesNode()
{
// Arrange
var webConfigPath = @"x:\my-website\web.config";
var webConfigContent = @"<?xml version=""1.0""?>
<configuration>
<connectionStrings>
<add name=""test"" />
</connectionStrings>
<system.web>
<profiles><add name=""awesomeprofile"" /></profiles>
</system.web>
</configuration>
".AsStream();
MemoryStream memoryStream = new MemoryStream();
var fileSystem = new Mock<IFileSystem>();
fileSystem.SetupGet(f => f.Root).Returns("x:\\my-website");
fileSystem.Setup(f => f.FileExists(It.Is<string>(p => p.Equals(webConfigPath)))).Returns(true).Verifiable();
fileSystem.Setup(f => f.OpenFile(It.Is<string>(p => p.Equals(webConfigPath)))).Returns(webConfigContent);
fileSystem.Setup(f => f.AddFile(It.Is<string>(p => p.Equals(webConfigPath)), It.IsAny<Stream>()))
.Callback<string, Stream>((_, s) => { s.CopyTo(memoryStream); });
var references = "System.Data";
// Act
WebProjectSystem.AddReferencesToConfig(fileSystem.Object, references);
// Assert
memoryStream.Seek(0, SeekOrigin.Begin);
XDocument document = XDocument.Load(memoryStream);
var element = document.Root;
Assert.Equal(element.Name, "configuration");
// Use SingleOrDefault to ensure there's exactly one element with that name
var assemblies = document.Root
.Elements().SingleOrDefault(e => e.Name.ToString().Equals("system.web"))
.Elements().SingleOrDefault(e => e.Name.ToString().Equals("compilation"))
.Elements().SingleOrDefault(e => e.Name.ToString().Equals("assemblies"));
Assert.Equal(references, assemblies.Elements().First().Attribute("assembly").Value);
// Make sure the original web.config content is unaffected
Assert.Equal("test", document.Root
.Elements().SingleOrDefault(e => e.Name.ToString().Equals("connectionStrings"))
.Elements().SingleOrDefault(e => e.Name.ToString().Equals("add"))
.Attributes().SingleOrDefault(e => e.Name.ToString().Equals("name")).Value);
Assert.Equal("awesomeprofile", document.Root.Element("system.web").Element("profiles").Element("add").Attribute("name").Value);
}
[Fact]
public void AddPackageWithFrameworkReferenceDoesNotAffectWebConfigIfReferencesAlreadyExist()
{
// Arrange
var webConfigPath = @"x:\my-website\web.config";
var memoryStream = new NeverCloseMemoryStream(@"<?xml version=""1.0""?>
<configuration>
<connectionStrings>
<add name=""test"" />
</connectionStrings>
<system.web>
<compilation>
<assemblies>
<add assembly=""System.Data, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"" />
</assemblies>
</compilation>
<profiles><add name=""awesomeprofile"" /></profiles>
</system.web>
</configuration>
");
var fileSystem = new Mock<IFileSystem>();
fileSystem.SetupGet(f => f.Root).Returns("x:\\my-website");
fileSystem.Setup(f => f.FileExists(It.Is<string>(p => p.Equals(webConfigPath)))).Returns(true);
fileSystem.Setup(f => f.OpenFile(It.Is<string>(p => p.Equals(webConfigPath)))).Returns(() =>
{
memoryStream.Seek(0, SeekOrigin.Begin);
return memoryStream;
});
fileSystem.Setup(f => f.AddFile(It.Is<string>(p => p.Equals(webConfigPath)), It.IsAny<Stream>()))
.Callback<string, Stream>((_, stream) => { memoryStream = new NeverCloseMemoryStream(stream.ReadToEnd()); });
// Act
WebProjectSystem.AddReferencesToConfig(fileSystem.Object, "System.Data");
WebProjectSystem.AddReferencesToConfig(fileSystem.Object, "Microsoft.Abstractions");
// Assert
memoryStream.Seek(0, SeekOrigin.Begin);
XDocument document = XDocument.Load(memoryStream);
var element = document.Root;
Assert.Equal(element.Name, "configuration");
// Use SingleOrDefault to ensure there's exactly one element with that name
var assemblies = document.Root
.Elements().SingleOrDefault(e => e.Name.ToString().Equals("system.web"))
.Elements().SingleOrDefault(e => e.Name.ToString().Equals("compilation"))
.Elements().SingleOrDefault(e => e.Name.ToString().Equals("assemblies"));
Assert.Equal(2, assemblies.Elements("add").Count());
Assert.Equal("System.Data, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35",
assemblies.Elements().First().Attribute("assembly").Value);
Assert.Equal("Microsoft.Abstractions",
assemblies.Elements().Last().Attribute("assembly").Value);
// Make sure the original web.config content is unaffected
Assert.Equal("test", document.Root
.Elements().SingleOrDefault(e => e.Name.ToString().Equals("connectionStrings"))
.Elements().SingleOrDefault(e => e.Name.ToString().Equals("add"))
.Attributes().SingleOrDefault(e => e.Name.ToString().Equals("name")).Value);
Assert.Equal("awesomeprofile", document.Root.Element("system.web").Element("profiles").Element("add").Attribute("name").Value);
}
[Fact]
public void ResolveAssemblyPartialNameForCommonAssemblies()
{
// Arrange
var commonAssemblies = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "System.Data", "System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" },
{ "System.Data.Linq", "System.Data.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" },
{ "System.Net", "System.Net, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" },
{ "System.Runtime.Caching", "System.Runtime.Caching, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" },
{ "System.Xml", "System.Xml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" },
{ "System.Web.DynamicData", "System.Web.DynamicData, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" },
};
// Act and Assert
foreach (var item in commonAssemblies)
{
var resolvedName = WebProjectSystem.ResolvePartialAssemblyName(item.Key);
Assert.Equal(item.Value, resolvedName);
}
}
private static IFileSystem GetFileSystem()
{
var fileSystem = new Mock<IFileSystem>();
fileSystem.Setup(c => c.Root).Returns(@"X:\packages\");
return fileSystem.Object;
}
private class NeverCloseMemoryStream : MemoryStream
{
public NeverCloseMemoryStream(string content)
: base(Encoding.UTF8.GetBytes(content))
{
}
protected override void Dispose(bool disposing)
{
// Do nothing
}
}
}
}

View File

@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Moq" version="4.0.10827" />
<package id="NuGet.Core" version="1.6.2" />
<package id="xunit" version="1.9.0.1566" />
<package id="xunit.extensions" version="1.9.0.1566" />
</packages>