-
Notifications
You must be signed in to change notification settings - Fork 4.7k
/
ResourceManagerTests.cs
488 lines (431 loc) · 22.5 KB
/
ResourceManagerTests.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Drawing.Imaging;
using System.Linq;
using System.Resources;
using System.Diagnostics;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
using System.Threading;
using System.Threading.Tasks;
using System.Collections;
[assembly:NeutralResourcesLanguage("en")]
namespace System.Resources.Tests
{
namespace Resources
{
internal class TestClassWithoutNeutralResources
{
}
}
public class ResourceManagerTests
{
public static bool AllowsCustomResourceTypes => AppContext.TryGetSwitch("System.Resources.ResourceManager.AllowCustomResourceTypes", out bool isEnabled) ? isEnabled : true;
[Fact]
public static void ExpectMissingManifestResourceException()
{
MissingManifestResourceException e = Assert.Throws<MissingManifestResourceException> (() =>
{
Type resourceType = typeof(Resources.TestClassWithoutNeutralResources);
ResourceManager resourceManager = new ResourceManager(resourceType);
string actual = resourceManager.GetString("Any");
});
Assert.NotNull(e.Message);
}
public static IEnumerable<object[]> EnglishResourceData()
{
yield return new object[] { "One", "Value-One" };
yield return new object[] { "Two", "Value-Two" };
yield return new object[] { "Three", "Value-Three" };
yield return new object[] { "Empty", "" };
yield return new object[] { "InvalidKeyName", null };
}
[Theory]
[MemberData(nameof(EnglishResourceData))]
public static void GetString_Basic(string key, string expectedValue)
{
ResourceManager resourceManager = new ResourceManager("System.Resources.Tests.Resources.TestResx", typeof(ResourceManagerTests).GetTypeInfo().Assembly);
string actual = resourceManager.GetString(key);
Assert.Equal(expectedValue, actual);
Assert.Same(actual, resourceManager.GetString(key));
Assert.Equal(expectedValue, resourceManager.GetObject(key));
}
[Theory]
[MemberData(nameof(EnglishResourceData))]
public static void GetString_FromResourceType(string key, string expectedValue)
{
Type resourceType = typeof(Resources.TestResx);
ResourceManager resourceManager = new ResourceManager(resourceType);
string actual = resourceManager.GetString(key);
Assert.Equal(expectedValue, actual);
}
public static IEnumerable<object[]> CultureResourceData()
{
yield return new object[] { "OneLoc", "es", "Value-One(es)" }; // Find language specific resource
yield return new object[] { "OneLoc", "es-ES", "Value-One(es)" }; // Finds parent language of culture specific resource
yield return new object[] { "OneLoc", "es-MX", "Value-One(es-MX)" }; // Finds culture specific resource
yield return new object[] { "OneLoc", "fr", "Value-One" }; // Find neutral resource when language resources are absent
yield return new object[] { "OneLoc", "fr-CA", "Value-One" }; // Find neutral resource when culture and language resources are absent
yield return new object[] { "OneLoc", "fr-FR", "Value-One(fr-FR)" }; // Finds culture specific resource
yield return new object[] { "Lang", "es-MX", "es" }; // Finds lang specific string when key is missing in culture resource
yield return new object[] { "NeutOnly", "es-MX", "Neutral" }; // Finds neutral string when key is missing in culture and lang resource
}
[Theory]
[MemberData(nameof(CultureResourceData))]
public static void GetString_CultureFallback(string key, string cultureName, string expectedValue)
{
Type resourceType = typeof(Resources.TestResx);
ResourceManager resourceManager = new ResourceManager(resourceType);
var culture = new CultureInfo(cultureName);
string actual = resourceManager.GetString(key, culture);
Assert.Equal(expectedValue, actual);
}
[Fact]
public static void GetString_FromTestClassWithoutNeutralResources()
{
// This test is designed to complement the GetString_FromCulutureAndResourceType "fr" & "fr-CA" cases
// Together these tests cover the case where there exists a satellite assembly for "fr" which has
// resources for some types, but not all. This confirms the fallback through a satellite which matches
// culture but does not match resource file
Type resourceType = typeof(Resources.TestClassWithoutNeutralResources);
ResourceManager resourceManager = new ResourceManager(resourceType);
var culture = new CultureInfo("fr");
string actual = resourceManager.GetString("One", culture);
Assert.Equal("Value-One(fr)", actual);
}
static int ResourcesAfAZEvents = 0;
#if NET
static System.Reflection.Assembly AssemblyResolvingEventHandler(System.Runtime.Loader.AssemblyLoadContext alc, System.Reflection.AssemblyName name)
{
if (name.FullName.StartsWith("System.Resources.ResourceManager.Tests.resources"))
{
if (name.FullName.Contains("Culture=af-ZA"))
{
Assert.Equal(System.Runtime.Loader.AssemblyLoadContext.Default, alc);
Assert.Equal("System.Resources.ResourceManager.Tests.resources", name.Name);
Assert.Equal("af-ZA", name.CultureName);
Assert.Equal(0, ResourcesAfAZEvents);
ResourcesAfAZEvents++;
}
}
return null;
}
#endif
static System.Reflection.Assembly AssemblyResolveEventHandler(object sender, ResolveEventArgs args)
{
string name = args.Name;
if (name.StartsWith("System.Resources.ResourceManager.Tests.resources"))
{
if (name.Contains("Culture=af-ZA"))
{
#if NET
Assert.Equal(1, ResourcesAfAZEvents);
#else
Assert.Equal(0, ResourcesAfAZEvents);
#endif
ResourcesAfAZEvents++;
}
}
return null;
}
[ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
public static void GetString_ExpectEvents()
{
RemoteExecutor.Invoke(() =>
{
// Events only fire first time. Remote to make sure test runs in a separate process
Remote_ExpectEvents();
}).Dispose();
}
private static void Remote_ExpectEvents()
{
#if NET
System.Runtime.Loader.AssemblyLoadContext.Default.Resolving += AssemblyResolvingEventHandler;
#endif
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(AssemblyResolveEventHandler);
ResourcesAfAZEvents = 0;
Type resourceType = typeof(Resources.TestResx);
ResourceManager resourceManager = new ResourceManager(resourceType);
var culture = new CultureInfo("af-ZA");
string actual = resourceManager.GetString("One", culture);
Assert.Equal("Value-One", actual);
#if NET
Assert.Equal(2, ResourcesAfAZEvents);
#else
Assert.Equal(1, ResourcesAfAZEvents);
#endif
}
[Fact]
public static void HeaderVersionNumber()
{
Assert.Equal(1, ResourceManager.HeaderVersionNumber);
}
[Fact]
public static void MagicNumber()
{
Assert.Equal(unchecked((int)0xBEEFCACE), ResourceManager.MagicNumber);
}
[Fact]
public static void UsingResourceSet()
{
var resourceManager = new ResourceManager("System.Resources.Tests.Resources.TestResx", typeof(ResourceManagerTests).GetTypeInfo().Assembly, typeof(ResourceSet));
Assert.Equal(typeof(ResourceSet), resourceManager.ResourceSetType);
}
[Fact]
public static void BaseName()
{
var manager = new ResourceManager("System.Resources.Tests.Resources.TestResx", typeof(ResourceManagerTests).Assembly);
Assert.Equal("System.Resources.Tests.Resources.TestResx", manager.BaseName);
manager = new ResourceManager(typeof(System.Resources.Tests.Resources.TestResx));
Assert.Equal("System.Resources.Tests.Resources.TestResx", manager.BaseName);
Type typeWithoutNamespace = new { }.GetType();
Assert.Null(typeWithoutNamespace.Namespace);
manager = new ResourceManager(typeWithoutNamespace);
Assert.Equal(typeWithoutNamespace.Name, manager.BaseName);
manager = new ResourceManager(typeof(List<string>));
Assert.Equal("System.Collections.Generic.List`1", manager.BaseName);
}
[Theory]
[MemberData(nameof(EnglishResourceData))]
public static void IgnoreCase(string key, string expectedValue)
{
var manager = new ResourceManager("System.Resources.Tests.Resources.TestResx", typeof(ResourceManagerTests).GetTypeInfo().Assembly);
var culture = new CultureInfo("en-US");
Assert.False(manager.IgnoreCase);
Assert.Equal(expectedValue, manager.GetString(key, culture));
Assert.Null(manager.GetString(key.ToLower(), culture));
manager.IgnoreCase = true;
Assert.Equal(expectedValue, manager.GetString(key, culture));
Assert.Equal(expectedValue, manager.GetString(key.ToLower(), culture));
}
/// <summary>
/// This test has multiple threads simultaneously loop over the keys of a moderately-sized resx using
/// <see cref="ResourceManager"/> and call <see cref="ResourceManager.GetString(string)"/> for each key.
/// This has historically been prone to thread-safety bugs because of the shared cache state and internal
/// method calls between RuntimeResourceSet and <see cref="ResourceReader"/>.
///
/// Running with <paramref name="useEnumeratorEntry"/> TRUE replicates https://github.com/dotnet/runtime/issues/74868,
/// while running with FALSE replicates the error from https://github.com/dotnet/runtime/issues/74052.
/// </summary>
/// <param name="useEnumeratorEntry">
/// Whether to use <see cref="IDictionaryEnumerator.Entry"/> vs. <see cref="IDictionaryEnumerator.Key"/> when enumerating;
/// these follow fairly different code paths.
/// </param>
[Theory]
[InlineData(false)]
[InlineData(true)]
public static void TestResourceManagerIsSafeForConcurrentAccessAndEnumeration(bool useEnumeratorEntry)
{
ResourceManager manager = new("System.Resources.Tests.Resources.AToZResx", typeof(ResourceManagerTests).GetTypeInfo().Assembly);
const int Threads = 10;
using Barrier barrier = new(Threads);
Task[] tasks = Enumerable.Range(0, Threads)
.Select(_ => Task.Factory.StartNew(
WaitForBarrierThenEnumerateResources,
CancellationToken.None,
TaskCreationOptions.LongRunning,
TaskScheduler.Default))
.ToArray();
Assert.True(Task.WaitAll(tasks, TimeSpan.FromSeconds(30)));
void WaitForBarrierThenEnumerateResources()
{
barrier.SignalAndWait();
ResourceSet set = manager.GetResourceSet(CultureInfo.InvariantCulture, createIfNotExists: true, tryParents: true);
IDictionaryEnumerator enumerator = set.GetEnumerator();
while (enumerator.MoveNext())
{
object key = useEnumeratorEntry ? enumerator.Entry.Key : enumerator.Key;
manager.GetObject((string)key);
Thread.Sleep(1);
}
}
}
public static IEnumerable<object[]> EnglishNonStringResourceData()
{
yield return new object[] { "Int", 42, false };
yield return new object[] { "Float", 3.14159, false };
yield return new object[] { "Bytes", new byte[] { 41, 42, 43, 44, 192, 168, 1, 1 }, false };
yield return new object[] { "InvalidKeyName", null, false };
yield return new object[] { "Point", new Point(50, 60), true };
yield return new object[] { "Size", new Size(20, 30), true };
}
[ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsBinaryFormatterSupported))]
[MemberData(nameof(EnglishNonStringResourceData))]
[ActiveIssue("https://github.com/dotnet/runtime/issues/50935", TestPlatforms.Android)]
public static void GetObject(string key, object expectedValue, bool requiresBinaryFormatter)
{
_ = requiresBinaryFormatter;
var manager = new ResourceManager("System.Resources.Tests.Resources.TestResx.netstandard17", typeof(ResourceManagerTests).GetTypeInfo().Assembly);
Assert.Equal(expectedValue, manager.GetObject(key));
Assert.Equal(expectedValue, manager.GetObject(key, new CultureInfo("en-US")));
}
private static byte[] GetImageData(object obj)
{
using (var stream = new MemoryStream())
{
switch (obj)
{
case Image image:
image.Save(stream, ImageFormat.Bmp);
break;
case Icon icon:
icon.Save(stream);
break;
default:
throw new NotSupportedException();
}
return stream.ToArray();
}
}
public static IEnumerable<object[]> EnglishImageResourceData()
{
yield return new object[] { "Bitmap", new Bitmap("bitmap.bmp") };
yield return new object[] { "Icon", new Icon("icon.ico") };
}
[ConditionalTheory(nameof(IsDrawingSupportedAndAllowsCustomResourceTypes))]
[ActiveIssue("https://github.com/dotnet/runtime/issues/34008", TestPlatforms.Linux | TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)]
[MemberData(nameof(EnglishImageResourceData))]
public static void GetObject_Images(string key, object expectedValue)
{
var manager = new ResourceManager("System.Resources.Tests.Resources.TestResx.netstandard17", typeof(ResourceManagerTests).GetTypeInfo().Assembly);
Assert.Equal(GetImageData(expectedValue), GetImageData(manager.GetObject(key)));
Assert.Equal(GetImageData(expectedValue), GetImageData(manager.GetObject(key, new CultureInfo("en-US"))));
}
[ConditionalTheory(nameof(IsDrawingSupportedAndAllowsCustomResourceTypes))]
[ActiveIssue("https://github.com/dotnet/runtime/issues/34008", TestPlatforms.Linux | TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)]
[MemberData(nameof(EnglishImageResourceData))]
public static void GetObject_Images_ResourceSet(string key, object expectedValue)
{
var manager = new ResourceManager(
"System.Resources.Tests.Resources.TestResx.netstandard17",
typeof(ResourceManagerTests).GetTypeInfo().Assembly,
typeof(ResourceSet));
Assert.Equal(GetImageData(expectedValue), GetImageData(manager.GetObject(key)));
Assert.Equal(GetImageData(expectedValue), GetImageData(manager.GetObject(key, new CultureInfo("en-US"))));
}
[Theory]
[MemberData(nameof(EnglishResourceData))]
public static void GetResourceSet_Strings(string key, string expectedValue)
{
var manager = new ResourceManager("System.Resources.Tests.Resources.TestResx", typeof(ResourceManagerTests).GetTypeInfo().Assembly);
var culture = new CultureInfo("en-US");
ResourceSet set = manager.GetResourceSet(culture, true, true);
Assert.Equal(expectedValue, set.GetString(key));
Assert.Equal(expectedValue, set.GetObject(key));
Assert.Equal(expectedValue, set.GetString(key));
}
[ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsBinaryFormatterSupported))]
[MemberData(nameof(EnglishNonStringResourceData))]
[ActiveIssue("https://github.com/dotnet/runtime/issues/50935", TestPlatforms.Android)]
public static void GetResourceSet_NonStrings(string key, object expectedValue, bool requiresBinaryFormatter)
{
_ = requiresBinaryFormatter;
var manager = new ResourceManager("System.Resources.Tests.Resources.TestResx.netstandard17", typeof(ResourceManagerTests).GetTypeInfo().Assembly);
var culture = new CultureInfo("en-US");
ResourceSet set = manager.GetResourceSet(culture, true, true);
Assert.Equal(expectedValue, set.GetObject(key));
Assert.Equal(expectedValue, set.GetObject(key));
}
[ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsBinaryFormatterSupported))]
[MemberData(nameof(EnglishNonStringResourceData))]
[ActiveIssue("https://github.com/dotnet/runtime/issues/50935", TestPlatforms.Android)]
public static void GetResourceSet_NonStringsIgnoreCase(string key, object expectedValue, bool requiresBinaryFormatter)
{
_ = requiresBinaryFormatter;
var manager = new ResourceManager("System.Resources.Tests.Resources.TestResx.netstandard17", typeof(ResourceManagerTests).GetTypeInfo().Assembly);
var culture = new CultureInfo("en-US");
ResourceSet set = manager.GetResourceSet(culture, true, true);
Assert.Equal(expectedValue, set.GetObject(key.ToLower(), true));
Assert.Equal(expectedValue, set.GetObject(key.ToLower(), true));
}
public static bool IsDrawingSupportedAndAllowsCustomResourceTypes => PlatformDetection.IsDrawingSupported && AllowsCustomResourceTypes;
[ConditionalTheory(nameof(IsDrawingSupportedAndAllowsCustomResourceTypes))]
[ActiveIssue("https://github.com/dotnet/runtime/issues/34008", TestPlatforms.Linux | TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)]
[MemberData(nameof(EnglishImageResourceData))]
public static void GetResourceSet_Images(string key, object expectedValue)
{
var manager = new ResourceManager("System.Resources.Tests.Resources.TestResx.netstandard17", typeof(ResourceManagerTests).GetTypeInfo().Assembly);
var culture = new CultureInfo("en-US");
ResourceSet set = manager.GetResourceSet(culture, true, true);
Assert.Equal(GetImageData(expectedValue), GetImageData(set.GetObject(key)));
}
[Theory]
[MemberData(nameof(EnglishNonStringResourceData))]
public static void File_GetObject(string key, object expectedValue, bool requiresBinaryFormatter)
{
var manager = ResourceManager.CreateFileBasedResourceManager("TestResx.netstandard17", Directory.GetCurrentDirectory(), null);
if (requiresBinaryFormatter)
{
Assert.Throws<NotSupportedException>(() => manager.GetObject(key));
Assert.Throws<NotSupportedException>(() => manager.GetObject(key, new CultureInfo("en-US")));
}
else
{
Assert.Equal(expectedValue, manager.GetObject(key));
Assert.Equal(expectedValue, manager.GetObject(key, new CultureInfo("en-US")));
}
}
[Theory]
[MemberData(nameof(EnglishNonStringResourceData))]
public static void File_GetResourceSet_NonStrings(string key, object expectedValue, bool requiresBinaryFormatter)
{
var manager = ResourceManager.CreateFileBasedResourceManager("TestResx.netstandard17", Directory.GetCurrentDirectory(), null);
var culture = new CultureInfo("en-US");
ResourceSet set = manager.GetResourceSet(culture, true, true);
if (requiresBinaryFormatter)
{
Assert.Throws<NotSupportedException>(() => set.GetObject(key));
}
else
{
Assert.Equal(expectedValue, set.GetObject(key));
}
}
[Fact]
public static void GetStream()
{
var manager = new ResourceManager("System.Resources.Tests.Resources.TestResx.netstandard17", typeof(ResourceManagerTests).GetTypeInfo().Assembly);
var culture = new CultureInfo("en-US");
var expectedBytes = new byte[] { 41, 42, 43, 44, 192, 168, 1, 1 };
using (Stream stream = manager.GetStream("ByteStream"))
{
foreach (byte b in expectedBytes)
{
Assert.Equal(b, stream.ReadByte());
}
}
using (Stream stream = manager.GetStream("ByteStream", culture))
{
foreach (byte b in expectedBytes)
{
Assert.Equal(b, stream.ReadByte());
}
}
}
[Fact]
public static void ConstructorNonRuntimeAssembly()
{
MockAssembly assembly = new MockAssembly();
Assert.Throws<ArgumentException>(() => new ResourceManager("name", assembly));
Assert.Throws<ArgumentException>(() => new ResourceManager("name", assembly, null));
}
[Fact]
public static void GetStringAfterDispose()
{
var manager = new ResourceManager("System.Resources.Tests.Resources.TestResx", typeof(ResourceManagerTests).GetTypeInfo().Assembly);
var culture = new CultureInfo("en-US");
ResourceSet set = manager.GetResourceSet(culture, true, true);
set.GetString("Any");
((IDisposable)set).Dispose();
Assert.Throws<ObjectDisposedException> (() => set.GetString("Any"));
}
private class MockAssembly : Assembly
{
}
}
}