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,135 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Web.TestUtil;
using Xunit;
namespace Microsoft.Web.Helpers.Test
{
/// <summary>
///This is a test class for AnalyticsTest and is intended
///to contain all AnalyticsTest Unit Tests
///</summary>
public class AnalyticsTest
{
/// <summary>
///A test for GetYahooAnalyticsHtml
///</summary>
[Fact]
public void GetYahooAnalyticsHtmlTest()
{
string account = "My_yahoo_account";
string actual = Analytics.GetYahooHtml(account).ToString();
Assert.True(actual.Contains(".yahoo.com") && actual.Contains("My_yahoo_account"));
}
/// <summary>
///A test for GetStatCounterAnalyticsHtml
///</summary>
[Fact]
public void GetStatCounterAnalyticsHtmlTest()
{
int project = 31553;
string security = "stat_security";
string actual = Analytics.GetStatCounterHtml(project, security).ToString();
Assert.True(actual.Contains("statcounter.com/counter/counter_xhtml.js") &&
actual.Contains(project.ToString()) && actual.Contains(security));
}
/// <summary>
///A test for GetGoogleAnalyticsHtml
///</summary>
[Fact]
public void GetGoogleAnalyticsHtmlTest()
{
string account = "My_google_account";
string actual = Analytics.GetGoogleHtml(account).ToString();
Assert.True(actual.Contains("google-analytics.com/ga.js") && actual.Contains("My_google_account"));
}
[Fact]
public void GetGoogleAnalyticsEscapesJavascript()
{
string account = "My_\"google_account";
string actual = Analytics.GetGoogleHtml(account).ToString();
string expected = "<script type=\"text/javascript\">\n" +
"var gaJsHost = ((\"https:\" == document.location.protocol) ? \"https://ssl.\" : \"http://www.\");\n" +
"document.write(unescape(\"%3Cscript src='\" + gaJsHost + \"google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E\"));\n" +
"</script>\n" +
"<script type=\"text/javascript\">\n" +
"try{\n" +
"var pageTracker = _gat._getTracker(\"My_\\\"google_account\");\n" +
"pageTracker._trackPageview();\n" +
"} catch(err) {}\n" +
"</script>\n";
UnitTestHelper.AssertEqualsIgnoreWhitespace(expected, actual);
}
[Fact]
public void GetGoogleAnalyticsAsyncHtmlTest()
{
string account = "My_google_account";
string actual = Analytics.GetGoogleAsyncHtml(account).ToString();
Assert.True(actual.Contains("google-analytics.com/ga.js") && actual.Contains("My_google_account"));
}
[Fact]
public void GetGoogleAnalyticsAsyncHtmlEscapesJavaScript()
{
string account = "My_\"google_account";
string actual = Analytics.GetGoogleAsyncHtml(account).ToString();
string expected = "<script type=\"text/javascript\">\n" +
"var _gaq = _gaq || [];\n" +
"_gaq.push(['_setAccount', 'My_\\\"google_account']);\n" +
"_gaq.push(['_trackPageview']);\n" +
"(function() {\n" +
"var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;\n" +
"ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';\n" +
"var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);\n" +
"})();\n" +
"</script>\n";
UnitTestHelper.AssertEqualsIgnoreWhitespace(expected, actual);
}
[Fact]
public void GetYahooAnalyticsEscapesJavascript()
{
string account = "My_\"yahoo_account";
string actual = Analytics.GetYahooHtml(account).ToString();
string expected = "<script type=\"text/javascript\">\n" +
"window.ysm_customData = new Object();\n" +
"window.ysm_customData.conversion = \"transId=,currency=,amount=\";\n" +
"var ysm_accountid = \"My_\\\"yahoo_account\";\n" +
"document.write(\"<SCR\" + \"IPT language='JavaScript' type='text/javascript' \"\n" +
"+ \"SRC=//\" + \"srv3.wa.marketingsolutions.yahoo.com\" + \"/script/ScriptServlet\" + \"?aid=\" + ysm_accountid\n" +
"+ \"></SCR\" + \"IPT>\");\n" +
"</script>\n";
UnitTestHelper.AssertEqualsIgnoreWhitespace(expected, actual);
}
[Fact]
public void GetStatCounterAnalyticsEscapesCorrectly()
{
string account = "My_\"stat_account";
string actual = Analytics.GetStatCounterHtml(2, account).ToString();
string expected = "<script type=\"text/javascript\">\n" +
"var sc_project=2;\n" +
"var sc_invisible=1;\n" +
"var sc_security=\"My_\\\"stat_account\";\n" +
"var sc_text=2;\n" +
"var sc_https=1;\n" +
"var scJsHost = ((\"https:\" == document.location.protocol) ? \"https://secure.\" : \"http://www.\");\n" +
"document.write(\"<sc\" + \"ript type='text/javascript' src='\" + " +
"scJsHost + \"statcounter.com/counter/counter_xhtml.js'></\" + \"script>\");\n" +
"</script>\n\n" +
"<noscript>" +
"<div class=\"statcounter\">" +
"<a title=\"tumblrstatistics\" class=\"statcounter\" href=\"http://www.statcounter.com/tumblr/\">" +
"<img class=\"statcounter\" src=\"https://c.statcounter.com/2/0/My_&quot;stat_account/1/\" alt=\"tumblr statistics\"/>" +
"</a>" +
"</div>" +
"</noscript>";
UnitTestHelper.AssertEqualsIgnoreWhitespace(expected, actual);
}
}
}

View File

@@ -0,0 +1,254 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Web;
using System.Web.Helpers.Test;
using System.Web.TestUtil;
using System.Web.WebPages.Scope;
using Moq;
using Xunit;
using Assert = Microsoft.TestCommon.AssertEx;
namespace Microsoft.Web.Helpers.Test
{
public class BingTest
{
private static readonly IDictionary<object, object> _emptyStateStorage = new Dictionary<object, object>();
private const string BasicBingSearchTemplate = @"<form action=""http://www.bing.com/search"" class=""BingSearch"" method=""get"" target=""_blank"">"
+ @"<input name=""FORM"" type=""hidden"" value=""FREESS"" /><input name=""cp"" type=""hidden"" value=""{0}"" />"
+ @"<table cellpadding=""0"" cellspacing=""0"" style=""width:{1}px;""><tr style=""height: 32px"">"
+ @"<td style=""width: 100%; border:solid 1px #ccc; border-right-style:none; padding-left:10px; padding-right:10px; vertical-align:middle;"">"
+ @"<input name=""q"" style=""background-image:url(http://www.bing.com/siteowner/s/siteowner/searchbox_background_k.png); background-position:right; background-repeat:no-repeat; font-family:Arial; font-size:14px; color:#000; width:100%; border:none 0 transparent;"" title=""Search Bing"" type=""text"" />"
+ @"</td><td style=""border:solid 1px #ccc; border-left-style:none; padding-left:0px; padding-right:3px;"">"
+ @"<input alt=""Search"" src=""http://www.bing.com/siteowner/s/siteowner/searchbutton_normal_k.gif"" style=""border:none 0 transparent; height:24px; width:24px; vertical-align:top;"" type=""image"" />"
+ @"</td></tr>";
private const string BasicBingSearchFooter = "</table></form>";
private const string BasicBingSearchLocalSiteSearch = @"<tr><td colspan=""2"" style=""font-size: small""><label><input checked=""checked"" name=""q1"" type=""radio"" value=""site:{0}"" />{1}</label>&nbsp;<label><input name=""q1"" type=""radio"" value="""" />Search Web</label></td></tr>";
[Fact]
public void SiteTitleThrowsWhenSetToNull()
{
Assert.ThrowsArgumentNull(() => Bing.SiteTitle = null, "SiteTitle");
}
[Fact]
public void SiteTitleUsesScopeStorage()
{
// Arrange
var value = "value";
// Act
Bing.SiteTitle = value;
// Assert
Assert.Equal(Bing.SiteTitle, value);
Assert.Equal(ScopeStorage.CurrentScope[Bing._siteTitleKey], value);
}
[Fact]
public void SiteUrlThrowsWhenSetToNull()
{
Assert.ThrowsArgumentNull(() => Bing.SiteUrl = null, "SiteUrl");
}
[Fact]
public void SiteUrlUsesScopeStorage()
{
// Arrange
var value = "value";
// Act
Bing.SiteUrl = value;
// Assert
Assert.Equal(Bing.SiteUrl, value);
Assert.Equal(ScopeStorage.CurrentScope[Bing._siteUrlKey], value);
}
[Fact]
public void SearchBoxGeneratesValidHtml()
{
// Act & Assert
XhtmlAssert.Validate1_0(
Bing._SearchBox("322px", null, null, GetContextForSearchBox(), _emptyStateStorage), true
);
}
[Fact]
public void SearchBoxDoesNotContainSearchLocalWhenSiteUrlIsNull()
{
// Arrange
var encoding = Encoding.UTF8;
var expectedHtml = String.Format(CultureInfo.InvariantCulture, BasicBingSearchTemplate, encoding.CodePage, 322) + BasicBingSearchFooter;
// Act
var actualHtml = Bing._SearchBox("322px", null, null, GetContextForSearchBox(encoding), _emptyStateStorage).ToString();
// Assert
UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedHtml, actualHtml);
}
[Fact]
public void SearchBoxDoesNotContainSearchLocalWhenSiteUrlIsEmpty()
{
// Arrange
var encoding = Encoding.UTF8;
var expectedHtml = String.Format(CultureInfo.InvariantCulture, BasicBingSearchTemplate, encoding.CodePage, 322) + BasicBingSearchFooter;
// Act
var actualHtml = Bing._SearchBox("322px", String.Empty, String.Empty, GetContextForSearchBox(encoding), _emptyStateStorage).ToString();
// Assert
UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedHtml, actualHtml);
}
[Fact]
public void SearchBoxUsesResponseEncodingToDetermineCodePage()
{
// Arrange
var encoding = Encoding.GetEncoding(51932); //euc-jp
var expectedHtml = String.Format(CultureInfo.InvariantCulture, BasicBingSearchTemplate, encoding.CodePage, 322) + BasicBingSearchFooter;
// Act
var actualHtml = Bing._SearchBox("322px", String.Empty, String.Empty, GetContextForSearchBox(encoding), _emptyStateStorage).ToString();
// Assert
UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedHtml, actualHtml);
}
[Fact]
public void SearchBoxUsesWidthToSetBingSearchTableSize()
{
// Arrange
var encoding = Encoding.UTF8;
var expectedHtml = String.Format(CultureInfo.InvariantCulture, BasicBingSearchTemplate, encoding.CodePage, 609) + BasicBingSearchFooter;
// Act
var actualHtml = Bing._SearchBox("609px", String.Empty, String.Empty, GetContextForSearchBox(encoding), _emptyStateStorage).ToString();
// Assert
UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedHtml, actualHtml);
}
[Fact]
public void SearchBoxUsesWithSiteUrlProducesLocalSearchOptions()
{
// Arrange
var encoding = Encoding.Default;
var expectedHtml = String.Format(CultureInfo.InvariantCulture, BasicBingSearchTemplate, encoding.CodePage, 322) +
String.Format(CultureInfo.InvariantCulture, BasicBingSearchLocalSiteSearch, "www.asp.net", "Search Site") + BasicBingSearchFooter;
// Act
var actualHtml = Bing._SearchBox("322px", "www.asp.net", String.Empty, GetContextForSearchBox(encoding), _emptyStateStorage).ToString();
// Assert
UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedHtml, actualHtml);
}
[Fact]
public void SearchBoxUsesWithSiteUrlAndSiteTitleProducesLocalSearchOptions()
{
// Arrange
var encoding = Encoding.Default;
var expectedHtml = String.Format(CultureInfo.InvariantCulture, BasicBingSearchTemplate, encoding.CodePage, 322) +
String.Format(CultureInfo.InvariantCulture, BasicBingSearchLocalSiteSearch, "www.microsoft.com", "Custom Search") + BasicBingSearchFooter;
// Act
var actualHtml = Bing._SearchBox("322px", "www.microsoft.com", "Custom Search", GetContextForSearchBox(encoding), _emptyStateStorage).ToString();
// Assert
UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedHtml, actualHtml);
}
[Fact]
public void SearchBoxWithLocalSiteOptionUsesResponseEncoding()
{
// Arrange
var encoding = Encoding.GetEncoding(1258); //windows-1258
var expectedHtml = String.Format(CultureInfo.InvariantCulture, BasicBingSearchTemplate, encoding.CodePage, 322) +
String.Format(CultureInfo.InvariantCulture, BasicBingSearchLocalSiteSearch, "www.asp.net", "Search Site") + BasicBingSearchFooter;
// Act
var actualHtml = Bing._SearchBox("322px", "www.asp.net", String.Empty, GetContextForSearchBox(encoding), _emptyStateStorage).ToString();
// Assert
UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedHtml, actualHtml);
}
[Fact]
public void SearchBoxUsesScopeStorageIfSiteTitleParameterIsNull()
{
// Arrange
var encoding = Encoding.GetEncoding(1258); //windows-1258
var expectedHtml = String.Format(CultureInfo.InvariantCulture, BasicBingSearchTemplate, encoding.CodePage, 322) +
String.Format(CultureInfo.InvariantCulture, BasicBingSearchLocalSiteSearch, "www.asp.net", "foobar") + BasicBingSearchFooter;
// Act
var actualHtml = Bing._SearchBox("322px", "www.asp.net", null, GetContextForSearchBox(encoding), new Dictionary<object, object> { { Bing._siteTitleKey, "foobar" } }).ToString();
// Assert
UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedHtml, actualHtml);
}
[Fact]
public void SearchBoxUsesScopeStorageIfSiteTitleParameterIsEmpty()
{
// Arrange
var encoding = Encoding.GetEncoding(1258); //windows-1258
var expectedHtml = String.Format(CultureInfo.InvariantCulture, BasicBingSearchTemplate, encoding.CodePage, 322) +
String.Format(CultureInfo.InvariantCulture, BasicBingSearchLocalSiteSearch, "www.asptest.net", "bazbiz") + BasicBingSearchFooter;
// Act
var actualHtml = Bing._SearchBox("322px", "www.asptest.net", String.Empty, GetContextForSearchBox(encoding), new Dictionary<object, object> { { Bing._siteTitleKey, "bazbiz" } }).ToString();
// Assert
UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedHtml, actualHtml);
}
[Fact]
public void SearchBoxUsesScopeStorageIfSiteUrlParameterIsNull()
{
// Arrange
var encoding = Encoding.GetEncoding(1258); //windows-1258
var expectedHtml = String.Format(CultureInfo.InvariantCulture, BasicBingSearchTemplate, encoding.CodePage, 322) +
String.Format(CultureInfo.InvariantCulture, BasicBingSearchLocalSiteSearch, "www.myawesomesite.net", "my-test-string") + BasicBingSearchFooter;
// Act
var actualHtml = Bing._SearchBox("322px", null, "my-test-string", GetContextForSearchBox(encoding), new Dictionary<object, object> { { Bing._siteUrlKey, "www.myawesomesite.net" } }).ToString();
// Assert
UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedHtml, actualHtml);
}
[Fact]
public void SearchBoxUsesScopeStorageIfSiteUrlParameterIsEmpty()
{
// Arrange
var encoding = Encoding.GetEncoding(1258); //windows-1258
var expectedHtml = String.Format(CultureInfo.InvariantCulture, BasicBingSearchTemplate, encoding.CodePage, 322) +
String.Format(CultureInfo.InvariantCulture, BasicBingSearchLocalSiteSearch, "www.myawesomesite.net", "my-test-string") + BasicBingSearchFooter;
// Act
var actualHtml = Bing._SearchBox("322px", String.Empty, "my-test-string", GetContextForSearchBox(encoding), new Dictionary<object, object> { { Bing._siteUrlKey, "www.myawesomesite.net" } }).ToString();
// Assert
UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedHtml, actualHtml);
}
private HttpContextBase GetContextForSearchBox(Encoding contentEncoding = null)
{
Mock<HttpContextBase> context = new Mock<HttpContextBase>();
Mock<HttpResponseBase> response = new Mock<HttpResponseBase>();
response.Setup(c => c.ContentEncoding).Returns(contentEncoding ?? Encoding.Default);
context.Setup(c => c.Response).Returns(response.Object);
return context.Object;
}
}
}

View File

@@ -0,0 +1,272 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.TestUtil;
using Microsoft.TestCommon;
using Moq;
using Xunit;
using Assert = Microsoft.TestCommon.AssertEx;
namespace Microsoft.Web.Helpers.Test
{
public class FacebookTest
{
public FacebookTest()
{
Facebook.AppId = "myapp'";
Facebook.AppSecret = "myappsecret";
Facebook.Language = "french";
}
[Fact]
public void GetFacebookCookieInfoReturnsEmptyStringIfCookieIsNotPresent()
{
// Arrange
var context = CreateHttpContext();
// Act
var info = Facebook.GetFacebookCookieInfo(context, "foo");
// Assert
Assert.Equal("", info);
}
[Fact]
public void GetFacebookCookieInfoThrowsIfCookieIsNotValid()
{
// Arrange
var context = CreateHttpContext(new Dictionary<string, string>
{
{"fbs_myapp'", "sig=malformed-signature&name=foo&val=bar&uid=MyFacebookName"},
{"fbs_uid", "MyFacebookName"},
});
// Act and Assert
Assert.Throws<InvalidOperationException>(() => Facebook.GetFacebookCookieInfo(context, "uid"), "Invalid Facebook cookie.");
}
[Fact]
public void GetFacebookCookieReturnsUserIdIfCookieIsValid()
{
// Arrange
var context = CreateHttpContext(new Dictionary<string, string>
{
{"fbs_myapp'", "sig=B2E6B3A21D0C9FA72E612BD6C3084807&name=foo&val=bar&uid=MyFacebookName"},
});
// Act
var info = Facebook.GetFacebookCookieInfo(context, "uid");
// Assert
Assert.Equal("MyFacebookName", info);
}
[Fact]
public void GetInitScriptsJSEncodesParameters()
{
// Arrange
var expectedText = @"
<div id=""fb-root""></div>
<script type=""text/javascript"">
window.fbAsyncInit = function () {
FB.init({ appId: 'MyApp\u0027', status: true, cookie: true, xfbml: true });
};
(function () {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol +
'//connect.facebook.net/French/all.js';
document.getElementById('fb-root').appendChild(e);
} ());
function loginRedirect(url) { window.location = url; }
</script>
";
// Act
var actualText = Facebook.GetInitializationScripts();
// Assert
UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedText, actualText.ToString());
}
[Fact]
public void LoginButtonTest()
{
// Arrange
var expected40 = @"<fb:login-button autologoutlink=""True"" size=""extra-small"" length=""extra-long"" onlogin=""loginRedirect(&#39;http://www.test.com/facebook/?registerUrl=http%3a%2f%2fwww.test.com%2f&amp;returnUrl=http%3a%2f%2fww.test.com%2fLogin.cshtml&#39;)"" show-faces=""True"" perms=""email,none&quot;"">Awesome &quot;button text&quot;</fb:login-button>";
var expected45 = @"<fb:login-button autologoutlink=""True"" size=""extra-small"" length=""extra-long"" onlogin=""loginRedirect(&#39;http://www.test.com/facebook/?registerUrl=http%3a%2f%2fwww.test.com%2f\u0026returnUrl=http%3a%2f%2fww.test.com%2fLogin.cshtml&#39;)"" show-faces=""True"" perms=""email,none&quot;"">Awesome &quot;button text&quot;</fb:login-button>";
// Act
var actualText = Facebook.LoginButton("http://www.test.com", "http://ww.test.com/Login.cshtml", "http://www.test.com/facebook/", "Awesome \"button text\"", true, "extra-small", "extra-long", true, "none\"");
// Assert
UnitTestHelper.AssertEqualsIgnoreWhitespace(RuntimeEnvironment.IsVersion45Installed ? expected45 : expected40, actualText.ToString());
}
[Fact]
public void LoginButtonOnlyTagTest()
{
// Arrange
var expectedText = @"<fb:login-button autologoutlink=""True"" size=""small"" length=""medium"" onlogin=""foobar();"" show-faces=""True"" perms=""none&quot;"">&quot;Awesome button text&quot;</fb:login-button>";
// Act
var actualText = Facebook.LoginButtonTagOnly("\"Awesome button text\"", true, "small", "medium", "foobar();", true, "none\"");
// Assert
UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedText, actualText.ToString());
}
[Fact]
public void LikeButtonTest()
{
// Arrange
var expectedText = @"<iframe src=""http://www.facebook.com/plugins/like.php?href=http%3a%2f%2fsomewebsite&amp;layout=modern&amp;show_faces=false&amp;width=300&amp;action=hop&amp;colorscheme=lighter&amp;height=30&amp;font=Comic+Sans&amp;locale=French&amp;ref=foo+bar"" scrolling=""no"" frameborder=""0"" style=""border:none; overflow:hidden; width:300px; height:30px;"" allowTransparency=""true""></iframe>";
// Act
var actualText = Facebook.LikeButton("http://somewebsite", "modern", false, 300, 30, "hop", "Comic Sans", "lighter", "foo bar");
// Assert
UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedText, actualText.ToString());
}
[Fact]
public void CommentsWithNoXidTest()
{
// Arrange
var expectedText = @"<fb:comments numposts=""3"" width=""300"" reverse=""true"" simple=""true"" ></fb:comments>";
// Act
var actualText = Facebook.Comments(null, 300, 3, true, true);
// Assert
UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedText, actualText.ToString());
}
[Fact]
public void CommentsWithXidTest()
{
// Arrange
var expectedText = @"<fb:comments xid=""bar"" numposts=""3"" width=""300"" reverse=""true"" simple=""true"" ></fb:comments>";
// Act
var actualText = Facebook.Comments("bar", 300, 3, true, true);
// Assert
UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedText, actualText.ToString());
}
[Fact]
public void RecommendationsTest()
{
// Arrange
var expectedText = @"<iframe src=""http://www.facebook.com/plugins/recommendations.php?site=http%3a%2f%2fsomesite&amp;width=100&amp;height=200&amp;header=False&amp;colorscheme=blue&amp;font=none&amp;border_color=black&amp;filter=All+posts&amp;ref=ref+label&amp;locale=french"" scrolling=""no"" frameborder=""0"" style=""border:none; overflow:hidden; width:100px; height:200px;"" allowTransparency=""true""></iframe>";
// Act
var actualText = Facebook.Recommendations("http://somesite", 100, 200, false, "blue", "none", "black", "All posts", "ref label");
// Assert
UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedText, actualText.ToString());
}
[Fact]
public void LikeBoxTest()
{
// Arrange
var expectedText = @"<iframe src=""http://www.facebook.com/plugins/recommendations.php?href=http%3a%2f%2fsomesite&amp;width=100&amp;height=200&amp;header=False&amp;colorscheme=blue&amp;connections=5&amp;stream=True&amp;header=False&amp;locale=french"" scrolling=""no"" frameborder=""0"" style=""border:none; overflow:hidden; width:100px; height:200px;"" allowTransparency=""true""></iframe>";
// Act
var actualText = Facebook.LikeBox("http://somesite", 100, 200, "blue", 5, true, false);
// Assert
UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedText, actualText.ToString());
}
[Fact]
public void FacepileTest()
{
// Arrange
var expectedText = @"<fb:facepile max-rows=""3"" width=""100""></fb:facepile>";
// Act
var actualText = Facebook.Facepile(3, 100);
// Assert
UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedText, actualText.ToString());
}
[Fact]
public void LiveStreamWithEmptyXidTest()
{
// Arrange
var expectedText = @"<iframe src=""http://www.facebook.com/plugins/live_stream_box.php?app_id=myapp%27&amp;width=100&amp;height=100&amp;always_post_to_friends=True&amp;locale=french"" scrolling=""no"" frameborder=""0"" style=""border:none; overflow:hidden; width:100px; height:100px;"" allowTransparency=""true""></iframe>";
// Act
var actualText = Facebook.LiveStream(100, 100, "", "", true);
// Assert
UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedText, actualText.ToString());
}
[Fact]
public void LiveStreamWithXidValueTest()
{
// Arrange
var expectedText = @"<iframe src=""http://www.facebook.com/plugins/live_stream_box.php?app_id=myapp%27&amp;width=100&amp;height=100&amp;always_post_to_friends=True&amp;locale=french&amp;xid=some-val&amp;via_url=http%3a%2f%2fmysite"" scrolling=""no"" frameborder=""0"" style=""border:none; overflow:hidden; width:100px; height:100px;"" allowTransparency=""true""></iframe>";
// Act
var actualText = Facebook.LiveStream(100, 100, "some-val", "http://mysite", true);
// Assert
UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedText, actualText.ToString());
}
[Fact]
public void ActivityStreamTest()
{
// Arrange
var expectedText = @"<iframe src=""http://www.facebook.com/plugins/activity.php?site=http%3a%2f%2fmysite&amp;width=100&amp;height=120&amp;header=False&amp;colorscheme=gray&amp;font=Arial&amp;border_color=blue&amp;recommendations=True&amp;locale=french"" scrolling=""no"" frameborder=""0"" style=""border:none; overflow:hidden; width:300px; height:300px;"" allowTransparency=""true""></iframe>";
// Act
var actualText = Facebook.ActivityFeed("http://mysite", 100, 120, false, "gray", "Arial", "blue", true);
// Assert
UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedText, actualText.ToString());
}
[Fact]
public void FbmlNamespacesTest()
{
// Arrange
var expectedText = @"xmlns:fb=""http://www.facebook.com/2008/fbml"" xmlns:og=""http://opengraphprotocol.org/schema/""";
// Act
var actualText = Facebook.FbmlNamespaces();
// Assert
Assert.Equal(expectedText, actualText.ToString());
}
private static HttpContextBase CreateHttpContext(IDictionary<string, string> cookieValues = null)
{
var context = new Mock<HttpContextBase>();
var httpRequest = new Mock<HttpRequestBase>();
var cookies = new HttpCookieCollection();
httpRequest.Setup(c => c.Cookies).Returns(cookies);
context.Setup(c => c.Request).Returns(httpRequest.Object);
if (cookieValues != null)
{
foreach (var item in cookieValues)
{
cookies.Add(new HttpCookie(item.Key, item.Value));
}
}
return context.Object;
}
}
}

