File: Utils.cs

package info (click to toggle)
mono 6.14.1%2Bds2-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,282,740 kB
  • sloc: cs: 11,182,461; xml: 2,850,281; ansic: 699,123; cpp: 122,919; perl: 58,604; javascript: 30,841; asm: 21,845; makefile: 19,602; sh: 10,973; python: 4,772; pascal: 925; sql: 859; sed: 16; php: 1
file content (263 lines) | stat: -rw-r--r-- 10,039 bytes parent folder | download | duplicates (9)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.

using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Reflection;
using System.Text;
using System.Web.Hosting;
using System.Web.WebPages.TestUtils;
using Moq;

namespace System.Web.WebPages.Test
{
    public static class Utils
    {
        public static string RenderWebPage(WebPage page, StartPage startPage = null, HttpRequestBase request = null)
        {
            var writer = new StringWriter();

            // Create an actual dummy HttpContext that has a request object
            var filename = "default.aspx";
            var url = "http://localhost/default.aspx";

            request = request ?? CreateTestRequest(filename, url).Object;
            var httpContext = CreateTestContext(request);

            var pageContext = new WebPageContext { HttpContext = httpContext.Object };
            page.ExecutePageHierarchy(pageContext, writer, startPage);
            return writer.ToString();
        }

        public static Mock<HttpContextBase> CreateTestContext(HttpRequestBase request = null, HttpResponseBase response = null, IDictionary items = null)
        {
            items = items ?? new Hashtable();
            request = request ?? CreateTestRequest("default.cshtml", "http://localhost/default.cshtml").Object;

            if (response == null)
            {
                var mockResponse = new Mock<HttpResponseBase>();
                mockResponse.Setup(r => r.Cookies).Returns(new HttpCookieCollection());
                response = mockResponse.Object;
            }

            var httpContext = new Mock<HttpContextBase>();
            httpContext.SetupGet(c => c.Items).Returns(items);
            httpContext.SetupGet(c => c.Request).Returns(request);
            httpContext.SetupGet(c => c.Response).Returns(response);
            return httpContext;
        }

        public static Mock<HttpRequestBase> CreateTestRequest(string filename, string url)
        {
            var mockRequest = new Mock<HttpRequestBase> { CallBase = true };
            mockRequest.SetupGet(r => r.Path).Returns(filename);
            mockRequest.SetupGet(r => r.RawUrl).Returns(url);
            mockRequest.SetupGet(r => r.IsLocal).Returns(false);
            mockRequest.SetupGet(r => r.QueryString).Returns(new NameValueCollection());
            mockRequest.SetupGet(r => r.Browser.IsMobileDevice).Returns(false);
            mockRequest.SetupGet(r => r.Cookies).Returns(new HttpCookieCollection());
            mockRequest.SetupGet(r => r.UserAgent).Returns(String.Empty);

            return mockRequest;
        }

        public static string RenderWebPage(Action<WebPage> pageExecuteAction, string pagePath = "~/index.cshtml")
        {
            var page = CreatePage(pageExecuteAction, pagePath);
            return RenderWebPage(page);
        }

        public static MockPage CreatePage(Action<WebPage> pageExecuteAction, string pagePath = "~/index.cshtml")
        {
            var page = new MockPage()
            {
                VirtualPath = pagePath,
                ExecuteAction = p => { pageExecuteAction(p); }
            };
            page.VirtualPathFactory = new HashVirtualPathFactory(page);
            page.DisplayModeProvider = new DisplayModeProvider();
            return page;
        }

        public static MockStartPage CreateStartPage(Action<StartPage> pageExecuteAction, string pagePath = "~/_pagestart.cshtml")
        {
            var page = new MockStartPage()
            {
                VirtualPath = pagePath,
                ExecuteAction = p => { pageExecuteAction(p); }
            };
            page.VirtualPathFactory = new HashVirtualPathFactory(page);
            page.DisplayModeProvider = new DisplayModeProvider();
            return page;
        }

        public static string RenderWebPageWithSubPage(Action<WebPage> pageExecuteAction, Action<WebPage> subpageExecuteAction,
                                                      string pagePath = "~/index.cshtml", string subpagePath = "~/subpage.cshtml")
        {
            var page = CreatePage(pageExecuteAction);
            var subPage = CreatePage(subpageExecuteAction, subpagePath);
            var virtualPathFactory = new HashVirtualPathFactory(page, subPage);
            subPage.VirtualPathFactory = virtualPathFactory;
            page.VirtualPathFactory = virtualPathFactory;
            return RenderWebPage(page);
        }

