/
IsolatedRazorEngineServiceTestFixture.cs
722 lines (648 loc) · 29 KB
/
IsolatedRazorEngineServiceTestFixture.cs
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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
using NUnit.Framework;
using RazorEngine.Compilation;
using RazorEngine.Templating;
using RazorEngine.Tests.TestTypes;
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Runtime.Remoting;
using System.Runtime.Serialization;
using System.Security;
using System.Security.Permissions;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using RazorEngine.Configuration;
using RazorEngine.Compilation.ReferenceResolver;
#if RAZOR4
using Microsoft.AspNetCore.Razor;
#else
using System.Web.Razor;
#endif
namespace Test.RazorEngine
{
/// <summary>
/// Tests the IsolatedRazorEngineService.
/// </summary>
[TestFixture]
public class IsolatedRazorEngineServiceTestFixture
{
/// <summary>
/// Check if we are running on mono.
/// </summary>
/// <returns></returns>
public static bool IsRunningOnMono()
{
return Type.GetType("Mono.Runtime") != null;
}
/// <summary>
/// Check if we have either an SecurityManager enabled or are running on mono
/// and ignore the test.
/// </summary>
public static void CheckMono()
{
#pragma warning disable 0618 // Mono recommends to do this.
if (!SecurityManager.SecurityEnabled)
Assert.Ignore("SecurityManager.SecurityEnabled is OFF");
#pragma warning restore 0618
if (IsRunningOnMono())
Assert.Ignore("IsolatedRazorEngineServiceTestFixture is not supported on mono");
}
/// <summary>
/// Creates a sandbox for testing.
/// </summary>
/// <returns></returns>
public static AppDomain SandboxCreator()
{
return SandboxCreator(null);
}
/// <summary>
/// Creates a sandbox for testing.
/// </summary>
/// <param name="permissions">Additional permissions</param>
/// <returns></returns>
public static AppDomain SandboxCreator(IEnumerable<IPermission> permissions)
{
CheckMono();
#if MONO
// Mono has no AddHostEvidence or GetHostEvidence.
// We do not run the tests anyway.
return null;
#else
Evidence ev = new Evidence();
ev.AddHostEvidence(new Zone(SecurityZone.Internet));
PermissionSet permSet = SecurityManager.GetStandardSandbox(ev);
if (permissions != null)
{
foreach (IPermission permission in permissions)
{
permSet.AddPermission(permission);
}
}
// We have to load ourself with full trust
StrongName razorEngineAssembly = typeof(RazorEngineService).Assembly.Evidence.GetHostEvidence<StrongName>();
// We have to load Razor with full trust (so all methods are SecurityCritical)
// This is because we apply AllowPartiallyTrustedCallers to RazorEngine, because
// We need the untrusted (transparent) code to be able to inherit TemplateBase.
// Because in the normal environment/appdomain we run as full trust and the Razor assembly has no security attributes
// it will be completely SecurityCritical.
// This means we have to mark a lot of our members SecurityCritical (which is fine).
// However in the sandbox domain we have partial trust and because razor has no Security attributes that means the
// code will be transparent (this is where we get a lot of exceptions, because we now have different security attributes)
// To work around this we give Razor full trust in the sandbox as well.
StrongName razorAssembly = typeof(RazorTemplateEngine).Assembly.Evidence.GetHostEvidence<StrongName>();
// We trust ourself as well
StrongName testAssembly = typeof(IsolatedRazorEngineServiceTestFixture).Assembly.Evidence.GetHostEvidence<StrongName>();
AppDomainSetup adSetup = new AppDomainSetup();
adSetup.ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
AppDomain newDomain = AppDomain.CreateDomain("Sandbox", null, adSetup, permSet, razorEngineAssembly, razorAssembly, testAssembly);
return newDomain;
#endif
}
/// <summary>
/// Tests that a simple template without a model can be parsed.
/// </summary>
[Test]
public void IsolatedRazorEngineService_WithNoModel_InSandbox()
{
using (var service = IsolatedRazorEngineService.Create(SandboxCreator))
{
const string template = "<h1>Hello World</h1>";
const string expected = template;
string result = service.RunCompile(template, "test");
Assert.That(result == expected, "Result does not match expected: " + result);
}
}
/// <summary>
/// Tests that a simple viewbag is working.
/// </summary>
[Test]
public void IsolatedRazorEngineService_DynamicViewBag_InSandBox()
{
using (var service = IsolatedRazorEngineService.Create(SandboxCreator))
{
const string template = "<h1>Hello @ViewBag.Test</h1>";
const string expected = "<h1>Hello TestItem</h1>";
dynamic viewbag = new DynamicViewBag();
viewbag.Test = "TestItem";
string result = service.RunCompile(template, "test", (Type)null, (object)null, (DynamicViewBag)viewbag);
Assert.AreEqual(expected, result);
}
}
/// <summary>
/// Tests that exchanging values on the viewbag works across app domains
/// </summary>
[Test]
public void IsolatedRazorEngineService_DynamicViewBag_FromSandBox()
{
using (var service = IsolatedRazorEngineService.Create(SandboxCreator))
{
const string template = "@{ ViewBag.Test = \"TestItem\"; }";
const string expected = "TestItem";
dynamic viewbag = new DynamicViewBag();
string result = service.RunCompile(template, "test", (Type)null, (object)null, (DynamicViewBag)viewbag);
Assert.AreEqual(expected, viewbag.Test);
}
}
/// <summary>
/// Tests that a simple viewbag is working.
/// </summary>
[Test]
public void IsolatedRazorEngineService_Dynamic_InSandBox()
{
using (var service = IsolatedRazorEngineService.Create(SandboxCreator))
{
const string template = "<h1>Hello @Model.Forename, @ViewBag.Test</h1>";
const string expected = "<h1>Hello Matt, TestItem</h1>";
dynamic viewbag = new DynamicViewBag();
viewbag.Test = "TestItem";
viewbag.Forename = "Matt";
string result = service.RunCompile(template, "test", null, (object)viewbag, (DynamicViewBag)viewbag);
Assert.AreEqual(expected, result);
}
}
/// <summary>
/// Tests that a bad template cannot do stuff
/// </summary>
[Test]
public void IsolatedRazorEngineService_BadTemplate_InSandbox()
{
using (var service = IsolatedRazorEngineService.Create(SandboxCreator))
{
string file = Path.Combine(Environment.CurrentDirectory, Path.GetRandomFileName());
string template = @"
@using System.IO
@{
File.WriteAllText(""$file$"", ""BAD DATA"");
}".Replace("$file$", file.Replace("\\", "\\\\"));
Assert.Throws<SecurityException>(() =>
{
service.RunCompile(template, "test");
});
Assert.IsFalse(File.Exists(file));
}
}
/// <summary>
/// Helper class to check the state of the remote AppDomain.
/// </summary>
public class AssemblyChecker : global::RazorEngine.CrossAppDomainObject
{
/// <summary>
/// The assemblies are called "@(namespace).@(class).dll"
/// </summary>
const string CompiledAssemblyPrefix = CompilerServiceBase.DynamicTemplateNamespace + "." + CompilerServiceBase.ClassNamePrefix;
/// <summary>
/// Check if a compiled assembly exists.
/// </summary>
/// <returns></returns>
public bool ExistsCompiledAssembly()
{
(new PermissionSet(PermissionState.Unrestricted)).Assert();
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
var razorEngine =
assemblies
.Where(a => a.FullName.StartsWith(CompiledAssemblyPrefix))
.FirstOrDefault();
return razorEngine != null;
}
/// <summary>
/// Check if everything is cleaned up.
/// </summary>
public void IsolatedRazorEngineService_CleanUpWorks()
{
var appDomain = SandboxCreator();
using (var service = IsolatedRazorEngineService.Create(() => appDomain))
{
string template = @"@Model.Name";
var result = service.RunCompile(template, "test", null, new { Name = "test" });
Assert.AreEqual("test", result);
ObjectHandle handle =
Activator.CreateInstanceFrom(
appDomain, typeof(AssemblyChecker).Assembly.ManifestModule.FullyQualifiedName,
typeof(AssemblyChecker).FullName
);
using (var localHelper = new AssemblyChecker())
{
Assert.False(localHelper.ExistsCompiledAssembly());
}
using (var remoteHelper = (AssemblyChecker)handle.Unwrap())
{
Assert.IsTrue(remoteHelper.ExistsCompiledAssembly());
}
}
Assert.Throws<AppDomainUnloadedException>(() => { Console.WriteLine(appDomain.FriendlyName); });
using (var localHelper = new AssemblyChecker())
{
Assert.False(localHelper.ExistsCompiledAssembly());
}
}
}
/// <summary>
/// Tests that a bad template cannot do stuff
/// </summary>
[Test]
public void IsolatedRazorEngineService_CleanUpWorks()
{
var current = AppDomain.CurrentDomain;
var appDomain = AppDomain.CreateDomain("TestDomain.IsolatedRazorEngineService_CleanUpWorks", current.Evidence, current.SetupInformation);
ObjectHandle handle =
Activator.CreateInstanceFrom(
appDomain, typeof(AssemblyChecker).Assembly.ManifestModule.FullyQualifiedName,
typeof(AssemblyChecker).FullName
);
using (var remoteHelper = (AssemblyChecker)handle.Unwrap())
{
remoteHelper.IsolatedRazorEngineService_CleanUpWorks();
}
}
/// <summary>
/// Tests that a very bad template cannot change its permissions.
/// </summary>
[Test]
public void IsolatedRazorEngineService_VeryBadTemplate_InSandbox()
{
using (var service = IsolatedRazorEngineService.Create(SandboxCreator))
{
string file = Path.Combine(Environment.CurrentDirectory, Path.GetRandomFileName());
string template = @"
@using System.IO
@using System.Security
@using System.Security.Permissions
@{
(new PermissionSet(PermissionState.Unrestricted)).Assert();
File.WriteAllText(""$file$"", ""BAD DATA"");
}".Replace("$file$", file.Replace("\\", "\\\\"));
Assert.Throws<InvalidOperationException>(() =>
{ // cannot create a file in template
service.RunCompile(template, "test");
});
Assert.IsFalse(File.Exists(file));
}
}
/// <summary>
/// Tests that a simple template without a model can be parsed.
/// </summary>
[Test]
public void RazorEngineService_VeryBadTemplate()
{
RazorEngineServiceTestFixture.RunTestHelper(service =>
{
string file = Path.Combine(Environment.CurrentDirectory, Path.GetRandomFileName());
string template = @"
@using System.IO
@using System.Security
@using System.Security.Permissions
@{
(new PermissionSet(PermissionState.Unrestricted)).Assert();
File.WriteAllText(""$file$"", ""BAD DATA"");
}".Replace("$file$", file.Replace("\\", "\\\\"));
var test = service.RunCompile(template, "test");
Assert.IsTrue(File.Exists(file));
File.Delete(file);
});
}
/// <summary>
/// Tests that a simple template without a model can be parsed.
/// </summary>
[Test]
public void IsolatedRazorEngineService_CanParseSimpleTemplate_WithNoModel()
{
using (var service = IsolatedRazorEngineService.Create())
{
const string template = "<h1>Hello World</h1>";
const string expected = template;
string result = service.RunCompile(template, "test");
Assert.That(result == expected, "Result does not match expected: " + result);
}
}
/// <summary>
/// Test that we can not access security critical types.
/// </summary>
[Test]
public void IsolatedRazorEngineService_StaticSecurityCriticalModel_InSandbox()
{
using (var service = IsolatedRazorEngineService.Create(SandboxCreator))
{
const string template = "<h1>Hello World @Model.Forename</h1>";
const string expected = "<h1>Hello World TestForename</h1>";
var model = new Person { Forename = "TestForename" };
Assert.Throws<MethodAccessException>(() =>
{ // Because we cannot access the template constructor (as there is a SecurityCritical type argument)
string result = service.RunCompile(template, "test", typeof(Person), model);
Assert.AreEqual(expected, result);
});
}
}
/// <summary>
/// Test that we can not access security critical members in model.
/// </summary>
[Test]
public void IsolatedRazorEngineService_StaticSecurityCriticalModelDynamicType_InSandBox()
{
using (var service = IsolatedRazorEngineService.Create(SandboxCreator))
{
const string template = "<h1>Hello @Model.Forename</h1>";
const string expected = "<h1>Hello Matt</h1>";
var model = new Person { Forename = "Matt" };
Assert.Throws<SecurityException>(() =>
{ // this time we have no security critical type argument but we still should not be able to access it...
string result = service.RunCompile(template, "test", null, model);
Assert.AreEqual(expected, result);
});
}
}
/// <summary>
/// Test that we can not access security critical types.
/// </summary>
[Test]
public void IsolatedRazorEngineService_StaticSecurityCriticalModelWrapped_InSandbox()
{
using (var service = IsolatedRazorEngineService.Create(SandboxCreator))
{
const string template = "<h1>Hello World @Model.Forename</h1>";
const string expected = "<h1>Hello World TestForename</h1>";
var model = new Person { Forename = "TestForename" };
string result = service.RunCompile(template, "test", null, new RazorDynamicObject(model));
Assert.AreEqual(expected, result);
}
}
/// <summary>
/// Test that we can access security transparent static models in a sandbox.
/// </summary>
[Test]
public void IsolatedRazorEngineService_StaticModel_InSandbox()
{
using (var service = IsolatedRazorEngineService.Create(SandboxCreator))
{
const string template = "<h1>Hello World @Model.Name</h1>";
const string expected = "<h1>Hello World TestForename</h1>";
// We "abuse" NameOnlyTemplateKey because it is SecurityTransparent and serializable.
var model = new NameOnlyTemplateKey("TestForename", ResolveType.Global, null);
string result = service.RunCompile(template, "test", typeof(NameOnlyTemplateKey), model);
Assert.AreEqual(expected, result);
}
}
/// <summary>
/// Test that we can access security transparent static models via "dynamic" in a sandbox.
/// </summary>
[Test]
public void IsolatedRazorEngineService_StaticModelDynamicType_InSandBox()
{
using (var service = IsolatedRazorEngineService.Create(SandboxCreator))
{
const string template = "<h1>Hello @Model.Name</h1>";
const string expected = "<h1>Hello Matt</h1>";
// We "abuse" NameOnlyTemplateKey because it is SecurityTransparent and serializable.
var model = new NameOnlyTemplateKey("Matt", ResolveType.Global, null);
string result = service.RunCompile(template, "test", null, model);
Assert.AreEqual(expected, result);
}
}
/// <summary>
/// Tests that a simple template with a model can be parsed.
/// </summary>
[Test]
public void IsolatedRazorEngineService_CanParseSimpleTemplate_WithComplexSerializableModel()
{
using (var service = IsolatedRazorEngineService.Create())
{
const string template = "<h1>Hello @Model.Forename</h1>";
const string expected = "<h1>Hello Matt</h1>";
var model = new Person { Forename = "Matt" };
string result = service.RunCompile(template, "test", typeof(Person), model);
Assert.That(result == expected, "Result does not match expected: " + result);
}
}
/// <summary>
/// Tests that a simple template with a non-serializable model cannot be parsed.
/// </summary>
[Test]
public void IsolatedRazorEngineService_CannotParseSimpleTemplate_WithComplexNonSerializableModel()
{
using (var service = IsolatedRazorEngineService.Create())
{
const string template = "<h1>Animal Type: @Model.Type</h1>";
Assert.Throws<SerializationException>(() =>
{
var model = new Animal { Type = "Cat" };
service.RunCompile(template, "test", typeof(Animal), model);
});
}
}
/// <summary>
/// Tests that a simple template with an anonymous model can be parsed.
/// </summary>
[Test]
public void IsolatedRazorEngineService_ParseSimpleTemplate_WithAnonymousModel()
{
using (var service = IsolatedRazorEngineService.Create())
{
const string template = "<h1>Animal Type: @Model.Type</h1>";
const string expected = "<h1>Animal Type: Cat</h1>";
var model = new { Type = "Cat" };
var result = service.RunCompile(template, "test", null, new RazorDynamicObject(model));
Assert.AreEqual(expected, result);
}
}
/// <summary>
/// Tests that a simple template with an anonymous model can be parsed within a sandbox.
/// </summary>
[Test]
public void IsolatedRazorEngineService_Sandbox_WithAnonymousModel()
{
using (var service = IsolatedRazorEngineService.Create(SandboxCreator))
{
const string template = "<h1>Animal Type: @Model.Type</h1>";
const string expected = "<h1>Animal Type: Cat</h1>";
var model = new { Type = "Cat" };
var result = service.RunCompile(template, "test", null, new RazorDynamicObject(model));
Assert.AreEqual(expected, result);
}
}
/// <summary>
/// Tests that a simple template with an expando model cannot be parsed.
/// </summary>
/// <remarks>
/// This may seem pointless to test, as the <see cref="IsolatedTemplateService"/> will explicitly
/// check and throw the exception, it's worth creating a test for future reference. It's also
/// something we can check should we ever find a way to support dynamic/anonymous objects
/// across application domain boundaries.
/// </remarks>
[Test]
public void IsolatedRazorEngineService_ParseSimpleTemplate_WithExpandoModel()
{
using (var service = IsolatedRazorEngineService.Create())
{
const string template = "<h1>Animal Type: @Model.Type</h1>";
const string expected = "<h1>Animal Type: Cat</h1>";
dynamic model = new ExpandoObject();
model.Type = "Cat";
var result = service.RunCompile(template, "test", null, (object)RazorDynamicObject.Create(model));
Assert.AreEqual(expected, result);
}
}
/// <summary>
/// Tests that a simple template with a dynamic model cannot be parsed.
/// </summary>
/// <remarks>
/// This may seem pointless to test, as the <see cref="IsolatedTemplateService"/> will explicitly
/// check and throw the exception, it's worth creating a test for future reference. It's also
/// something we can check should we ever find a way to support dynamic/anonymous objects
/// across application domain boundaries.
/// </remarks>
[Test]
public void IsolatedRazorEngineService_CannotParseSimpleTemplate_WithDynamicModel()
{
using (var service = IsolatedRazorEngineService.Create())
{
const string template = "<h1>Animal Type: @Model.Type</h1>";
const string expected = "<h1>Animal Type: Cat</h1>";
dynamic model = new ValueObject(new Dictionary<string, object> { { "Type", "Cat" } });
string result = service.RunCompile(template, "test", null, (object)RazorDynamicObject.Create(model));
Assert.AreEqual(expected, result);
}
}
/// <summary>
/// Tests that a simple template with an ISerializable model can be parsed within a sandbox.
/// </summary>
[Test]
public void IsolatedRazorEngineService_Sandbox_WithISerializableModel()
{
using (var service = IsolatedRazorEngineService.Create(SandboxCreator))
{
const string template = "<h1>Uri Host: @Model.Host</h1>";
const string expected = "<h1>Uri Host: example.com</h1>";
var model = new Uri("http://example.com");
var result = service.RunCompile(template, "test", null, (object)RazorDynamicObject.Create(model));
Assert.AreEqual(expected, result);
}
}
/// <summary>
/// Tests that an isolated template service cannot use the same application domain as the
/// main application domain.
/// </summary>
/// <remarks>
/// An isolated template service will unload it's child application domain on Dispose. We need to ensure
/// it doesn't attempt to unload the current application domain that it is running in. This may or may
/// not be the main application domain (but is very likely to be).
/// </remarks>
[Test]
public void IsolatedRazorEngineService_WillThrowException_WhenUsingMainAppDomain()
{
Assert.Throws<InvalidOperationException>(() =>
{
using (var service = IsolatedRazorEngineService.Create(() => AppDomain.CurrentDomain))
{ }
});
}
/// <summary>
/// Tests that an isolated template service cannot use a null application domain.
/// </summary>
/// <remarks>
/// I had considered using the default <see cref="IAppDomainFactory"/> to spawn a default
/// application domain to load templates into when a null value is returned, but behaviourly this didn't
/// seem like the right thing to do. If you're using an <see cref="IsolatedTemplateService"/>,
/// you should expect it to have a valid application domain, so passing null should cause an exception.
/// </remarks>
[Test]
public void IsolatedRazorEngineService_WillThrowException_WhenUsingNullAppDomain()
{
Assert.Throws<InvalidOperationException>(() =>
{
using (var service = IsolatedRazorEngineService.Create(() => null))
{ }
});
}
/// <summary>
/// Test Type.
/// </summary>
[Serializable]
public class InsecureConfigCreator : IsolatedRazorEngineService.IConfigCreator
{
/// <summary>
/// Test Type.
/// </summary>
public ITemplateServiceConfiguration CreateConfiguration()
{
var config = new TemplateServiceConfiguration();
config.DisableTempFileLocking = true;
return config;
}
}
/// <summary>
/// Tests that we cannot create an insecure sandbox.
/// </summary>
[Test]
public void IsolatedRazorEngineService_WillThrowException_WhenUsingDisableFileLocking()
{
Assert.Throws<InvalidOperationException>(() =>
{
using (var service = IsolatedRazorEngineService.Create(new InsecureConfigCreator(), SandboxCreator))
{
const string template = "<h1>Hello World</h1>";
const string expected = template;
string result = service.RunCompile(template, "test");
Assert.That(result == expected, "Result does not match expected: " + result);
}
});
}
/// <summary>
/// Test Type.
/// </summary>
[Serializable]
class ReferenceResolverConfigCreator : IsolatedRazorEngineService.IConfigCreator, IReferenceResolver
{
/// <summary>
/// Test Type.
/// </summary>
public ITemplateServiceConfiguration CreateConfiguration()
{
var config = new TemplateServiceConfiguration();
config.ReferenceResolver = this;
config.CompilerServiceFactory = new DefaultCompilerServiceFactory();
return config;
}
public IEnumerable<CompilerReference> GetReferences(TypeContext context, IEnumerable<CompilerReference> includeAssemblies = null)
{
// We need to return this standard set or even simple views blow up on
// a missing reference to System.Linq.
var loadedAssemblies = (new UseCurrentAssembliesReferenceResolver()).GetReferences(null);
foreach (var reference in loadedAssemblies)
yield return reference;
var testHelper = Path.Combine(
Path.GetDirectoryName(typeof(ReferenceResolverConfigCreator).Assembly.Location),
"test",
"TestHelper.dll");
yield return CompilerReference.From(testHelper);
}
}
/// <summary>
/// Tests that we can use types from other assemblies in templates.
/// Even when the type can be loaded.
/// </summary>
[Test]
public void IsolatedRazorEngineService_CheckThatWeCanUseUnknownTypesAtExecuteTime()
{
using (var service = IsolatedRazorEngineService.Create(new ReferenceResolverConfigCreator(), () => SandboxCreator(new IPermission[] {
new FileIOPermission(PermissionState.Unrestricted),
new ReflectionPermission(PermissionState.Unrestricted)
})))
{
var template = @"
@{
var t = new TestHelper.TestClass();
}
@t.TestProperty";
#if RAZOR4
const string expected = "\nTestPropert";
#else
const string expected = "\n\nTestPropert";
#endif
string result = service.RunCompile(template, "test");
Assert.That(result == expected, "Result does not match expected: " + result);
}
}
}
}