View File

@@ -0,0 +1,201 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections;
using System.Web;
using System.Web.Helpers.Test;
using System.Web.TestUtil;
using Moq;
using Xunit;
using Assert = Microsoft.TestCommon.AssertEx;
namespace Microsoft.Web.Helpers.Test
{
public class FileUploadTest
{
private const string _fileUploadScript = "<script type=\"text/javascript\"> if (!window[\"FileUploadHelper\"]) window[\"FileUploadHelper\"] = {}; FileUploadHelper.addInputElement = function(index, name) { var inputElem = document.createElement(\"input\"); inputElem.type = \"file\"; inputElem.name = name; var divElem = document.createElement(\"div\"); divElem.appendChild(inputElem.cloneNode(false)); var inputs = document.getElementById(\"file-upload-\" + index); inputs.appendChild(divElem); } </script>";
[Fact]
public void RenderThrowsWhenNumberOfFilesIsLessThanZero()
{
// Act and Assert
Assert.ThrowsArgumentGreaterThanOrEqualTo(
() => FileUpload._GetHtml(GetContext(), name: null, initialNumberOfFiles: -2, allowMoreFilesToBeAdded: false, includeFormTag: false, addText: "", uploadText: "").ToString(),
"initialNumberOfFiles", "0");
}
[Fact]
public void ResultIncludesFormTagAndSubmitButtonWhenRequested()
{
// Arrange
string expectedResult = @"<form action="""" enctype=""multipart/form-data"" method=""post""><div class=""file-upload"" id=""file-upload-0"">"
+ @"<div><input name=""fileUpload"" type=""file"" /></div></div>"
+ @"<div class=""file-upload-buttons""><input type=""submit"" value=""Upload"" /></div></form>";
// Act
var actualResult = FileUpload._GetHtml(GetContext(), name: null, initialNumberOfFiles: 1, allowMoreFilesToBeAdded: false, includeFormTag: true, addText: null, uploadText: null);
// Assert
UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedResult, actualResult.ToString());
}
[Fact]
public void ResultDoesNotIncludeFormTagAndSubmitButtonWhenNotRequested()
{
// Arrange
string expectedResult = @"<div class=""file-upload"" id=""file-upload-0""><div><input name=""fileUpload"" type=""file"" /></div></div>";
// Act
var actualResult = FileUpload._GetHtml(GetContext(), name: null, initialNumberOfFiles: 1, allowMoreFilesToBeAdded: false, includeFormTag: false, addText: null, uploadText: null);
// Assert
UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedResult, actualResult.ToString());
}
[Fact]
public void ResultIncludesCorrectNumberOfInputFields()
{
// Arrange
string expectedResult = @"<div class=""file-upload"" id=""file-upload-0""><div><input name=""fileUpload"" type=""file"" /></div><div><input name=""fileUpload"" type=""file"" /></div>"
+ @"<div><input name=""fileUpload"" type=""file"" /></div></div>";
// Act
var actualResult = FileUpload._GetHtml(GetContext(), name: null, initialNumberOfFiles: 3, allowMoreFilesToBeAdded: false, includeFormTag: false, addText: null, uploadText: null);
// Assert
UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedResult, actualResult.ToString());
}
[Fact]
public void ResultIncludesAnchorTagWithCorrectAddText()
{
// Arrange
string customAddText = "Add More";
string expectedResult = _fileUploadScript
+ @"<div class=""file-upload"" id=""file-upload-0""><div><input name=""fileUpload"" type=""file"" /></div></div>"
+ @"<div class=""file-upload-buttons""><a href=""#"" onclick=""FileUploadHelper.addInputElement(0, &quot;fileUpload&quot;); return false;"">" + customAddText + "</a></div>";
// Act
var result = FileUpload._GetHtml(GetContext(), name: null, allowMoreFilesToBeAdded: true, includeFormTag: false, addText: customAddText, initialNumberOfFiles: 1, uploadText: null);
// Assert
UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedResult, result.ToString());
}
[Fact]
public void ResultDoesNotIncludeAnchorTagNorAddTextWhenNotRequested()
{
// Arrange
string customAddText = "Add More";
string expectedResult = @"<div class=""file-upload"" id=""file-upload-0""><div><input name=""fileUpload"" type=""file"" /></div></div>";
// Act
var result = FileUpload._GetHtml(GetContext(), name: null, allowMoreFilesToBeAdded: false, includeFormTag: false, addText: customAddText, uploadText: null, initialNumberOfFiles: 1);
// Assert
UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedResult, result.ToString());
}
[Fact]
public void ResultIncludesSubmitInputTagWithCustomUploadText()
{
// Arrange
string customUploadText = "Now!";
string expectedResult = @"<form action="""" enctype=""multipart/form-data"" method=""post""><div class=""file-upload"" id=""file-upload-0"">"
+ @"<div><input name=""fileUpload"" type=""file"" /></div></div>"
+ @"<div class=""file-upload-buttons""><input type=""submit"" value=""" + customUploadText + @""" /></div></form>";
// Act
var result = FileUpload._GetHtml(GetContext(), name: null, includeFormTag: true, uploadText: customUploadText, allowMoreFilesToBeAdded: false, initialNumberOfFiles: 1, addText: null);
// Assert
UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedResult, result.ToString());
}
[Fact]
public void FileUploadGeneratesUniqueIdsForMultipleCallsForCommonRequest()
{
// Arrange
var context = GetContext();
string expectedResult1 = @"<div class=""file-upload"" id=""file-upload-0""><div><input name=""fileUpload"" type=""file"" /></div><div><input name=""fileUpload"" type=""file"" /></div>"
+ @"<div><input name=""fileUpload"" type=""file"" /></div></div>";
string expectedResult2 = @"<form action="""" enctype=""multipart/form-data"" method=""post""><div class=""file-upload"" id=""file-upload-1""><div><input name=""fileUpload"" type=""file"" /></div>"
+ @"<div><input name=""fileUpload"" type=""file"" /></div></div><div class=""file-upload-buttons""><input type=""submit"" value=""Upload"" /></div></form>";
// Act
var result1 = FileUpload._GetHtml(context, name: null, initialNumberOfFiles: 3, allowMoreFilesToBeAdded: false, includeFormTag: false, addText: null, uploadText: null);
var result2 = FileUpload._GetHtml(context, name: null, initialNumberOfFiles: 2, allowMoreFilesToBeAdded: false, includeFormTag: true, addText: null, uploadText: null);
// Assert
UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedResult1, result1.ToString());
UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedResult2, result2.ToString());
}
[Fact]
public void FileUploadGeneratesScriptOncePerRequest()
{
// Arrange
var context = GetContext();
string expectedResult1 = _fileUploadScript
+ @"<div class=""file-upload"" id=""file-upload-0""><div><input name=""fileUpload"" type=""file"" /></div></div>"
+ @"<div class=""file-upload-buttons""><a href=""#"" onclick=""FileUploadHelper.addInputElement(0, &quot;fileUpload&quot;); return false;"">Add more files</a></div>";
string expectedResult2 = @"<form action="""" enctype=""multipart/form-data"" method=""post""><div class=""file-upload"" id=""file-upload-1""><div><input name=""fileUpload"" type=""file"" /></div></div>"
+ @"<div class=""file-upload-buttons""><a href=""#"" onclick=""FileUploadHelper.addInputElement(1, &quot;fileUpload&quot;); return false;"">Add more files</a><input type=""submit"" value=""Upload"" /></div></form>";
string expectedResult3 = @"<form action="""" enctype=""multipart/form-data"" method=""post""><div class=""file-upload"" id=""file-upload-2"">"
+ @"<div><input name=""fileUpload"" type=""file"" /></div></div>"
+ @"<div class=""file-upload-buttons""><input type=""submit"" value=""Upload"" /></div></form>";
// Act
var result1 = FileUpload._GetHtml(context, name: null, initialNumberOfFiles: 1, allowMoreFilesToBeAdded: true, includeFormTag: false, addText: null, uploadText: null);
var result2 = FileUpload._GetHtml(context, name: null, initialNumberOfFiles: 1, allowMoreFilesToBeAdded: true, includeFormTag: true, addText: null, uploadText: null);
var result3 = FileUpload._GetHtml(context, name: null, initialNumberOfFiles: 1, allowMoreFilesToBeAdded: false, includeFormTag: true, addText: null, uploadText: null);
// Assert
UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedResult1, result1.ToString());
UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedResult2, result2.ToString());
UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedResult3, result3.ToString());
}
[Fact]
public void FileUploadUsesNamePropertyInJavascript()
{
// Arrange
var context = GetContext();
string name = "foobar";
string expectedResult = _fileUploadScript
+ @"<form action="""" enctype=""multipart/form-data"" method=""post""><div class=""file-upload"" id=""file-upload-0""><div><input name=""foobar"" type=""file"" /></div></div>"
+ @"<div class=""file-upload-buttons""><a href=""#"" onclick=""FileUploadHelper.addInputElement(0, &quot;foobar&quot;); return false;"">Add more files</a><input type=""submit"" value=""Upload"" /></div></form>";
// Act
var result = FileUpload._GetHtml(context, name: name, initialNumberOfFiles: 1, allowMoreFilesToBeAdded: true, includeFormTag: true, addText: null, uploadText: null);
// Assert
UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedResult, result.ToString());
}
[Fact]
public void _GetHtmlWithDefaultArgumentsProducesValidXhtml()
{
// Act
var result = FileUpload._GetHtml(GetContext(), name: null, initialNumberOfFiles: 1, includeFormTag: false, allowMoreFilesToBeAdded: false, addText: null, uploadText: null);
// Assert
XhtmlAssert.Validate1_1(result, "div");
}
[Fact]
public void _GetHtmlWithoutFormTagProducesValidXhtml()
{
// Act
var result = FileUpload._GetHtml(GetContext(), name: null, includeFormTag: false, initialNumberOfFiles: 1, allowMoreFilesToBeAdded: false, addText: null, uploadText: null);
XhtmlAssert.Validate1_1(result, "div");
}
private HttpContextBase GetContext()
{
var context = new Mock<HttpContextBase>();
context.Setup(c => c.Items).Returns(new Hashtable());
return context.Object;
}
}
}

View File

@@ -0,0 +1,61 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Web.Helpers.Test;
using System.Web.TestUtil;
using Xunit;
using Assert = Microsoft.TestCommon.AssertEx;
namespace Microsoft.Web.Helpers.Test
{
public class GamerCardTest
{
[Fact]
public void RenderThrowsWhenGamertagIsEmpty()
{
// Act & Assert
Assert.ThrowsArgumentNullOrEmptyString(() => { GamerCard.GetHtml(String.Empty).ToString(); }, "gamerTag");
}
[Fact]
public void RenderThrowsWhenGamertagIsNull()
{
// Act & Assert
Assert.ThrowsArgumentNullOrEmptyString(() => { GamerCard.GetHtml(null).ToString(); }, "gamerTag");
}
[Fact]
public void RenderGeneratesProperMarkupWithSimpleGamertag()
{
// Arrange
string expectedHtml = "<iframe frameborder=\"0\" height=\"140\" scrolling=\"no\" src=\"http://gamercard.xbox.com/osbornm.card\" width=\"204\">osbornm</iframe>";
// Act
string html = GamerCard.GetHtml("osbornm").ToHtmlString();
// Assert
UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedHtml, html);
}
[Fact]
public void RenderGeneratesProperMarkupWithComplexGamertag()
{
// Arrange
string expectedHtml = "<iframe frameborder=\"0\" height=\"140\" scrolling=\"no\" src=\"http://gamercard.xbox.com/matthew%20osborn&#39;s.card\" width=\"204\">matthew osborn&#39;s</iframe>";
// Act
string html = GamerCard.GetHtml("matthew osborn's").ToHtmlString();
// Assert
UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedHtml, html);
}
[Fact]
public void RenderGeneratesValidXhtml()
{
XhtmlAssert.Validate1_0(
GamerCard.GetHtml("osbornm")
);
}
}
}

View File

@@ -0,0 +1,143 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Web.Helpers.Test;
using Xunit;
using Assert = Microsoft.TestCommon.AssertEx;
namespace Microsoft.Web.Helpers.Test
{
public class GravatarTest
{
[Fact]
public void GetUrlDefaults()
{
string url = Gravatar.GetUrl("foo@bar.com");
Assert.Equal("http://www.gravatar.com/avatar/f3ada405ce890b6f8204094deb12d8a8?s=80", url);
}
[Fact]
public void RenderEncodesDefaultImageUrl()
{
string render = Gravatar.GetHtml("foo@bar.com", defaultImage: "http://example.com/images/example.jpg").ToString();
Assert.Equal(
"<img src=\"http://www.gravatar.com/avatar/f3ada405ce890b6f8204094deb12d8a8?s=80&amp;d=http%3a%2f%2fexample.com%2fimages%2fexample.jpg\" alt=\"gravatar\" />",
render);
}
[Fact]
public void RenderLowerCasesEmail()
{
string render = Gravatar.GetHtml("FOO@BAR.COM").ToString();
Assert.Equal(
"<img src=\"http://www.gravatar.com/avatar/f3ada405ce890b6f8204094deb12d8a8?s=80\" alt=\"gravatar\" />",
render);
}
[Fact]
public void RendersValidXhtml()
{
XhtmlAssert.Validate1_1(Gravatar.GetHtml("foo@bar.com"));
}
[Fact]
public void RenderThrowsWhenEmailIsEmpty()
{
Assert.ThrowsArgumentNullOrEmptyString(() => { Gravatar.GetHtml(String.Empty); }, "email");
}
[Fact]
public void RenderThrowsWhenEmailIsNull()
{
Assert.ThrowsArgumentNullOrEmptyString(() => { Gravatar.GetHtml(null); }, "email");
}
[Fact]
public void RenderThrowsWhenImageSizeIsLessThanZero()
{
Assert.ThrowsArgument(() => { Gravatar.GetHtml("foo@bar.com", imageSize: -1); }, "imageSize", "The Gravatar image size must be between 1 and 512 pixels.");
}
[Fact]
public void RenderThrowsWhenImageSizeIsZero()
{
Assert.ThrowsArgument(() => { Gravatar.GetHtml("foo@bar.com", imageSize: 0); }, "imageSize", "The Gravatar image size must be between 1 and 512 pixels.");
}
[Fact]
public void RenderThrowsWhenImageSizeIsGreaterThan512()
{
Assert.ThrowsArgument(() => { Gravatar.GetHtml("foo@bar.com", imageSize: 513); }, "imageSize", "The Gravatar image size must be between 1 and 512 pixels.");
}
[Fact]
public void RenderTrimsEmail()
{
string render = Gravatar.GetHtml(" \t foo@bar.com\t\r\n").ToString();
Assert.Equal(
"<img src=\"http://www.gravatar.com/avatar/f3ada405ce890b6f8204094deb12d8a8?s=80\" alt=\"gravatar\" />",
render);
}
[Fact]
public void RenderUsesDefaultImage()
{
string render = Gravatar.GetHtml("foo@bar.com", defaultImage: "wavatar").ToString();
Assert.Equal(
"<img src=\"http://www.gravatar.com/avatar/f3ada405ce890b6f8204094deb12d8a8?s=80&amp;d=wavatar\" alt=\"gravatar\" />",
render);
}
[Fact]
public void RenderUsesImageSize()
{
string render = Gravatar.GetHtml("foo@bar.com", imageSize: 512).ToString();
Assert.Equal(
"<img src=\"http://www.gravatar.com/avatar/f3ada405ce890b6f8204094deb12d8a8?s=512\" alt=\"gravatar\" />",
render);
}
[Fact]
public void RenderUsesRating()
{
string render = Gravatar.GetHtml("foo@bar.com", rating: GravatarRating.G).ToString();
Assert.Equal(
"<img src=\"http://www.gravatar.com/avatar/f3ada405ce890b6f8204094deb12d8a8?s=80&amp;r=g\" alt=\"gravatar\" />",
render);
}
[Fact]
public void RenderWithAttributes()
{
string render = Gravatar.GetHtml("foo@bar.com",
attributes: new { id = "gravatar", alT = "<b>foo@bar.com</b>", srC = "ignored" }).ToString();
// beware of attributes ordering in tests
Assert.Equal(
"<img src=\"http://www.gravatar.com/avatar/f3ada405ce890b6f8204094deb12d8a8?s=80\" alT=\"&lt;b>foo@bar.com&lt;/b>\" id=\"gravatar\" />",
render);
}
[Fact]
public void RenderWithDefaults()
{
string render = Gravatar.GetHtml("foo@bar.com").ToString();
Assert.Equal(
"<img src=\"http://www.gravatar.com/avatar/f3ada405ce890b6f8204094deb12d8a8?s=80\" alt=\"gravatar\" />",
render);
}
[Fact]
public void RenderWithExtension()
{
string render = Gravatar.GetHtml("foo@bar.com", imageExtension: ".png").ToString();
Assert.Equal(
"<img src=\"http://www.gravatar.com/avatar/f3ada405ce890b6f8204094deb12d8a8.png?s=80\" alt=\"gravatar\" />",
render);
render = Gravatar.GetHtml("foo@bar.com", imageExtension: "xyz").ToString();
Assert.Equal(
"<img src=\"http://www.gravatar.com/avatar/f3ada405ce890b6f8204094deb12d8a8.xyz?s=80\" alt=\"gravatar\" />",
render);
}
}
}

View File

@@ -0,0 +1,189 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Linq;
using System.Web;
using System.Web.Helpers.Test;
using System.Web.TestUtil;
using System.Web.WebPages.Scope;
using Xunit;
using Assert = Microsoft.TestCommon.AssertEx;
namespace Microsoft.Web.Helpers.Test
{
public class LinkShareTest
{
private static LinkShareSite[] _allLinkShareSites = new[]
{
LinkShareSite.Delicious, LinkShareSite.Digg, LinkShareSite.GoogleBuzz,
LinkShareSite.Facebook, LinkShareSite.Reddit, LinkShareSite.StumbleUpon, LinkShareSite.Twitter
};
[Fact]
public void RenderWithFacebookFirst_ReturnsHtmlWithFacebookAndThenOthersTest()
{
string pageTitle = "page1";
string pageLinkBack = "page link back";
string twitterUserName = String.Empty;
string twitterTag = String.Empty;
string actual;
actual = LinkShare.GetHtml(pageTitle, pageLinkBack, twitterUserName, twitterTag, LinkShareSite.Facebook, LinkShareSite.All).ToString();
Assert.True(actual.Contains("twitter.com"));
int pos = actual.IndexOf("facebook.com");
Assert.True(pos > 0);
int pos2 = actual.IndexOf("reddit.com");
Assert.True(pos2 > pos);
pos2 = actual.IndexOf("digg.com");
Assert.True(pos2 > pos);
}
[Fact]
public void BitlyApiKeyThrowsWhenSetToNull()
{
Assert.ThrowsArgumentNull(() => LinkShare.BitlyApiKey = null, "value");
}
[Fact]
public void BitlyApiKeyUsesScopeStorage()
{
// Arrange
var value = "value";
// Act
LinkShare.BitlyApiKey = value;
// Assert
Assert.Equal(LinkShare.BitlyApiKey, value);
Assert.Equal(ScopeStorage.CurrentScope[LinkShare._bitlyApiKey], value);
}
[Fact]
public void BitlyLoginThrowsWhenSetToNull()
{
Assert.ThrowsArgumentNull(() => LinkShare.BitlyLogin = null, "value");
}
[Fact]
public void BitlyLoginUsesScopeStorage()
{
// Arrange
var value = "value";
// Act
LinkShare.BitlyLogin = value;
// Assert
Assert.Equal(LinkShare.BitlyLogin, value);
Assert.Equal(ScopeStorage.CurrentScope[LinkShare._bitlyLogin], value);
}
[Fact]
public void RenderWithNullPageTitle_ThrowsException()
{
Assert.ThrowsArgumentNullOrEmptyString(
() => LinkShare.GetHtml(null).ToString(),
"pageTitle");
}
[Fact]
public void Render_WithFacebook_Works()
{
string actualHTML = LinkShare.GetHtml("page-title", "www.foo.com", linkSites: LinkShareSite.Facebook).ToString();
string expectedHTML =
"<a href=\"http://www.facebook.com/sharer.php?u=www.foo.com&amp;t=page-title\" target=\"_blank\" title=\"Share on Facebook\"><img alt=\"Share on Facebook\" src=\"http://www.facebook.com/favicon.ico\" style=\"border:0; height:16px; width:16px; margin:0 1px;\" title=\"Share on Facebook\" /></a>";
UnitTestHelper.AssertEqualsIgnoreWhitespace(actualHTML, expectedHTML);
}
[Fact]
public void Render_WithFacebookAndDigg_Works()
{
string actualHTML = LinkShare.GetHtml("page-title", "www.foo.com", linkSites: new[] { LinkShareSite.Facebook, LinkShareSite.Digg }).ToString();
string expectedHTML =
"<a href=\"http://www.facebook.com/sharer.php?u=www.foo.com&amp;t=page-title\" target=\"_blank\" title=\"Share on Facebook\"><img alt=\"Share on Facebook\" src=\"http://www.facebook.com/favicon.ico\" style=\"border:0; height:16px; width:16px; margin:0 1px;\" title=\"Share on Facebook\" /></a><a href=\"http://digg.com/submit?url=www.foo.com&amp;title=page-title\" target=\"_blank\" title=\"Digg!\"><img alt=\"Digg!\" src=\"http://digg.com/img/badges/16x16-digg-guy.gif\" style=\"border:0; height:16px; width:16px; margin:0 1px;\" title=\"Digg!\" /></a>";
UnitTestHelper.AssertEqualsIgnoreWhitespace(actualHTML, expectedHTML);
}
[Fact]
public void Render_WithFacebook_RendersAnchorTitle()
{
string actualHTML = LinkShare.GetHtml("page-title", "www.foo.com", linkSites: LinkShareSite.Facebook).ToString();
string expectedHtml = @"<a href=""http://www.facebook.com/sharer.php?u=www.foo.com&amp;t=page-title"" target=""_blank"" title=""Share on Facebook"">
<img alt=""Share on Facebook"" src=""http://www.facebook.com/favicon.ico"" style=""border:0; height:16px; width:16px; margin:0 1px;"" title=""Share on Facebook"" />
</a>";
UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedHtml, actualHTML);
}
[Fact]
public void LinkShare_GetSitesInOrderReturnsAllSitesWhenArgumentIsNull()
{
// Act and Assert
var result = LinkShare.GetSitesInOrder(linkSites: null);
Assert.Equal(_allLinkShareSites, result.ToArray());
}
[Fact]
public void LinkShare_GetSitesInOrderReturnsAllSitesWhenArgumentIEmpty()
{
// Act
var result = LinkShare.GetSitesInOrder(linkSites: new LinkShareSite[] { });
// Assert
Assert.Equal(_allLinkShareSites, result.ToArray());
}
[Fact]
public void LinkShare_GetSitesInOrderReturnsAllSitesWhenAllIsFirstItem()
{
// Act
var result = LinkShare.GetSitesInOrder(linkSites: new[] { LinkShareSite.All, LinkShareSite.Reddit });
// Assert
Assert.Equal(_allLinkShareSites, result.ToArray());
}
[Fact]
public void LinkShare_GetSitesInOrderReturnsSitesInOrderWhenAllIsNotFirstItem()
{
// Act
var result = LinkShare.GetSitesInOrder(linkSites: new[] { LinkShareSite.Reddit, LinkShareSite.Facebook, LinkShareSite.All });
// Assert
Assert.Equal(new[]
{
LinkShareSite.Reddit, LinkShareSite.Facebook, LinkShareSite.Delicious, LinkShareSite.Digg,
LinkShareSite.GoogleBuzz, LinkShareSite.StumbleUpon, LinkShareSite.Twitter
}, result.ToArray());
}
[Fact]
public void LinkShare_EncodesParameters()
{
// Arrange
var expectedHtml =
@"<a href=""http://reddit.com/submit?url=www.foo.com&amp;title=%26%26"" target=""_blank"" title=""Reddit!"">
<img alt=""Reddit!"" src=""http://www.Reddit.com/favicon.ico"" style=""border:0; height:16px; width:16px; margin:0 1px;"" title=""Reddit!"" />
</a>
<a href=""http://twitter.com/home/?status=%26%26%3a+www.foo.com%2c+(via+%40%40%3cTweeter+Bot%3e)+I+%3c3+Tweets"" target=""_blank"" title=""Share on Twitter"">
<img alt=""Share on Twitter"" src=""http://twitter.com/favicon.ico"" style=""border:0; height:16px; width:16px; margin:0 1px;"" title=""Share on Twitter"" />
</a>";
// Act
var actualHtml = LinkShare.GetHtml("&&", "www.foo.com", "<Tweeter Bot>", "I <3 Tweets", LinkShareSite.Reddit, LinkShareSite.Twitter).ToString();
// Assert
UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedHtml, actualHtml);
}
[Fact]
public void LinkshareRendersValidXhtml()
{
string result = "<html> <head> \n <title> </title> \n </head> \n <body> <div> \n" +
LinkShare.GetHtml("any<>title", "my test page <>") +
"\n </div> </body> \n </html>";
HtmlString htmlResult = new HtmlString(result);
XhtmlAssert.Validate1_0(htmlResult);
}
}
}

View File

@@ -0,0 +1,57 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Linq;
using Xunit;
namespace Microsoft.Web.Helpers.Test
{
public class MapsTest
{
[Fact]
public void GetDirectionsQueryReturnsLocationIfNotEmpty()
{
// Arrange
var location = "a%";
var latitude = "12.34";
var longitude = "-56.78";
// Act
string result = Maps.GetDirectionsQuery(location, latitude, longitude);
// Assert
Assert.Equal("a%25", result);
}
[Fact]
public void GetDirectionsQueryReturnsLatitudeLongitudeIfLocationIsEmpty()
{
// Arrange
var location = "";
var latitude = "12.34%";
var longitude = "-&56.78";
// Act
string result = Maps.GetDirectionsQuery(location, latitude, longitude);
// Assert
Assert.Equal("12.34%25%2c-%2656.78", result);
}
[Fact]
public void GetDirectionsQueryUsesSpecifiedEncoder()
{
// Arrange
var location = "24 gnidliuB tfosorciM";
var latitude = "12.34%";
var longitude = "-&56.78";
Func<string, string> encoder = k => new String(k.Reverse().ToArray());
// Act
string result = Maps.GetDirectionsQuery(location, latitude, longitude, encoder);
// Assert
Assert.Equal("Microsoft Building 42", result);
}
}
}

View File

@@ -0,0 +1,108 @@
<?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>{2C653A66-8159-4A41-954F-A67915DFDA87}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Microsoft.Web.Helpers.Test</RootNamespace>
<AssemblyName>Microsoft.Web.Helpers.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="System" />
<Reference Include="System.Web" />
<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>
<Compile Include="AnalyticsTest.cs" />
<Compile Include="BingTest.cs" />
<Compile Include="FacebookTest.cs" />
<Compile Include="FileUploadTest.cs" />
<Compile Include="GamerCardTest.cs" />
<Compile Include="GravatarTest.cs" />
<Compile Include="LinkShareTest.cs" />
<Compile Include="MapsTest.cs" />
<Compile Include="PreAppStartCodeTest.cs" />
<Compile Include="ThemesTest.cs" />
<Compile Include="TwitterTest.cs" />
<Compile Include="VideoTest.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="ReCaptchaTest.cs" />
<Compile Include="UrlBuilderTest.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\Microsoft.Web.Helpers\Microsoft.Web.Helpers.csproj">
<Project>{0C7CE809-0F72-4C19-8C64-D6573E4D9521}</Project>
<Name>Microsoft.Web.Helpers</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.Razor\System.Web.Razor.csproj">
<Project>{8F18041B-9410-4C36-A9C5-067813DF5F31}</Project>
<Name>System.Web.Razor</Name>
</ProjectReference>
<ProjectReference Include="..\..\src\System.Web.WebPages.Razor\System.Web.WebPages.Razor.csproj">
<Project>{0939B11A-FE4E-4BA1-8AD6-D97741EE314F}</Project>
<Name>System.Web.WebPages.Razor</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>
<ProjectReference Include="..\System.Web.Helpers.Test\System.Web.Helpers.Test.csproj">
<Project>{D3313BDF-8071-4AC8-9D98-ABF7F9E88A57}</Project>
<Name>System.Web.Helpers.Test</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
</Project>

View File

@@ -0,0 +1,33 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Linq;
using System.Web.WebPages.Razor;
using System.Web.WebPages.TestUtils;
using Xunit;
namespace Microsoft.Web.Helpers.Test
{
public class PreApplicationStartCodeTest
{
[Fact]
public void StartTest()
{
AppDomainUtils.RunInSeparateAppDomain(() =>
{
// Act
AppDomainUtils.SetPreAppStartStage();
PreApplicationStartCode.Start();
// Assert
var imports = WebPageRazorHost.GetGlobalImports();
Assert.True(imports.Any(ns => ns.Equals("Microsoft.Web.Helpers")));
});
}
[Fact]
public void TestPreAppStartClass()
{
PreAppStartTestHelper.TestPreAppStartClass(typeof(PreApplicationStartCode));
}
}
}

View File

@@ -0,0 +1,36 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Microsoft.Web.Helpers.Test")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("MSIT")]
[assembly: AssemblyProduct("Microsoft.Web.Helpers.Test")]
[assembly: AssemblyCopyright("Copyright <20> MSIT 2010")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@@ -0,0 +1,253 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Web;
using System.Web.Helpers.Test;
using System.Web.TestUtil;
using System.Web.WebPages.Scope;
using Moq;
using Xunit;
using Assert = Microsoft.TestCommon.AssertEx;
namespace Microsoft.Web.Helpers.Test
{
public class ReCaptchaTest
{
[Fact]
public void ReCaptchaOptionsMissingWhenNoOptionsAndDefaultRendering()
{
var html = ReCaptcha.GetHtml(GetContext(), "PUBLIC_KEY");
UnitTestHelper.AssertEqualsIgnoreWhitespace(
@"<script src=""http://www.google.com/recaptcha/api/challenge?k=PUBLIC_KEY"" type=""text/javascript""></script>" +
@"<noscript>" +
@"<iframe frameborder=""0"" height=""300px"" src=""http://www.google.com/recaptcha/api/noscript?k=PUBLIC_KEY"" width=""500px""></iframe><br/><br/>" +
@"<textarea cols=""40"" name=""recaptcha_challenge_field"" rows=""3""></textarea>" +
@"<input name=""recaptcha_response_field"" type=""hidden"" value=""manual_challenge""/>" +
@"</noscript>",
html.ToString());
XhtmlAssert.Validate1_0(html, addRoot: true);
}
[Fact]
public void ReCaptchaOptionsWhenOneOptionAndDefaultRendering()
{
var html = ReCaptcha.GetHtml(GetContext(), "PUBLIC_KEY", options: new { theme = "white" });
UnitTestHelper.AssertEqualsIgnoreWhitespace(
@"<script type=""text/javascript"">var RecaptchaOptions={""theme"":""white""};</script>" +
@"<script src=""http://www.google.com/recaptcha/api/challenge?k=PUBLIC_KEY"" type=""text/javascript""></script>" +
@"<noscript>" +
@"<iframe frameborder=""0"" height=""300px"" src=""http://www.google.com/recaptcha/api/noscript?k=PUBLIC_KEY"" width=""500px""></iframe><br/><br/>" +
@"<textarea cols=""40"" name=""recaptcha_challenge_field"" rows=""3""></textarea>" +
@"<input name=""recaptcha_response_field"" type=""hidden"" value=""manual_challenge""/>" +
@"</noscript>",
html.ToString());
XhtmlAssert.Validate1_0(html, addRoot: true);
}
[Fact]
public void ReCaptchaOptionsWhenMultipleOptionsAndDefaultRendering()
{
var html = ReCaptcha.GetHtml(GetContext(), "PUBLIC_KEY", options: new { theme = "white", tabindex = 5 });
UnitTestHelper.AssertEqualsIgnoreWhitespace(
@"<script type=""text/javascript"">var RecaptchaOptions={""theme"":""white"",""tabindex"":5};</script>" +
@"<script src=""http://www.google.com/recaptcha/api/challenge?k=PUBLIC_KEY"" type=""text/javascript""></script>" +
@"<noscript>" +
@"<iframe frameborder=""0"" height=""300px"" src=""http://www.google.com/recaptcha/api/noscript?k=PUBLIC_KEY"" width=""500px""></iframe><br/><br/>" +
@"<textarea cols=""40"" name=""recaptcha_challenge_field"" rows=""3""></textarea>" +
@"<input name=""recaptcha_response_field"" type=""hidden"" value=""manual_challenge""/>" +
@"</noscript>",
html.ToString());
XhtmlAssert.Validate1_0(html, addRoot: true);
}
[Fact]
public void ReCaptchaOptionsWhenMultipleOptionsFromDictionaryAndDefaultRendering()
{
// verifies that a dictionary will serialize the same as a projection
var options = new Dictionary<string, object> { { "theme", "white" }, { "tabindex", 5 } };
var html = ReCaptcha.GetHtml(GetContext(), "PUBLIC_KEY", options: options);
UnitTestHelper.AssertEqualsIgnoreWhitespace(
@"<script type=""text/javascript"">var RecaptchaOptions={""theme"":""white"",""tabindex"":5};</script>" +
@"<script src=""http://www.google.com/recaptcha/api/challenge?k=PUBLIC_KEY"" type=""text/javascript""></script>" +
@"<noscript>" +
@"<iframe frameborder=""0"" height=""300px"" src=""http://www.google.com/recaptcha/api/noscript?k=PUBLIC_KEY"" width=""500px""></iframe><br/><br/>" +
@"<textarea cols=""40"" name=""recaptcha_challenge_field"" rows=""3""></textarea>" +
@"<input name=""recaptcha_response_field"" type=""hidden"" value=""manual_challenge""/>" +
@"</noscript>",
html.ToString());
XhtmlAssert.Validate1_0(html, addRoot: true);
}
[Fact]
public void RenderUsesLastError()
{
HttpContextBase context = GetContext();
ReCaptcha.HandleValidateResponse(context, "false\nincorrect-captcha-sol");
var html = ReCaptcha.GetHtml(context, "PUBLIC_KEY");
UnitTestHelper.AssertEqualsIgnoreWhitespace(
@"<script src=""http://www.google.com/recaptcha/api/challenge?k=PUBLIC_KEY&amp;error=incorrect-captcha-sol"" type=""text/javascript""></script>" +
@"<noscript>" +
@"<iframe frameborder=""0"" height=""300px"" src=""http://www.google.com/recaptcha/api/noscript?k=PUBLIC_KEY"" width=""500px""></iframe><br/><br/>" +
@"<textarea cols=""40"" name=""recaptcha_challenge_field"" rows=""3""></textarea>" +
@"<input name=""recaptcha_response_field"" type=""hidden"" value=""manual_challenge""/>" +
@"</noscript>",
html.ToString());
XhtmlAssert.Validate1_0(html, addRoot: true);
}
[Fact]
public void RenderWhenConnectionIsSecure()
{
var html = ReCaptcha.GetHtml(GetContext(isSecure: true), "PUBLIC_KEY");
UnitTestHelper.AssertEqualsIgnoreWhitespace(
@"<script src=""https://www.google.com/recaptcha/api/challenge?k=PUBLIC_KEY"" type=""text/javascript""></script>" +
@"<noscript>" +
@"<iframe frameborder=""0"" height=""300px"" src=""https://www.google.com/recaptcha/api/noscript?k=PUBLIC_KEY"" width=""500px""></iframe><br/><br/>" +
@"<textarea cols=""40"" name=""recaptcha_challenge_field"" rows=""3""></textarea>" +
@"<input name=""recaptcha_response_field"" type=""hidden"" value=""manual_challenge""/>" +
@"</noscript>",
html.ToString());
XhtmlAssert.Validate1_0(html, addRoot: true);
}
[Fact]
public void ValidateThrowsWhenRemoteAddressNotAvailable()
{
HttpContextBase context = GetContext();
VirtualPathUtilityBase virtualPathUtility = GetVirtualPathUtility();
context.Request.Form["recaptcha_challenge_field"] = "CHALLENGE";
context.Request.Form["recaptcha_response_field"] = "RESPONSE";
Assert.Throws<InvalidOperationException>(() => { ReCaptcha.Validate(context, privateKey: "PRIVATE_KEY", virtualPathUtility: virtualPathUtility).ToString(); }, "The captcha cannot be validated because the remote address was not found in the request.");
}
[Fact]
public void ValidateReturnsFalseWhenChallengeNotPosted()
{
HttpContextBase context = GetContext();
VirtualPathUtilityBase virtualPathUtility = GetVirtualPathUtility();
context.Request.ServerVariables["REMOTE_ADDR"] = "127.0.0.1";
Assert.False(ReCaptcha.Validate(context, privateKey: "PRIVATE_KEY", virtualPathUtility: virtualPathUtility));
}
[Fact]
public void ValidatePostData()
{
HttpContextBase context = GetContext();
VirtualPathUtilityBase virtualPathUtility = GetVirtualPathUtility();
context.Request.ServerVariables["REMOTE_ADDR"] = "127.0.0.1";
context.Request.Form["recaptcha_challenge_field"] = "CHALLENGE";
context.Request.Form["recaptcha_response_field"] = "RESPONSE";
Assert.Equal("privatekey=PRIVATE_KEY&remoteip=127.0.0.1&challenge=CHALLENGE&response=RESPONSE",
ReCaptcha.GetValidatePostData(context, "PRIVATE_KEY", virtualPathUtility));
}
[Fact]
public void ValidatePostDataWhenNoResponse()
{
// Arrange
HttpContextBase context = GetContext();
VirtualPathUtilityBase virtualPathUtility = GetVirtualPathUtility();
context.Request.ServerVariables["REMOTE_ADDR"] = "127.0.0.1";
context.Request.Form["recaptcha_challenge_field"] = "CHALLENGE";
// Act
var validatePostData = ReCaptcha.GetValidatePostData(context, "PRIVATE_KEY", virtualPathUtility);
// Assert
Assert.Equal("privatekey=PRIVATE_KEY&remoteip=127.0.0.1&challenge=CHALLENGE&response=", validatePostData);
}
[Fact]
public void ValidateResponseReturnsFalseOnEmptyReCaptchaResponse()
{
HttpContextBase context = GetContext();
Assert.False(ReCaptcha.HandleValidateResponse(context, ""));
Assert.Equal(String.Empty, ReCaptcha.GetLastError(context));
}
[Fact]
public void ValidateResponseReturnsTrueOnSuccess()
{
HttpContextBase context = GetContext();
Assert.True(ReCaptcha.HandleValidateResponse(context, "true\nsuccess"));
Assert.Equal(String.Empty, ReCaptcha.GetLastError(context));
}
[Fact]
public void ValidateResponseReturnsFalseOnError()
{
HttpContextBase context = GetContext();
Assert.False(ReCaptcha.HandleValidateResponse(context, "false\nincorrect-captcha-sol"));
Assert.Equal("incorrect-captcha-sol", ReCaptcha.GetLastError(context));
}
[Fact]
public void ReCaptchaPrivateKeyThowsWhenSetToNull()
{
Assert.ThrowsArgumentNull(() => ReCaptcha.PrivateKey = null, "value");
}
[Fact]
public void ReCaptchaPrivateKeyUsesScopeStorage()
{
// Arrange
var value = "value";
// Act
ReCaptcha.PrivateKey = value;
// Assert
Assert.Equal(ReCaptcha.PrivateKey, value);
Assert.Equal(ScopeStorage.CurrentScope[ReCaptcha._privateKey], value);
}
[Fact]
public void PublicKeyThowsWhenSetToNull()
{
Assert.ThrowsArgumentNull(() => ReCaptcha.PublicKey = null, "value");
}
[Fact]
public void ReCaptchaPublicKeyUsesScopeStorage()
{
// Arrange
var value = "value";
// Act
ReCaptcha.PublicKey = value;
// Assert
Assert.Equal(ReCaptcha.PublicKey, value);
Assert.Equal(ScopeStorage.CurrentScope[ReCaptcha._publicKey], value);
}
private HttpContextBase GetContext(bool isSecure = false)
{
// mock HttpRequest
Mock<HttpRequestBase> requestMock = new Mock<HttpRequestBase>();
requestMock.Setup(request => request.IsSecureConnection).Returns(isSecure);
requestMock.Setup(request => request.Form).Returns(new NameValueCollection());
requestMock.Setup(request => request.ServerVariables).Returns(new NameValueCollection());
// mock HttpContext
Mock<HttpContextBase> contextMock = new Mock<HttpContextBase>();
contextMock.Setup(context => context.Items).Returns(new Hashtable());
contextMock.Setup(context => context.Request).Returns(requestMock.Object);
return contextMock.Object;
}
private static VirtualPathUtilityBase GetVirtualPathUtility()
{
var virtualPathUtility = new Mock<VirtualPathUtilityBase>();
virtualPathUtility.Setup(c => c.ToAbsolute(It.IsAny<string>())).Returns<string>(_ => _);
return virtualPathUtility.Object;
}
}
}

View File

@@ -0,0 +1,374 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Web.Hosting;
using System.Web.WebPages.Scope;
using Moq;
using Xunit;
using Assert = Microsoft.TestCommon.AssertEx;
namespace Microsoft.Web.Helpers.Test
{
public class ThemesTest
{
[Fact]
public void Initialize_WithBadParams_Throws()
{
// Arrange
var mockVpp = new Mock<VirtualPathProvider>().Object;
var scope = new ScopeStorageDictionary();
// Act and Assert
Assert.ThrowsArgumentNullOrEmptyString(() => new ThemesImplementation(mockVpp, scope).Initialize(null, "foo"), "themeDirectory");
Assert.ThrowsArgumentNullOrEmptyString(() => new ThemesImplementation(mockVpp, scope).Initialize("", "foo"), "themeDirectory");
Assert.ThrowsArgumentNullOrEmptyString(() => new ThemesImplementation(mockVpp, scope).Initialize("~/folder", null), "defaultTheme");
Assert.ThrowsArgumentNullOrEmptyString(() => new ThemesImplementation(mockVpp, scope).Initialize("~/folder", ""), "defaultTheme");
}
[Fact]
public void CurrentThemeThrowsIfAssignedNullOrEmpty()
{
// Arrange
var mockVpp = new Mock<VirtualPathProvider>().Object;
var scope = new ScopeStorageDictionary();
var themesImpl = new ThemesImplementation(mockVpp, scope);
// Act and Assert
Assert.ThrowsArgumentNullOrEmptyString(() => { themesImpl.CurrentTheme = null; }, "value");
Assert.ThrowsArgumentNullOrEmptyString(() => { themesImpl.CurrentTheme = String.Empty; }, "value");
}
[Fact]
public void InvokingPropertiesAndMethodsBeforeInitializationThrows()
{
// Arrange
var mockVpp = new Mock<VirtualPathProvider>().Object;
var scope = new ScopeStorageDictionary();
var themesImpl = new ThemesImplementation(mockVpp, scope);
// Act and Assert
Assert.Throws<InvalidOperationException>(() => themesImpl.CurrentTheme = "Foo",
@"You must call the ""Themes.Initialize"" method before you call any other method of the ""Themes"" class.");
Assert.Throws<InvalidOperationException>(() => { var x = themesImpl.CurrentTheme; },
@"You must call the ""Themes.Initialize"" method before you call any other method of the ""Themes"" class.");
Assert.Throws<InvalidOperationException>(() => { var x = themesImpl.AvailableThemes; },
@"You must call the ""Themes.Initialize"" method before you call any other method of the ""Themes"" class.");
Assert.Throws<InvalidOperationException>(() => { var x = themesImpl.DefaultTheme; },
@"You must call the ""Themes.Initialize"" method before you call any other method of the ""Themes"" class.");
Assert.Throws<InvalidOperationException>(() => { var x = themesImpl.GetResourcePath("baz"); },
@"You must call the ""Themes.Initialize"" method before you call any other method of the ""Themes"" class.");
Assert.Throws<InvalidOperationException>(() => { var x = themesImpl.GetResourcePath("baz", "some-file"); },
@"You must call the ""Themes.Initialize"" method before you call any other method of the ""Themes"" class.");
}
[Fact]
public void InitializeThrowsIfDefaultThemeDirectoryDoesNotExist()
{
// Arrange
var defaultTheme = "default-theme";
var themeDirectory = "theme-directory";
var scope = new ScopeStorageDictionary();
var themesImpl = new ThemesImplementation(GetVirtualPathProvider(themeDirectory, new Dir("not-default-theme")), scope);
// Act And Assert
Assert.ThrowsArgument(
() => themesImpl.Initialize(themeDirectory: themeDirectory, defaultTheme: defaultTheme),
"defaultTheme",
"Unknown theme 'default-theme'. Ensure that a directory labeled 'default-theme' exists under the theme directory.");
}
[Fact]
public void ThemesImplUsesScopeStorageToStoreProperties()
{
// Arrange
var defaultTheme = "default-theme";
var themeDirectory = "theme-directory";
var scope = new ScopeStorageDictionary();
var themesImpl = new ThemesImplementation(GetVirtualPathProvider(themeDirectory, new Dir(defaultTheme)), scope);
// Act
themesImpl.Initialize(themeDirectory: themeDirectory, defaultTheme: defaultTheme);
// Ensure Theme use scope storage to store properties
Assert.Equal(scope[ThemesImplementation.ThemesInitializedKey], true);
Assert.Equal(scope[ThemesImplementation.ThemeDirectoryKey], themeDirectory);
Assert.Equal(scope[ThemesImplementation.DefaultThemeKey], defaultTheme);
}
[Fact]
public void ThemesImplUsesDefaultThemeWhenNoCurrentThemeIsSpecified()
{
// Arrange
var defaultTheme = "default-theme";
var themeDirectory = "theme-directory";
var scope = new ScopeStorageDictionary();
var themesImpl = new ThemesImplementation(GetVirtualPathProvider(themeDirectory, new Dir(defaultTheme)), scope);
themesImpl.Initialize(themeDirectory, defaultTheme);
// Act and Assert
// CurrentTheme falls back to default theme when null
Assert.Equal(themesImpl.CurrentTheme, defaultTheme);
}
[Fact]
public void ThemesImplThrowsIfCurrentThemeIsInvalid()
{
// Arrange
var defaultTheme = "default-theme";
var themeDirectory = "theme-directory";
var themesImpl = new ThemesImplementation(GetVirtualPathProvider(themeDirectory, new Dir(defaultTheme), new Dir("not-a-random-value")), new ScopeStorageDictionary());
themesImpl.Initialize(themeDirectory, defaultTheme);
// Act and Assert
Assert.ThrowsArgument(() => themesImpl.CurrentTheme = "random-value",
"value",
"Unknown theme 'random-value'. Ensure that a directory labeled 'random-value' exists under the theme directory.");
}
[Fact]
public void ThemesImplUsesScopeStorageToStoreCurrentTheme()
{
// Arrange
var defaultTheme = "default-theme";
var themeDirectory = "theme-directory";
var currentThemeDir = "custom-theme-dir";
var scope = new ScopeStorageDictionary();
var themesImpl = new ThemesImplementation(GetVirtualPathProvider(themeDirectory, new Dir(defaultTheme), new Dir("custom-theme-dir")), scope);
// Act
themesImpl.Initialize(themeDirectory, defaultTheme);
themesImpl.CurrentTheme = currentThemeDir;
// Assert
Assert.Equal(scope[ThemesImplementation.CurrentThemeKey], currentThemeDir);
}
[Fact]
public void GetResourcePathThrowsIfCurrentDirectoryIsNull()
{
// Arrange
var themesImpl = new ThemesImplementation(scopeStorage: new ScopeStorageDictionary(),
vpp: GetVirtualPathProvider("themes", new Dir("default"), new Dir("mobile"), new Dir(@"mobile", "wp7.css")));
themesImpl.Initialize("themes", "default");
// Act and Assert
Assert.ThrowsArgumentNull(() => themesImpl.GetResourcePath(folder: null, fileName: "wp7.css"), "folder");
}
[Fact]
public void GetResourcePathThrowsIfFileNameIsNullOrEmpty()
{
// Arrange
var themesImpl = new ThemesImplementation(scopeStorage: new ScopeStorageDictionary(),
vpp: GetVirtualPathProvider("themes", new Dir("default"), new Dir("mobile"), new Dir(@"mobile", "wp7.css")));
themesImpl.Initialize("themes", "default");
// Act and Assert
Assert.ThrowsArgumentNullOrEmptyString(() => themesImpl.GetResourcePath(folder: String.Empty, fileName: null), "fileName");
Assert.ThrowsArgumentNullOrEmptyString(() => themesImpl.GetResourcePath(folder: String.Empty, fileName: String.Empty), "fileName");
}
[Fact]
public void GetResourcePathReturnsItemFromThemeRootIfAvailable()
{
// Arrange
var themesImpl = new ThemesImplementation(scopeStorage: new ScopeStorageDictionary(),
vpp: GetVirtualPathProvider("themes", new Dir("default"), new Dir("mobile"), new Dir(@"mobile", "wp7.css")));
themesImpl.Initialize("themes", "default");
// Act
themesImpl.CurrentTheme = "mobile";
var themePath = themesImpl.GetResourcePath(fileName: "wp7.css");
// Assert
Assert.Equal(themePath, @"themes/mobile/wp7.css");
}
[Fact]
public void GetResourcePathReturnsItemFromCurrentThemeDirectoryIfAvailable()
{
// Arrange
var themesImpl = new ThemesImplementation(scopeStorage: new ScopeStorageDictionary(),
vpp: GetVirtualPathProvider("themes", new Dir("default"), new Dir("mobile"), new Dir(@"mobile\styles", "wp7.css"), new Dir(@"default\styles", "main.css")));
themesImpl.Initialize("themes", "default");
// Act
themesImpl.CurrentTheme = "mobile";
var themePath = themesImpl.GetResourcePath(folder: "styles", fileName: "wp7.css");
// Assert
Assert.Equal(themePath, @"themes/mobile/styles/wp7.css");
}
[Fact]
public void GetResourcePathReturnsItemFromDefaultThemeDirectoryIfNotFoundInCurrentThemeDirectory()
{
// Arrange
var themesImpl = new ThemesImplementation(scopeStorage: new ScopeStorageDictionary(),
vpp: GetVirtualPathProvider("themes", new Dir("default"), new Dir("mobile"), new Dir(@"mobile\styles", "wp7.css"), new Dir(@"default\styles", "main.css")));
themesImpl.Initialize("themes", "default");
// Act
themesImpl.CurrentTheme = "mobile";
var themePath = themesImpl.GetResourcePath(folder: "styles", fileName: "main.css");
// Assert
Assert.Equal(themePath, @"themes/default/styles/main.css");
}
[Fact]
public void GetResourcePathReturnsNullIfDirectoryDoesNotExist()
{
// Arrange
var themesImpl = new ThemesImplementation(scopeStorage: new ScopeStorageDictionary(),
vpp: GetVirtualPathProvider("themes", new Dir("default"), new Dir("mobile"), new Dir(@"mobile\styles", "wp7.css"), new Dir(@"default\styles", "main.css")));
themesImpl.Initialize("themes", "default");
// Act
themesImpl.CurrentTheme = "mobile";
var themePath = themesImpl.GetResourcePath(folder: "does-not-exist", fileName: "main.css");
// Assert
Assert.Null(themePath);
}
[Fact]
public void GetResourcePathReturnsNullIfItemNotFoundInCurrentAndDefaultThemeDirectories()
{
// Arrange
var themesImpl = new ThemesImplementation(scopeStorage: new ScopeStorageDictionary(),
vpp: GetVirtualPathProvider("themes", new Dir("default"), new Dir("mobile"), new Dir(@"mobile\styles", "wp7.css"), new Dir(@"default\styles", "main.css")));
themesImpl.Initialize("themes", "default");
// Act
themesImpl.CurrentTheme = "mobile";
var themePath = themesImpl.GetResourcePath(folder: "styles", fileName: "awesome-blinking-text.css");
// Assert
Assert.Null(themePath);
}
[Fact]
public void AvaliableThemesReturnsTopLevelDirectoriesUnderThemeDirectory()
{
// Arrange
var themesImpl = new ThemesImplementation(scopeStorage: new ScopeStorageDictionary(),
vpp: GetVirtualPathProvider("themes", new Dir("default"), new Dir("mobile"), new Dir("rotary-phone")));
// Act
themesImpl.Initialize("themes", "default");
var themes = themesImpl.AvailableThemes;
// Assert
Assert.Equal(3, themes.Count);
Assert.Equal(themes[0], "default");
Assert.Equal(themes[1], "mobile");
Assert.Equal(themes[2], "rotary-phone");
}
/// <remarks>
/// // folder structure:
/// // /root
/// // /foo
/// // /bar.cs
/// // testing that a file specified as foo/bar in folder root will return null
/// </remarks>
[Fact]
public void FileWithSlash_ReturnsNull()
{
// Arrange
var themesImpl = new ThemesImplementation(scopeStorage: new ScopeStorageDictionary(),
vpp: GetVirtualPathProvider("themes", new Dir("default"), new Dir("root"), new Dir(@"root\foo", "wp7.css"), new Dir(@"default\styles", "main.css")));
// Act
var actual = themesImpl.FindMatchingFile("root", "foo/bar.cs");
// Assert
Assert.Null(actual);
}
[Fact]
public void DirectoryWithNoFilesReturnsNull()
{
// Arrange
var themesImpl = new ThemesImplementation(scopeStorage: new ScopeStorageDictionary(),
vpp: GetVirtualPathProvider("themes", new Dir("default"), new Dir("empty-dir")));
// Act
var actual = themesImpl.FindMatchingFile(@"themes\empty-dir", "main.css");
// Assert
Assert.Null(actual);
}
[Fact]
public void MatchingFiles_ReturnsCorrectFile()
{
// Arrange
var themesImpl = new ThemesImplementation(scopeStorage: new ScopeStorageDictionary(),
vpp: GetVirtualPathProvider("themes", new Dir(@"nomatchingfiles", "foo.cs")));
// Act
var bar = themesImpl.FindMatchingFile(@"themes\nomatchingfiles", "bar.cs");
var foo = themesImpl.FindMatchingFile(@"themes\nomatchingfiles", "foo.cs");
// Assert
Assert.Null(bar);
Assert.Equal(@"themes/nomatchingfiles/foo.cs", foo);
}
private static VirtualPathProvider GetVirtualPathProvider(string themeRoot, params Dir[] fileSystem)
{
var mockVpp = new Mock<VirtualPathProvider>();
var dirRoot = new Mock<VirtualDirectory>(themeRoot);
var themeDirectories = new List<VirtualDirectory>();
foreach (var directory in fileSystem)
{
var dir = new Mock<VirtualDirectory>(directory.Name);
var directoryPath = themeRoot + '\\' + directory.Name;
dir.SetupGet(d => d.Name).Returns(directory.Name);
mockVpp.Setup(c => c.GetDirectory(It.Is<string>(p => p.Equals(directoryPath, StringComparison.OrdinalIgnoreCase)))).Returns(dir.Object);
var fileList = new List<VirtualFile>();
foreach (var item in directory.Files)
{
var filePath = directoryPath + '\\' + item;
var file = new Mock<VirtualFile>(filePath);
file.SetupGet(f => f.Name).Returns(item);
fileList.Add(file.Object);
}
dir.SetupGet(c => c.Files).Returns(fileList);
themeDirectories.Add(dir.Object);
}
dirRoot.SetupGet(c => c.Directories).Returns(themeDirectories);
mockVpp.Setup(c => c.GetDirectory(themeRoot)).Returns(dirRoot.Object);
return mockVpp.Object;
}
private class Dir
{
public Dir(string name, params string[] files)
{
Name = name;
Files = files;
}
public string Name { get; private set; }
public IEnumerable<string> Files { get; private set; }
}
}
}

View File

@@ -0,0 +1,483 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Web;
using System.Web.Helpers;
using System.Web.Helpers.Test;
using System.Web.TestUtil;
using Xunit;
using Assert = Microsoft.TestCommon.AssertEx;
namespace Microsoft.Web.Helpers.Test
{
public class TwitterTest
{
/// <summary>
///A test for Profile
///</summary>
[Fact]
public void Profile_ReturnsValidData()
{
// Arrange
string twitterUserName = "my-userName";
int width = 100;
int height = 100;
string backgroundShellColor = "my-backgroundShellColor";
string shellColor = "my-shellColor";
string tweetsBackgroundColor = "tweetsBackgroundColor";
string tweetsColor = "tweets-color";
string tweetsLinksColor = "tweets Linkcolor";
bool scrollBar = false;
bool loop = false;
bool live = false;
bool hashTags = false;
bool timestamp = false;
bool avatars = false;
var behavior = "all";
int searchInterval = 10;
// Act
string actual = Twitter.Profile(twitterUserName, width, height, backgroundShellColor, shellColor, tweetsBackgroundColor, tweetsColor, tweetsLinksColor,
5, scrollBar, loop, live, hashTags, timestamp, avatars, behavior, searchInterval).ToString();
// Assert
var json = GetTwitterJSObject(actual);
Assert.Equal(json.type, "profile");
Assert.Equal(json.interval, 1000 * searchInterval);
Assert.Equal(json.width.ToString(), width.ToString());
Assert.Equal(json.height.ToString(), height.ToString());
Assert.Equal(json.theme.shell.background, backgroundShellColor);
Assert.Equal(json.theme.shell.color, shellColor);
Assert.Equal(json.theme.tweets.background, tweetsBackgroundColor);
Assert.Equal(json.theme.tweets.color, tweetsColor);
Assert.Equal(json.theme.tweets.links, tweetsLinksColor);
Assert.Equal(json.features.scrollbar, scrollBar);
Assert.Equal(json.features.loop, loop);
Assert.Equal(json.features.live, live);
Assert.Equal(json.features.hashtags, hashTags);
Assert.Equal(json.features.avatars, avatars);
Assert.Equal(json.features.behavior, behavior.ToLowerInvariant());
Assert.True(actual.Contains(".setUser('my-userName')"));
}
[Fact]
public void ProfileJSEncodesParameters()
{
// Arrange
string twitterUserName = "\"my-userName\'";
string backgroundShellColor = "\\foo";
string shellColor = "<shellColor>\\";
string tweetsBackgroundColor = "<tweetsBackgroundColor";
string tweetsColor = "<tweetsColor>";
string tweetsLinksColor = "<tweetsLinkColor>";
// Act
string actual = Twitter.Profile(twitterUserName, 100, 100, backgroundShellColor, shellColor, tweetsBackgroundColor, tweetsColor, tweetsLinksColor).ToString();
// Assert
Assert.True(actual.Contains("background: '\\\\foo"));
Assert.True(actual.Contains("color: '\\u003cshellColor\\u003e\\\\"));
Assert.True(actual.Contains("background: '\\u003ctweetsBackgroundColor"));
Assert.True(actual.Contains("color: '\\u003ctweetsColor\\u003e"));
Assert.True(actual.Contains("links: '\\u003ctweetsLinkColor\\u003e"));
Assert.True(actual.Contains(".setUser('\\\"my-userName\\u0027')"));
}
[Fact]
public void Search_ReturnsValidData()
{
// Arrange
string search = "awesome-search-term";
int width = 100;
int height = 100;
string title = "cust-title";
string caption = "some caption";
string backgroundShellColor = "background-shell-color";
string shellColor = "shellColorValue";
string tweetsBackgroundColor = "tweetsBackgroundColor";
string tweetsColor = "tweetsColorVal";
string tweetsLinksColor = "tweetsLinkColor";
bool scrollBar = false;
bool loop = false;
bool live = true;
bool hashTags = false;
bool timestamp = true;
bool avatars = true;
bool topTweets = true;
var behavior = "default";
int searchInterval = 10;
// Act
string actual = Twitter.Search(search, width, height, title, caption, backgroundShellColor, shellColor, tweetsBackgroundColor, tweetsColor, tweetsLinksColor, scrollBar,
loop, live, hashTags, timestamp, avatars, topTweets, behavior, searchInterval).ToString();
// Assert
var json = GetTwitterJSObject(actual);
Assert.Equal(json.type, "search");
Assert.Equal(json.search, search);
Assert.Equal(json.interval, 1000 * searchInterval);
Assert.Equal(json.title, title);
Assert.Equal(json.subject, caption);
Assert.Equal(json.width.ToString(), width.ToString());
Assert.Equal(json.height.ToString(), height.ToString());
Assert.Equal(json.theme.shell.background, backgroundShellColor);
Assert.Equal(json.theme.shell.color, shellColor);
Assert.Equal(json.theme.tweets.background, tweetsBackgroundColor);
Assert.Equal(json.theme.tweets.color, tweetsColor);
Assert.Equal(json.theme.tweets.links, tweetsLinksColor);
Assert.Equal(json.features.scrollbar, scrollBar);
Assert.Equal(json.features.loop, loop);
Assert.Equal(json.features.live, live);
Assert.Equal(json.features.hashtags, hashTags);
Assert.Equal(json.features.avatars, avatars);
Assert.Equal(json.features.toptweets, topTweets);
Assert.Equal(json.features.behavior, behavior.ToLowerInvariant());
}
[Fact]
public void SearchJavascriptEncodesParameters()
{
// Arrange
string search = "<script>";
int width = 100;
int height = 100;
string title = "'title'";
string caption = "<caption>";
string backgroundShellColor = "\\foo";
string shellColor = "<shellColor>\\";
string tweetsBackgroundColor = "<tweetsBackgroundColor";
string tweetsColor = "<tweetsColor>";
string tweetsLinksColor = "<tweetsLinkColor>";
// Act
string actual = Twitter.Search(search, width, height, title, caption, backgroundShellColor, shellColor, tweetsBackgroundColor, tweetsColor, tweetsLinksColor).ToString();
// Assert
Assert.True(actual.Contains("search: '\\u003cscript\\u003e'"));
Assert.True(actual.Contains("title: '\\u0027title\\u0027'"));
Assert.True(actual.Contains("subject: '\\u003ccaption\\u003e'"));
Assert.True(actual.Contains("background: '\\\\foo"));
Assert.True(actual.Contains("color: '\\u003cshellColor\\u003e\\\\"));
Assert.True(actual.Contains("background: '\\u003ctweetsBackgroundColor"));
Assert.True(actual.Contains("color: '\\u003ctweetsColor\\u003e"));
Assert.True(actual.Contains("links: '\\u003ctweetsLinkColor\\u003e"));
}
[Fact]
public void SearchWithInvalidArgs_ThrowsArgumentException()
{
Assert.ThrowsArgumentNullOrEmptyString(() => Twitter.Search(null).ToString(), "searchQuery");
}
[Fact]
public void ProfileWithInvalidArgs_ThrowsArgumentException()
{
Assert.ThrowsArgumentNullOrEmptyString(() => Twitter.Profile(null).ToString(), "userName");
}
[Fact]
public void SearchRendersRendersValidXhtml()
{
string result = "<html> <head> \n <title> </title> \n </head> \n <body> \n" +
Twitter.Search("any<>term") +
"\n </body> \n </html>";
HtmlString htmlResult = new HtmlString(result);
XhtmlAssert.Validate1_1(htmlResult);
}
[Fact]
public void SearchEncodesSearchTerms()
{
// Act
string result = Twitter.Search("'any term'", backgroundShellColor: "\"bad-color").ToString();
// Assert
Assert.True(result.Contains(@"background: '\""bad-color',"));
//Assert.True(result.Contains(@"search: @"'\u0027any term\u0027'","));
}
[Fact]
public void ProfileRendersRendersValidXhtml()
{
string result = "<html> <head> \n <title> </title> \n </head> \n <body> \n" +
Twitter.Profile("any<>Name") +
"\n </body> \n </html>";
HtmlString htmlResult = new HtmlString(result);
XhtmlAssert.Validate1_1(htmlResult);
}
[Fact]
public void ProfileEncodesSearchTerms()
{
// Act
string result = Twitter.Profile("'some user'", backgroundShellColor: "\"malformed-color").ToString();
// Assert
Assert.True(result.Contains(@"background: '\""malformed-color'"));
Assert.True(result.Contains("setUser('\\u0027some user\\u0027')"));
}
[Fact]
public void TweetButtonWithDefaultAttributes()
{
// Arrange
string expected = @"<a href=""http://twitter.com/share"" class=""twitter-share-button"" data-count=""vertical"">Tweet</a><script type=""text/javascript"" src=""http://platform.twitter.com/widgets.js""></script>";
// Act
string result = Twitter.TweetButton().ToString();
// Assert
UnitTestHelper.AssertEqualsIgnoreWhitespace(result, expected);
}
[Fact]
public void TweetButtonWithSpeicifedAttributes()
{
// Arrange
string expected = @"<a href=""http://twitter.com/share"" class=""twitter-share-button"" data-text=""tweet-text"" data-url=""http://www.microsoft.com"" data-via=""userName"" data-related=""related-userName:rel-desc"" data-count=""none"">my-share-text</a><script type=""text/javascript"" src=""http://platform.twitter.com/widgets.js""></script>";
// Act
string result = Twitter.TweetButton("none", shareText: "my-share-text", tweetText: "tweet-text", url: "http://www.microsoft.com", language: "en", userName: "userName", relatedUserName: "related-userName", relatedUserDescription: "rel-desc").ToString();
// Assert
UnitTestHelper.AssertEqualsIgnoreWhitespace(result, expected);
}
[Fact]
public void TweetButtonHtmlEncodesValues()
{
// Arrange
string expected = @"<a href=""http://twitter.com/share"" class=""twitter-share-button"" data-text=""&lt;tweet-text>"" data-url=""&lt;http://www.microsoft.com>"" data-via=""&lt;userName>"" data-related=""&lt;related-userName>:&lt;rel-desc>"" data-count=""none"">&lt;Tweet</a><script type=""text/javascript"" src=""http://platform.twitter.com/widgets.js""></script>";
// Act
string result = Twitter.TweetButton("none", shareText: "<Tweet", tweetText: "<tweet-text>", url: "<http://www.microsoft.com>", language: "en", userName: "<userName>", relatedUserName: "<related-userName>", relatedUserDescription: "<rel-desc>").ToString();
// Assert
UnitTestHelper.AssertEqualsIgnoreWhitespace(result, expected);
}
[Fact]
public void FollowButtonWithDefaultParameters()
{
// Arrange
string expected = @"<a href=""http://www.twitter.com/my-twitter-userName""><img src=""http://twitter-badges.s3.amazonaws.com/follow_me-a.png"" alt=""Follow my-twitter-userName on Twitter""/></a>";
// Act
string result = Twitter.FollowButton("my-twitter-userName").ToString();
// Assert
UnitTestHelper.AssertEqualsIgnoreWhitespace(result, expected);
}
[Fact]
public void FollowButtonWithSpecifiedParmeters()
{
// Arrange
string expected = @"<a href=""http://www.twitter.com/my-twitter-userName""><img src=""http://twitter-badges.s3.amazonaws.com/t_logo-b.png"" alt=""Follow my-twitter-userName on Twitter""/></a>";
// Act
string result = Twitter.FollowButton("my-twitter-userName", "t_logo", "b").ToString();
// Assert
UnitTestHelper.AssertEqualsIgnoreWhitespace(result, expected);
}
[Fact]
public void FollowButtonEncodesParameters()
{
// Arrange
string expected = @"<a href=""http://www.twitter.com/http%3a%2f%2fmy-twitter-userName%3cscript""><img src=""http://twitter-badges.s3.amazonaws.com/t_logo-b.png"" alt=""Follow http://my-twitter-userName&lt;script on Twitter""/></a>";
// Act
string result = Twitter.FollowButton("http://my-twitter-userName<script", "t_logo", "b").ToString();
// Assert
UnitTestHelper.AssertEqualsIgnoreWhitespace(result, expected);
}
[Fact]
public void FavesReturnsValidData()
{
// Arrange
string twitterUserName = "my-userName";
string title = "my-title";
string caption = "my-caption";
int width = 100;
int height = 100;
string backgroundShellColor = "my-backgroundShellColor";
string shellColor = "my-shellColor";
string tweetsBackgroundColor = "tweetsBackgroundColor";
string tweetsColor = "tweets-color";
string tweetsLinksColor = "tweets Linkcolor";
int numTweets = 4;
bool scrollBar = false;
bool loop = false;
bool live = false;
bool hashTags = false;
bool timestamp = false;
bool avatars = false;
var behavior = "all";
int searchInterval = 10;
// Act
string actual = Twitter.Faves(twitterUserName, width, height, title, caption, backgroundShellColor, shellColor, tweetsBackgroundColor, tweetsColor, tweetsLinksColor,
numTweets, scrollBar, loop, live, hashTags, timestamp, avatars, "all", searchInterval).ToString();
// Assert
var json = GetTwitterJSObject(actual);
Assert.Equal(json.type, "faves");
Assert.Equal(json.interval, 1000 * searchInterval);
Assert.Equal(json.width.ToString(), width.ToString());
Assert.Equal(json.height.ToString(), height.ToString());
Assert.Equal(json.title, title);
Assert.Equal(json.subject, caption);
Assert.Equal(json.theme.shell.background, backgroundShellColor);
Assert.Equal(json.theme.shell.color, shellColor);
Assert.Equal(json.theme.tweets.background, tweetsBackgroundColor);
Assert.Equal(json.theme.tweets.color, tweetsColor);
Assert.Equal(json.theme.tweets.links, tweetsLinksColor);
Assert.Equal(json.features.scrollbar, scrollBar);
Assert.Equal(json.features.loop, loop);
Assert.Equal(json.features.live, live);
Assert.Equal(json.features.hashtags, hashTags);
Assert.Equal(json.features.avatars, avatars);
Assert.Equal(json.features.behavior, behavior.ToLowerInvariant());
Assert.True(actual.Contains(".setUser('my-userName')"));
}
[Fact]
public void FavesJavascriptEncodesParameters()
{
// Arrange
string twitterUserName = "<my-userName>";
string title = "<my-title>";
string caption = "<my-caption>";
int width = 100;
int height = 100;
string backgroundShellColor = "<my-backgroundShellColor>";
string shellColor = "<my-shellColor>";
string tweetsBackgroundColor = "<tweetsBackgroundColor>";
string tweetsColor = "<tweets-color>";
string tweetsLinksColor = "<tweets Linkcolor>";
// Act
string actual = Twitter.Faves(twitterUserName, width, height, title, caption, backgroundShellColor, shellColor, tweetsBackgroundColor, tweetsColor, tweetsLinksColor).ToString();
// Assert
Assert.True(actual.Contains("title: '\\u003cmy-title\\u003e'"));
Assert.True(actual.Contains("subject: '\\u003cmy-caption\\u003e'"));
Assert.True(actual.Contains("background: '\\u003cmy-backgroundShellColor\\u003e'"));
Assert.True(actual.Contains("color: '\\u003cmy-shellColor\\u003e'"));
Assert.True(actual.Contains("background: '\\u003ctweetsBackgroundColor\\u003e'"));
Assert.True(actual.Contains("color: '\\u003ctweets-color\\u003e"));
Assert.True(actual.Contains("links: '\\u003ctweets Linkcolor\\u003e'"));
Assert.True(actual.Contains(".setUser('\\u003cmy-userName\\u003e')"));
}
[Fact]
public void FavesRendersRendersValidXhtml()
{
string result = "<html> <head> \n <title> </title> \n </head> \n <body> \n" +
Twitter.Faves("any<>Name") +
"\n </body> \n </html>";
HtmlString htmlResult = new HtmlString(result);
XhtmlAssert.Validate1_1(htmlResult);
}
[Fact]
public void ListReturnsValidData()
{
// Arrange
string twitterUserName = "my-userName";
string list = "my-list";
string title = "my-title";
string caption = "my-caption";
int width = 100;
int height = 100;
string backgroundShellColor = "my-backgroundShellColor";
string shellColor = "my-shellColor";
string tweetsBackgroundColor = "tweetsBackgroundColor";
string tweetsColor = "tweets-color";
string tweetsLinksColor = "tweets Linkcolor";
int numTweets = 4;
bool scrollBar = false;
bool loop = false;
bool live = false;
bool hashTags = false;
bool timestamp = false;
bool avatars = false;
var behavior = "all";
int searchInterval = 10;
// Act
string actual = Twitter.List(twitterUserName, list, width, height, title, caption, backgroundShellColor, shellColor, tweetsBackgroundColor, tweetsColor, tweetsLinksColor,
numTweets, scrollBar, loop, live, hashTags, timestamp, avatars, "all", searchInterval).ToString();
// Assert
var json = GetTwitterJSObject(actual);
Assert.Equal(json.type, "list");
Assert.Equal(json.interval, 1000 * searchInterval);
Assert.Equal(json.width.ToString(), width.ToString());
Assert.Equal(json.height.ToString(), height.ToString());
Assert.Equal(json.title, title);
Assert.Equal(json.subject, caption);
Assert.Equal(json.theme.shell.background, backgroundShellColor);
Assert.Equal(json.theme.shell.color, shellColor);
Assert.Equal(json.theme.tweets.background, tweetsBackgroundColor);
Assert.Equal(json.theme.tweets.color, tweetsColor);
Assert.Equal(json.theme.tweets.links, tweetsLinksColor);
Assert.Equal(json.features.scrollbar, scrollBar);
Assert.Equal(json.features.loop, loop);
Assert.Equal(json.features.live, live);
Assert.Equal(json.features.hashtags, hashTags);
Assert.Equal(json.features.avatars, avatars);
Assert.Equal(json.features.behavior, behavior.ToLowerInvariant());
Assert.True(actual.Contains(".setList('my-userName', 'my-list')"));
}
[Fact]
public void ListJavascriptEncodesParameters()
{
// Arrange
string twitterUserName = "<my-userName>";
string list = "<my-list>";
string title = "<my-title>";
string caption = "<my-caption>";
int width = 100;
int height = 100;
string backgroundShellColor = "<my-backgroundShellColor>";
string shellColor = "<my-shellColor>";
string tweetsBackgroundColor = "<tweetsBackgroundColor>";
string tweetsColor = "<tweets-color>";
string tweetsLinksColor = "<tweets Linkcolor>";
// Act
string actual = Twitter.List(twitterUserName, list, width, height, title, caption, backgroundShellColor, shellColor, tweetsBackgroundColor, tweetsColor, tweetsLinksColor).ToString();
// Assert
Assert.True(actual.Contains("title: '\\u003cmy-title\\u003e'"));
Assert.True(actual.Contains("subject: '\\u003cmy-caption\\u003e'"));
Assert.True(actual.Contains("background: '\\u003cmy-backgroundShellColor\\u003e'"));
Assert.True(actual.Contains("color: '\\u003cmy-shellColor\\u003e'"));
Assert.True(actual.Contains("background: '\\u003ctweetsBackgroundColor\\u003e'"));
Assert.True(actual.Contains("color: '\\u003ctweets-color\\u003e"));
Assert.True(actual.Contains("links: '\\u003ctweets Linkcolor\\u003e'"));
Assert.True(actual.Contains(".setList('\\u003cmy-userName\\u003e', '\\u003cmy-list\\u003e')"));
}
[Fact]
public void ListRendersRendersValidXhtml()
{
string result = "<html> <head> \n <title> </title> \n </head> \n <body> \n" +
Twitter.List("any<>Name", "my-list") +
"\n </body> \n </html>";
HtmlString htmlResult = new HtmlString(result);
XhtmlAssert.Validate1_1(htmlResult);
}
private static dynamic GetTwitterJSObject(string twitterOutput)
{
const string startString = "Widget(";
int start = twitterOutput.IndexOf(startString) + startString.Length, end = twitterOutput.IndexOf(')');
return Json.Decode(twitterOutput.Substring(start, end - start));
}
}
}

View File

@@ -0,0 +1,415 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Collections;
using System.IO;
using System.Reflection;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.WebPages;
using Moq;
using Xunit;
namespace Microsoft.Web.Helpers.Test
{
public class UrlBuilderTest
{
private static TestVirtualPathUtility _virtualPathUtility = new TestVirtualPathUtility();
[Fact]
public void UrlBuilderUsesPathAsIsIfPathIsAValidUri()
{
// Arrange
var pagePath = "http://www.test.com/page-path";
// Act
var builder = new UrlBuilder(GetContext(), _virtualPathUtility, pagePath, null);
// Assert
Assert.Equal("http://www.test.com/page-path", builder.Path);
}
[Fact]
public void UrlBuilderUsesQueryComponentsIfPathIsAValidUri()
{
// Arrange
var pagePath = "http://www.test.com/page-path.vbhtml?param=value&baz=biz";
// Act
var builder = new UrlBuilder(GetContext(), _virtualPathUtility, pagePath, null);
// Assert
Assert.Equal("http://www.test.com/page-path.vbhtml", builder.Path);
Assert.Equal("?param=value&baz=biz", builder.QueryString);
}
[Fact]
public void UrlBuilderUsesUsesObjectParameterAsQueryString()
{
// Arrange
var pagePath = "http://www.test.com/page-path.vbhtml?param=value&baz=biz";
// Act
var builder = new UrlBuilder(GetContext(), _virtualPathUtility, pagePath, null);
// Assert
Assert.Equal("http://www.test.com/page-path.vbhtml", builder.Path);
Assert.Equal("?param=value&baz=biz", builder.QueryString);
}
[Fact]
public void UrlBuilderAppendsObjectParametersToPathWithQueryString()
{
// Arrange
var pagePath = "http://www.test.com/page-path.vbhtml?param=value&baz=biz";
// Act
var builder = new UrlBuilder(GetContext(), _virtualPathUtility, pagePath, new { param2 = "param2val" });
// Assert
Assert.Equal("http://www.test.com/page-path.vbhtml", builder.Path);
Assert.Equal("?param=value&baz=biz&param2=param2val", builder.QueryString);
}
[Fact]
public void UrlBuilderWithVirtualPathUsesVirtualPathUtility()
{
// Arrange
var pagePath = "~/page";
// Act
var builder = new UrlBuilder(GetContext(), _virtualPathUtility, pagePath, null);
// Assert
Assert.Equal("page", builder.Path);
}
[Fact]
public void UrlBuilderDoesNotResolvePathIfContextIsNull()
{
// Arrange
var pagePath = "~/foo/bar";
// Act
var builder = new UrlBuilder(null, _virtualPathUtility, pagePath, null);
// Assert
Assert.Equal(pagePath, builder.Path);
}
[Fact]
public void UrlBuilderSetsPathToNullIfContextIsNullAndPagePathIsNotSpecified()
{
// Act
var builder = new UrlBuilder(null, null, null, null);
// Assert
Assert.Null(builder.Path);
Assert.True(String.IsNullOrEmpty(builder.ToString()));
}
[Fact]
public void UrlBuilderWithVirtualPathAppendsObjectAsQueryString()
{
// Arrange
var pagePath = "~/page";
// Act
var builder = new UrlBuilder(GetContext(), _virtualPathUtility, pagePath, new { Foo = "bar", baz = "qux" });
// Assert
Assert.Equal("page", builder.Path);
Assert.Equal("?Foo=bar&baz=qux", builder.QueryString);
}
[Fact]
public void UrlBuilderWithVirtualPathExtractsQueryStringParameterFromPath()
{
// Arrange
var pagePath = "~/dir/page?someparam=value";
// Act
var builder = new UrlBuilder(GetContext(), _virtualPathUtility, pagePath, null);
// Assert
Assert.Equal("dir/page", builder.Path);
Assert.Equal("?someparam=value", builder.QueryString);
}
[Fact]
public void UrlBuilderWithVirtualPathAndQueryStringAppendsObjectAsQueryStringParams()
{
// Arrange
var pagePath = "~/dir/page?someparam=value";
// Act
var builder = new UrlBuilder(GetContext(), _virtualPathUtility, pagePath, new { someotherparam = "value2" });
// Assert
Assert.Equal("dir/page", builder.Path);
Assert.Equal("?someparam=value&someotherparam=value2", builder.QueryString);
}
[Fact]
public void AddPathAddsPathPortionToRelativeUrl()
{
// Arrange
var pagePath = "~/dir/page?someparam=value";
// Act
var builder = new UrlBuilder(GetContext(), _virtualPathUtility, pagePath, null);
builder.AddPath("foo").AddPath("bar/baz");
// Assert
Assert.Equal("dir/page/foo/bar/baz", builder.Path);
Assert.Equal("?someparam=value", builder.QueryString);
}
[Fact]
public void AddPathEncodesPathParams()
{
// Arrange
var pagePath = "~/dir/page?someparam=value";
// Act
var builder = new UrlBuilder(GetContext(), _virtualPathUtility, pagePath, null);
builder.AddPath("foo bar").AddPath("baz biz", "qux");
// Assert
Assert.Equal("dir/page/foo%20bar/baz%20biz/qux", builder.Path);
}
[Fact]
public void AddPathAddsPathPortionToAbsoluteUrl()
{
// Arrange
var pagePath = "http://some-site/dir/page?someparam=value";
// Act
var builder = new UrlBuilder(GetContext(), _virtualPathUtility, pagePath, null);
builder.AddPath("foo").AddPath("bar/baz");
// Assert
Assert.Equal("http://some-site/dir/page/foo/bar/baz", builder.Path);
Assert.Equal("?someparam=value", builder.QueryString);
}
[Fact]
public void AddPathWithParamsArrayAddsPathPortionToRelativeUrl()
{
// Arrange
var pagePath = "~/dir/page/?someparam=value";
// Act
var builder = new UrlBuilder(GetContext(), _virtualPathUtility, pagePath, null);
builder.AddPath("foo", "bar", "baz").AddPath("qux");
// Assert
Assert.Equal("dir/page/foo/bar/baz/qux", builder.Path);
Assert.Equal("?someparam=value", builder.QueryString);
}
[Fact]
public void AddPathEnsuresSlashesAreNotRepeated()
{
// Arrange
var pagePath = "~/dir/page/";
// Act
var builder = new UrlBuilder(GetContext(), _virtualPathUtility, pagePath, null);
builder.AddPath("foo").AddPath("/bar/").AddPath("/baz");
// Assert
Assert.Equal("dir/page/foo/bar/baz", builder.Path);
}
[Fact]
public void AddPathWithParamsEnsuresSlashAreNotRepeated()
{
// Arrange
var pagePath = "~/dir/page/";
// Act
var builder = new UrlBuilder(GetContext(), _virtualPathUtility, pagePath, null);
builder.AddPath("foo", "/bar/", "/baz").AddPath("qux/");
// Assert
Assert.Equal("dir/page/foo/bar/baz/qux/", builder.Path);
}
[Fact]
public void AddPathWithParamsArrayAddsPathPortionToAbsoluteUrl()
{
// Arrange
var pagePath = "http://www.test.com/dir/page/?someparam=value";
// Act
var builder = new UrlBuilder(GetContext(), _virtualPathUtility, pagePath, null);
builder.AddPath("foo", "bar", "baz").AddPath("qux");
// Assert
Assert.Equal("http://www.test.com/dir/page/foo/bar/baz/qux", builder.Path);
Assert.Equal("?someparam=value", builder.QueryString);
}
[Fact]
public void UrlBuilderEncodesParameters()
{
// Arrange
var pagePath = "~/dir/page/?someparam=value";
// Act
var builder = new UrlBuilder(GetContext(), _virtualPathUtility, pagePath, new { Λ = "λ" });
builder.AddParam(new { π = "is not a lie" }).AddParam("Π", "maybe a lie");
// Assert
Assert.Equal("?someparam=value&%ce%9b=%ce%bb&%cf%80=is+not+a+lie&%ce%a0=maybe+a+lie", builder.QueryString);
}
[Fact]
public void AddParamAddsParamToQueryString()
{
// Arrange
var pagePath = "http://www.test.com/dir/page/?someparam=value";
// Act
var builder = new UrlBuilder(GetContext(), _virtualPathUtility, pagePath, null);
builder.AddParam("foo", "bar");
// Assert
Assert.Equal("?someparam=value&foo=bar", builder.QueryString);
}
[Fact]
public void AddParamAddsQuestionMarkToQueryStringIfFirstParam()
{
// Arrange
var pagePath = "~/dir/page";
// Act
var builder = new UrlBuilder(GetContext(), _virtualPathUtility, pagePath, null);
builder.AddParam("foo", "bar").AddParam(new { baz = "qux", biz = "quark" });
// Assert
Assert.Equal("?foo=bar&baz=qux&biz=quark", builder.QueryString);
}
[Fact]
public void AddParamIgnoresParametersWithEmptyKey()
{
// Arrange
var pagePath = "~/dir/page";
// Act
var builder = new UrlBuilder(GetContext(), _virtualPathUtility, pagePath, null);
builder.AddParam("", "bar").AddParam(new { baz = "", biz = "quark" }).AddParam("qux", null).AddParam(null, "somevalue");
// Assert
Assert.Equal("?baz=&biz=quark&qux=", builder.QueryString);
}
[Fact]
public void ToStringConcatsPathAndQueryString()
{
// Arrange
var pagePath = "~/dir/page";
// Act
var builder = new UrlBuilder(GetContext(), _virtualPathUtility, pagePath, null);
builder.AddParam("foo", "bar").AddParam(new { baz = "qux", biz = "quark" });
// Assert
Assert.Equal("dir/page?foo=bar&baz=qux&biz=quark", builder.ToString());
}
[Fact]
public void UrlBuilderWithRealVirtualPathUtilityTest()
{
// Arrange
var pagePath = "~/world/test.aspx";
try
{
// Act
CreateHttpContext("default.aspx", "http://localhost/WebSite1/subfolder1/default.aspx");
CreateHttpRuntime("/WebSite1/");
var builder = new UrlBuilder(pagePath, null);
// Assert
Assert.Equal(@"/WebSite1/world/test.aspx", builder.Path);
}
finally
{
RestoreHttpRuntime();
}
}
private static HttpContextBase GetContext(params string[] virtualPaths)
{
var httpContext = new Mock<HttpContextBase>();
var table = new Hashtable();
httpContext.SetupGet(c => c.Items).Returns(table);
foreach (var item in virtualPaths)
{
var page = new Mock<ITemplateFile>();
page.SetupGet(p => p.TemplateInfo).Returns(new TemplateFileInfo(item));
TemplateStack.Push(httpContext.Object, page.Object);
}
return httpContext.Object;
}
private class TestVirtualPathUtility : VirtualPathUtilityBase
{
public override string Combine(string basePath, string relativePath)
{
return basePath + '/' + relativePath.TrimStart('~', '/');
}
public override string ToAbsolute(string virtualPath)
{
return virtualPath.TrimStart('~', '/');
}
}
internal static void CreateHttpRuntime(string appVPath)
{
var runtime = new HttpRuntime();
var appDomainAppVPathField = typeof(HttpRuntime).GetField("_appDomainAppVPath", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance);
appDomainAppVPathField.SetValue(runtime, CreateVirtualPath(appVPath));
GetTheRuntime().SetValue(null, runtime);
var appDomainIdField = typeof(HttpRuntime).GetField("_appDomainId", BindingFlags.NonPublic | BindingFlags.Instance);
appDomainIdField.SetValue(runtime, "test");
}
internal static FieldInfo GetTheRuntime()
{
return typeof(HttpRuntime).GetField("_theRuntime", BindingFlags.NonPublic | BindingFlags.Static);
}
internal static void RestoreHttpRuntime()
{
GetTheRuntime().SetValue(null, null);
}
// E.g. "default.aspx", "http://localhost/WebSite1/subfolder1/default.aspx"
internal static void CreateHttpContext(string filename, string url)
{
var request = new HttpRequest(filename, url, null);
var httpContext = new HttpContext(request, new HttpResponse(new StringWriter(new StringBuilder())));
HttpContext.Current = httpContext;
}
internal static void RestoreHttpContext()
{
HttpContext.Current = null;
}
internal static object CreateVirtualPath(string path)
{
var vPath = typeof(Page).Assembly.GetType("System.Web.VirtualPath");
var method = vPath.GetMethod("CreateNonRelativeTrailingSlash", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);
return method.Invoke(null, new object[] { path });
}
}
}

View File

@@ -0,0 +1,301 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Web;
using Moq;
using Xunit;
using Assert = Microsoft.TestCommon.AssertEx;
namespace Microsoft.Web.Helpers.Test
{
public class VideoTest
{
private VirtualPathUtilityWrapper _pathUtility = new VirtualPathUtilityWrapper();
[Fact]
public void FlashCannotOverrideHtmlAttributes()
{
Assert.ThrowsArgument(() => { Video.Flash(GetContext(), _pathUtility, "http://foo.bar.com/foo.swf", htmlAttributes: new { cLASSid = "CanNotOverride" }); }, "htmlAttributes", "Property \"cLASSid\" cannot be set through this argument.");
}
[Fact]
public void FlashDefaults()
{
string html = Video.Flash(GetContext(), _pathUtility, "http://foo.bar.com/foo.swf").ToString().Replace("\r\n", "");
Assert.True(html.StartsWith(
"<object classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\" " +
"codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab\" type=\"application/x-oleobject\" >"
));
Assert.True(html.Contains("<param name=\"movie\" value=\"http://foo.bar.com/foo.swf\" />"));
Assert.True(html.Contains("<embed src=\"http://foo.bar.com/foo.swf\" type=\"application/x-shockwave-flash\" />"));
Assert.True(html.EndsWith("</object>"));
}
[Fact]
public void FlashThrowsWhenPathIsEmpty()
{
Assert.ThrowsArgumentNullOrEmptyString(() => { Video.Flash(GetContext(), _pathUtility, String.Empty); }, "path");
}
[Fact]
public void FlashThrowsWhenPathIsNull()
{
Assert.ThrowsArgumentNullOrEmptyString(() => { Video.Flash(GetContext(), _pathUtility, null); }, "path");
}
[Fact]
public void FlashWithExposedOptions()
{
string html = Video.Flash(GetContext(), _pathUtility, "http://foo.bar.com/foo.swf", width: "100px", height: "100px",
play: false, loop: false, menu: false, backgroundColor: "#000", quality: "Q", scale: "S", windowMode: "WM",
baseUrl: "http://foo.bar.com/", version: "1.0.0.0", htmlAttributes: new { id = "fl" }, embedName: "efl").ToString().Replace("\r\n", "");
Assert.True(html.StartsWith(
"<object classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\" " +
"codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=1,0,0,0\" " +
"height=\"100px\" id=\"fl\" type=\"application/x-oleobject\" width=\"100px\" >"
));
Assert.True(html.Contains("<param name=\"play\" value=\"False\" />"));
Assert.True(html.Contains("<param name=\"loop\" value=\"False\" />"));
Assert.True(html.Contains("<param name=\"menu\" value=\"False\" />"));
Assert.True(html.Contains("<param name=\"bgColor\" value=\"#000\" />"));
Assert.True(html.Contains("<param name=\"quality\" value=\"Q\" />"));
Assert.True(html.Contains("<param name=\"scale\" value=\"S\" />"));
Assert.True(html.Contains("<param name=\"wmode\" value=\"WM\" />"));
Assert.True(html.Contains("<param name=\"base\" value=\"http://foo.bar.com/\" />"));
var embed = new Regex("<embed.*/>").Match(html);
Assert.True(embed.Success);
Assert.True(embed.Value.StartsWith("<embed src=\"http://foo.bar.com/foo.swf\" width=\"100px\" height=\"100px\" name=\"efl\" type=\"application/x-shockwave-flash\" "));
Assert.True(embed.Value.Contains("play=\"False\""));
Assert.True(embed.Value.Contains("loop=\"False\""));
Assert.True(embed.Value.Contains("menu=\"False\""));
Assert.True(embed.Value.Contains("bgColor=\"#000\""));
Assert.True(embed.Value.Contains("quality=\"Q\""));
Assert.True(embed.Value.Contains("scale=\"S\""));
Assert.True(embed.Value.Contains("wmode=\"WM\""));
Assert.True(embed.Value.Contains("base=\"http://foo.bar.com/\""));
}
[Fact]
public void FlashWithUnexposedOptions()
{
string html = Video.Flash(GetContext(), _pathUtility, "http://foo.bar.com/foo.swf", options: new { X = "Y", Z = 123 }).ToString().Replace("\r\n", "");
Assert.True(html.Contains("<param name=\"X\" value=\"Y\" />"));
Assert.True(html.Contains("<param name=\"Z\" value=\"123\" />"));
// note - can't guarantee order of optional params:
Assert.True(
html.Contains("<embed src=\"http://foo.bar.com/foo.swf\" type=\"application/x-shockwave-flash\" X=\"Y\" Z=\"123\" />") ||
html.Contains("<embed src=\"http://foo.bar.com/foo.swf\" type=\"application/x-shockwave-flash\" Z=\"123\" X=\"Y\" />")
);
}
[Fact]
public void MediaPlayerCannotOverrideHtmlAttributes()
{
Assert.ThrowsArgument(() => { Video.MediaPlayer(GetContext(), _pathUtility, "http://foo.bar.com/foo.wmv", htmlAttributes: new { cODEbase = "CanNotOverride" }); }, "htmlAttributes", "Property \"cODEbase\" cannot be set through this argument.");
}
[Fact]
public void MediaPlayerDefaults()
{
string html = Video.MediaPlayer(GetContext(), _pathUtility, "http://foo.bar.com/foo.wmv").ToString().Replace("\r\n", "");
Assert.True(html.StartsWith(
"<object classid=\"clsid:6BF52A52-394A-11D3-B153-00C04F79FAA6\" >"
));
Assert.True(html.Contains("<param name=\"URL\" value=\"http://foo.bar.com/foo.wmv\" />"));
Assert.True(html.Contains("<embed src=\"http://foo.bar.com/foo.wmv\" type=\"application/x-mplayer2\" />"));
Assert.True(html.EndsWith("</object>"));
}
[Fact]
public void MediaPlayerThrowsWhenPathIsEmpty()
{
Assert.ThrowsArgumentNullOrEmptyString(() => { Video.MediaPlayer(GetContext(), _pathUtility, String.Empty); }, "path");
}
[Fact]
public void MediaPlayerThrowsWhenPathIsNull()
{
Assert.ThrowsArgumentNullOrEmptyString(() => { Video.MediaPlayer(GetContext(), _pathUtility, null); }, "path");
}
[Fact]
public void MediaPlayerWithExposedOptions()
{
string html = Video.MediaPlayer(GetContext(), _pathUtility, "http://foo.bar.com/foo.wmv", width: "100px", height: "100px",
autoStart: false, playCount: 2, uiMode: "UIMODE", stretchToFit: true, enableContextMenu: false, mute: true,
volume: 1, baseUrl: "http://foo.bar.com/", htmlAttributes: new { id = "mp" }, embedName: "emp").ToString().Replace("\r\n", "");
Assert.True(html.StartsWith(
"<object classid=\"clsid:6BF52A52-394A-11D3-B153-00C04F79FAA6\" height=\"100px\" id=\"mp\" width=\"100px\" >"
));
Assert.True(html.Contains("<param name=\"URL\" value=\"http://foo.bar.com/foo.wmv\" />"));
Assert.True(html.Contains("<param name=\"autoStart\" value=\"False\" />"));
Assert.True(html.Contains("<param name=\"playCount\" value=\"2\" />"));
Assert.True(html.Contains("<param name=\"uiMode\" value=\"UIMODE\" />"));
Assert.True(html.Contains("<param name=\"stretchToFit\" value=\"True\" />"));
Assert.True(html.Contains("<param name=\"enableContextMenu\" value=\"False\" />"));
Assert.True(html.Contains("<param name=\"mute\" value=\"True\" />"));
Assert.True(html.Contains("<param name=\"volume\" value=\"1\" />"));
Assert.True(html.Contains("<param name=\"baseURL\" value=\"http://foo.bar.com/\" />"));
var embed = new Regex("<embed.*/>").Match(html);
Assert.True(embed.Success);
Assert.True(embed.Value.StartsWith("<embed src=\"http://foo.bar.com/foo.wmv\" width=\"100px\" height=\"100px\" name=\"emp\" type=\"application/x-mplayer2\" "));
Assert.True(embed.Value.Contains("autoStart=\"False\""));
Assert.True(embed.Value.Contains("playCount=\"2\""));
Assert.True(embed.Value.Contains("uiMode=\"UIMODE\""));
Assert.True(embed.Value.Contains("stretchToFit=\"True\""));
Assert.True(embed.Value.Contains("enableContextMenu=\"False\""));
Assert.True(embed.Value.Contains("mute=\"True\""));
Assert.True(embed.Value.Contains("volume=\"1\""));
Assert.True(embed.Value.Contains("baseURL=\"http://foo.bar.com/\""));
}
[Fact]
public void MediaPlayerWithUnexposedOptions()
{
string html = Video.MediaPlayer(GetContext(), _pathUtility, "http://foo.bar.com/foo.wmv", options: new { X = "Y", Z = 123 }).ToString().Replace("\r\n", "");
Assert.True(html.Contains("<param name=\"X\" value=\"Y\" />"));
Assert.True(html.Contains("<param name=\"Z\" value=\"123\" />"));
Assert.True(
html.Contains("<embed src=\"http://foo.bar.com/foo.wmv\" type=\"application/x-mplayer2\" X=\"Y\" Z=\"123\" />") ||
html.Contains("<embed src=\"http://foo.bar.com/foo.wmv\" type=\"application/x-mplayer2\" Z=\"123\" X=\"Y\" />")
);
}
[Fact]
public void SilverlightCannotOverrideHtmlAttributes()
{
Assert.ThrowsArgument(() =>
{
Video.Silverlight(GetContext(), _pathUtility, "http://foo.bar.com/foo.xap", "100px", "100px",
htmlAttributes: new { WIDTH = "CanNotOverride" });
}, "htmlAttributes", "Property \"WIDTH\" cannot be set through this argument.");
}
[Fact]
public void SilverlightDefaults()
{
string html = Video.Silverlight(GetContext(), _pathUtility, "http://foo.bar.com/foo.xap", "100px", "100px").ToString().Replace("\r\n", "");
Assert.True(html.StartsWith(
"<object data=\"data:application/x-silverlight-2,\" height=\"100px\" type=\"application/x-silverlight-2\" " +
"width=\"100px\" >"
));
Assert.True(html.Contains("<param name=\"source\" value=\"http://foo.bar.com/foo.xap\" />"));
Assert.True(html.Contains(
"<a href=\"http://go.microsoft.com/fwlink/?LinkID=149156\" style=\"text-decoration:none\">" +
"<img src=\"http://go.microsoft.com/fwlink?LinkId=108181\" alt=\"Get Microsoft Silverlight\" " +
"style=\"border-style:none\"/></a>"));
Assert.True(html.EndsWith("</object>"));
}
[Fact]
public void SilverlightThrowsWhenPathIsEmpty()
{
Assert.ThrowsArgumentNullOrEmptyString(() => { Video.Silverlight(GetContext(), _pathUtility, String.Empty, "100px", "100px"); }, "path");
}
[Fact]
public void SilverlightThrowsWhenPathIsNull()
{
Assert.ThrowsArgumentNullOrEmptyString(() => { Video.Silverlight(GetContext(), _pathUtility, null, "100px", "100px"); }, "path");
}
[Fact]
public void SilverlightThrowsWhenHeightIsEmpty()
{
Assert.ThrowsArgumentNullOrEmptyString(() => { Video.Silverlight(GetContext(), _pathUtility, "http://foo.bar.com/foo.xap", "100px", String.Empty); }, "height");
}
[Fact]
public void SilverlightThrowsWhenHeightIsNull()
{
Assert.ThrowsArgumentNullOrEmptyString(() => { Video.Silverlight(GetContext(), _pathUtility, "http://foo.bar.com/foo.xap", "100px", null); }, "height");
}
[Fact]
public void SilverlightThrowsWhenWidthIsEmpty()
{
Assert.ThrowsArgumentNullOrEmptyString(() => { Video.Silverlight(GetContext(), _pathUtility, "http://foo.bar.com/foo.xap", String.Empty, "100px"); }, "width");
}
[Fact]
public void SilverlightThrowsWhenWidthIsNull()
{
Assert.ThrowsArgumentNullOrEmptyString(() => { Video.Silverlight(GetContext(), _pathUtility, "http://foo.bar.com/foo.xap", null, "100px"); }, "width");
}
[Fact]
public void SilverlightWithExposedOptions()
{
string html = Video.Silverlight(GetContext(), _pathUtility, "http://foo.bar.com/foo.xap", width: "85%", height: "85%",
backgroundColor: "red", initParameters: "X=Y", minimumVersion: "1.0.0.0", autoUpgrade: false,
htmlAttributes: new { id = "sl" }).ToString().Replace("\r\n", "");
Assert.True(html.StartsWith(
"<object data=\"data:application/x-silverlight-2,\" height=\"85%\" id=\"sl\" " +
"type=\"application/x-silverlight-2\" width=\"85%\" >"
));
Assert.True(html.Contains("<param name=\"background\" value=\"red\" />"));
Assert.True(html.Contains("<param name=\"initparams\" value=\"X=Y\" />"));
Assert.True(html.Contains("<param name=\"minruntimeversion\" value=\"1.0.0.0\" />"));
Assert.True(html.Contains("<param name=\"autoUpgrade\" value=\"False\" />"));
var embed = new Regex("<embed.*/>").Match(html);
Assert.False(embed.Success);
}
[Fact]
public void SilverlightWithUnexposedOptions()
{
string html = Video.Silverlight(GetContext(), _pathUtility, "http://foo.bar.com/foo.xap", width: "50px", height: "50px",
options: new { X = "Y", Z = 123 }).ToString().Replace("\r\n", "");
Assert.True(html.Contains("<param name=\"X\" value=\"Y\" />"));
Assert.True(html.Contains("<param name=\"Z\" value=\"123\" />"));
}
[Fact]
public void ValidatePathResolvesExistingLocalPath()
{
string path = Assembly.GetExecutingAssembly().Location;
Mock<VirtualPathUtilityBase> pathUtility = new Mock<VirtualPathUtilityBase>();
pathUtility.Setup(p => p.Combine(It.IsAny<string>(), It.IsAny<string>())).Returns(path);
pathUtility.Setup(p => p.ToAbsolute(It.IsAny<string>())).Returns(path);
Mock<HttpServerUtilityBase> serverMock = new Mock<HttpServerUtilityBase>();
serverMock.Setup(s => s.MapPath(It.IsAny<string>())).Returns(path);
HttpContextBase context = GetContext(serverMock.Object);
string html = Video.Flash(context, pathUtility.Object, "foo.bar").ToString();
Assert.True(html.StartsWith("<object"));
Assert.True(html.Contains(HttpUtility.HtmlAttributeEncode(HttpUtility.UrlPathEncode(path))));
}
[Fact]
public void ValidatePathThrowsForNonExistingLocalPath()
{
string path = "c:\\does\\not\\exist.swf";
Mock<VirtualPathUtilityBase> pathUtility = new Mock<VirtualPathUtilityBase>();
pathUtility.Setup(p => p.Combine(It.IsAny<string>(), It.IsAny<string>())).Returns(path);
pathUtility.Setup(p => p.ToAbsolute(It.IsAny<string>())).Returns(path);
Mock<HttpServerUtilityBase> serverMock = new Mock<HttpServerUtilityBase>();
serverMock.Setup(s => s.MapPath(It.IsAny<string>())).Returns(path);
HttpContextBase context = GetContext(serverMock.Object);
Assert.Throws<InvalidOperationException>(() => { Video.Flash(context, pathUtility.Object, "exist.swf"); }, "The media file \"exist.swf\" does not exist.");
}
private static HttpContextBase GetContext(HttpServerUtilityBase serverUtility = null)
{
// simple mocked context - won't reference as long as path starts with 'http'
Mock<HttpRequestBase> requestMock = new Mock<HttpRequestBase>();
Mock<HttpContextBase> contextMock = new Mock<HttpContextBase>();
contextMock.Setup(context => context.Request).Returns(requestMock.Object);
contextMock.Setup(context => context.Server).Returns(serverUtility);
return contextMock.Object;
}
}
}

View File

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