        // E.g. "default.aspx", "http://localhost/WebSite1/subfolder1/default.aspx"
        /// <summary>
        /// Creates an instance of HttpContext and assigns it to HttpContext.Current. Ensure that the returned value is disposed at the end of the test.
        /// </summary>
        /// <returns>Returns an IDisposable that restores the original HttpContext.</returns>
        internal static IDisposable 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;

            return new DisposableAction(RestoreHttpContext);
        }

        internal static void RestoreHttpContext()
        {
            HttpContext.Current = null;
        }

        internal static IDisposable CreateHttpRuntime(string appVPath)
        {
            return WebUtils.CreateHttpRuntime(appVPath);
        }

        public static void SetupVirtualPathInAppDomain(string vpath, string contents)
        {
            var file = new Mock<VirtualFile>(vpath);
            file.Setup(f => f.Open()).Returns(new MemoryStream(ASCIIEncoding.Default.GetBytes(contents)));
            var vpp = new Mock<VirtualPathProvider>();
            vpp.Setup(p => p.FileExists(vpath)).Returns(true);
            vpp.Setup(p => p.GetFile(vpath)).Returns(file.Object);
            AppDomainUtils.SetAppData();
            var env = new HostingEnvironment();

            var register = typeof(HostingEnvironment).GetMethod("RegisterVirtualPathProviderInternal", BindingFlags.Static | BindingFlags.NonPublic);
            register.Invoke(null, new object[] { vpp.Object });
        }

        /// <summary>
        /// Assigns a common object factory to the pages.
        /// </summary>
        internal static IVirtualPathFactory AssignObjectFactoriesAndDisplayModeProvider(params WebPageExecutingBase[] pages)
        {
            var objectFactory = new HashVirtualPathFactory(pages);
            var displayModeProvider = new DisplayModeProvider();
            foreach (var item in pages)
            {
                item.VirtualPathFactory = objectFactory;
                var webPageRenderingBase = item as WebPageRenderingBase;
                if (webPageRenderingBase != null)
                {
                    webPageRenderingBase.DisplayModeProvider = displayModeProvider;
                }
            }

            return objectFactory;
        }

        internal static DisplayModeProvider AssignDisplayModeProvider(params WebPageRenderingBase[] pages)
        {
            var displayModeProvider = new DisplayModeProvider();
            foreach (var item in pages)
            {
                item.DisplayModeProvider = displayModeProvider;
            }
            return displayModeProvider;
        }
    }

    public class MockPageHelper
    {
        internal static string GetDirectory(string virtualPath)
        {
            var dir = Path.GetDirectoryName(virtualPath);
            if (dir == "~")
            {
                return null;
            }
            return dir;
        }
    }

    // This is a mock implementation of WebPage mainly to make the Render method work and
    // generate a string.
    // The Execute method simulates what is typically generated based on markup by the parsers.
    public class MockPage : WebPage
    {
        public Action<WebPage> ExecuteAction { get; set; }

        internal override string GetDirectory(string virtualPath)
        {
            return MockPageHelper.GetDirectory(virtualPath);
        }

        public override void Execute()
        {
            ExecuteAction(this);
        }
    }

    public class MockStartPage : StartPage
    {
        public Action<StartPage> ExecuteAction { get; set; }

        internal override string GetDirectory(string virtualPath)
        {
            return MockPageHelper.GetDirectory(virtualPath);
        }

        public override void Execute()
        {
            ExecuteAction(this);
        }

        public Dictionary<string, object> CombinedPageInstances
        {
            get
            {
                var combinedInstances = new Dictionary<string, object>();
                var instances = new Dictionary<string, object>();
                WebPageRenderingBase childPage = this;
                while (childPage != null)
                {
                    if (childPage is MockStartPage)
                    {
                        var initPage = childPage as MockStartPage;
                        childPage = initPage.ChildPage;
                    }
                    else if (childPage is MockPage)
                    {
                        childPage = null;
                    }
                    foreach (var kvp in instances)
                    {
                        combinedInstances.Add(kvp.Key, kvp.Value);
                    }
                }
                return combinedInstances;
            }
        }
    }

    public class MockHttpRuntime
    {
        public static Version RequestValidationMode { get; set; }
    }

    public class MockHttpApplication
    {
        public static Type ModuleType { get; set; }

        public static void RegisterModule(Type moduleType)
        {
            ModuleType = moduleType;
        }
    }
}