-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathDuckGenerator.cs
More file actions
339 lines (269 loc) · 10.6 KB
/
DuckGenerator.cs
File metadata and controls
339 lines (269 loc) · 10.6 KB
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
/********************************************************************************
* DuckGenerator.cs *
* *
* Author: Denes Solti *
********************************************************************************/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices.ComTypes;
using System.Threading.Tasks;
using Moq;
using NUnit.Framework;
[assembly: InternalsVisibleTo("Duck_6191D0BB1603D9ADCE5DC9C7263A20D7")]
[assembly: InternalsVisibleTo("Duck_B18DECEF59D57C6AB68D9A8E24528852")]
namespace Solti.Utils.Proxy.Generators.Tests
{
using Internals;
[TestFixture, Parallelizable(ParallelScope.All)]
public sealed class DuckGeneratorTests
{
private static Task<TInterface> CreateDuck<TInterface, TTarget>(TTarget target) where TInterface : class =>
DuckGenerator<TInterface, TTarget>.ActivateAsync(target);
[Test]
public async Task GeneratedDuck_ShouldWorkWithComplexInterfaces()
{
IList<int> proxy = await CreateDuck<IList<int>, IList<int>>(new List<int>());
Assert.DoesNotThrow(() => proxy.Add(1986));
Assert.That(proxy.Count, Is.EqualTo(1));
Assert.That(proxy[0], Is.EqualTo(1986));
}
public interface IGeneric
{
T Foo<T, TT>(T a, TT b);
}
public class Generic
{
public B Foo<B, C>(B a, C b) => default;
}
[Test]
public void GeneratedDuck_ShouldWorkWithGenerics() => Assert.DoesNotThrowAsync(() => CreateDuck<IGeneric, Generic>(new Generic()));
public interface IRef
{
ref object Foo(out string para);
ref readonly object Bar();
}
public class Ref
{
private object FObject = new object();
public ref object Foo(out string para)
{
para = "cica";
return ref FObject;
}
public ref readonly object Bar() => ref FObject;
}
[Test]
public async Task GeneratedProxy_ShouldHandleRefs()
{
IRef proxy = await CreateDuck<IRef, Ref>(new Ref());
string para = null;
Assert.DoesNotThrow(() => proxy.Foo(out para));
Assert.That(para, Is.EqualTo("cica"));
}
public interface IEventSource
{
event EventHandler Event;
}
public class EventSource
{
public event EventHandler Event;
public void Raise() => Event.Invoke(this, null);
}
[Test]
public void GeneratedProxy_ShouldBeAccessibleParallelly() => Assert.DoesNotThrowAsync(() => Task.WhenAll(100.Times(() => CreateDuck<IRef, Ref>(new Ref()))));
[Test]
public async Task GeneratedProxy_ShouldHandleEvents()
{
var src = new EventSource();
IEventSource proxy = await CreateDuck<IEventSource, EventSource>(src);
int callCount = 0;
proxy.Event += (s, a) => callCount++;
src.Raise();
Assert.That(callCount, Is.EqualTo(1));
}
internal interface IInternal
{
void Foo();
}
internal class Internal
{
internal void Foo() { }
}
[Test]
public void GeneratedProxy_ShouldWorkWithInternalTypes() =>
Assert.DoesNotThrowAsync(() => CreateDuck<IInternal, Internal>(new Internal()));
public interface IBar
{
string Foo { get; }
int Baz();
}
public interface IAnotherBar
{
string Foo { get; }
int Baz();
}
public class AnotherBarExplicit : IAnotherBar
{
string IAnotherBar.Foo => "cica";
int IAnotherBar.Baz() => 1986;
}
[Test]
public async Task GeneratedProxy_ShouldWorkWithExplicitImplementations()
{
IBar proxy = await CreateDuck<IBar, AnotherBarExplicit>(new AnotherBarExplicit());
Assert.That(proxy.Baz(), Is.EqualTo(1986));
proxy = await CreateDuck<IBar, IAnotherBar>(new AnotherBarExplicit());
Assert.That(proxy.Baz(), Is.EqualTo(1986));
}
private class Private : IBar
{
public int Baz() => 0;
public string Foo { get; }
}
[Test]
public void DuckGenerator_ShouldValidate()
{
Assert.ThrowsAsync<ArgumentException>(() => CreateDuck<object, object>(new object()));
Assert.ThrowsAsync<MemberAccessException>(() => CreateDuck<IBar, Private>(new Private()));
}
public class MyBar
{
public int Bar() => 0;
public int Baz() => 0;
public string Foo { get; }
}
[Test]
public void DuckGenerator_ShouldDistinguishByName() =>
Assert.DoesNotThrowAsync(() => DuckGenerator<IBar, MyBar>.GetGeneratedTypeAsync());
[Test]
public void DuckGenerator_ShouldThrowOnAmbiguousImplementation() =>
Assert.ThrowsAsync<AmbiguousMatchException>(() => DuckGenerator<IBar, MultipleBaz>.GetGeneratedTypeAsync());
public class MultipleBaz : IBar
{
string IBar.Foo => throw new NotImplementedException();
int IBar.Baz() => throw new NotImplementedException();
public int Baz() => throw new NotImplementedException();
}
[Test]
public void DuckGenerator_ShouldWorkWithAnonimObjects()
{
var anon = new
{
Cica = 1,
Kutya = "Dénes"
};
// anonim objektumok mindig internal-ok
Assert.DoesNotThrow(() => new DuckGenerator(typeof(IProps), anon.GetType()).GetGeneratedType());
}
public interface IProps
{
int Cica { get; }
string Kutya { get; }
}
[Test]
public void DuckGenerator_ShouldWorkWithGenericTypes() =>
Assert.DoesNotThrowAsync(() => DuckGenerator<IGeneric<int>, Generic<int>>.GetGeneratedTypeAsync());
public interface IGeneric<T> { T Foo(); }
public class Generic<T>
{
public T Foo() => default;
}
[Test]
public void DuckGenerator_ShouldCacheTheGeneratedAssemblyIfCacheDirectoryIsSet()
{
Generator generator = DuckGenerator<IGeneric<Guid>, Generic<Guid>>.Instance;
string tmpDir = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "tmp");
Directory.CreateDirectory(tmpDir);
string cacheFile = Path.Combine(tmpDir, $"{generator.GetDefaultAssemblyName()}.dll");
if (File.Exists(cacheFile))
File.Delete(cacheFile);
Mock<IAssemblyCachingConfiguration> mockCachingConfig = new(MockBehavior.Strict);
mockCachingConfig
.SetupGet(c => c.AssemblyCacheDir)
.Returns(tmpDir);
generator.EmitAsync
(
mockCachingConfig.Object,
SyntaxFactoryContext.Default with
{
ReferenceCollector = new ReferenceCollector()
},
default
).GetAwaiter().GetResult();
Assert.That(File.Exists(cacheFile));
}
[
Test
#if NETFRAMEWORK
, Ignore(".NET Framework cannot load assembly targeting .NET Core")
#endif
]
public async Task DuckGenerator_ShouldUseTheCachedAssemblyIfTheCacheDirectoryIsSet()
{
Generator generator = DuckGenerator<IGeneric<object>, Generic<object>>.Instance;
string
cacheDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
cacheFile = Path.Combine(cacheDir, $"{generator.GetDefaultAssemblyName()}.dll");
Mock<IAssemblyCachingConfiguration> mockCachingConfig = new(MockBehavior.Strict);
mockCachingConfig
.SetupGet(c => c.AssemblyCacheDir)
.Returns(cacheDir);
Type gt =
(
await generator.EmitAsync
(
mockCachingConfig.Object,
SyntaxFactoryContext.Default with
{
ReferenceCollector = new ReferenceCollector()
},
default
)
).Type;
Assert.That(gt.Assembly.Location, Is.EqualTo(cacheFile));
}
public static IEnumerable<Type> RandomInterfaces => Proxy.Tests.RandomInterfaces<string>
.Values
.Except(new[] { typeof(ITypeLib2), typeof(ITypeInfo2) })
#if NET8_0_OR_GREATER
.Except(new[] { typeof(IParsable<string>), typeof(ISpanParsable<string>) })
#endif
#if NETFRAMEWORK
.Where(iface => !iface.Name.StartsWith("_"))
#endif
;
[TestCaseSource(nameof(RandomInterfaces))]
public void DuckGenerator_ShouldWorkWith(Type iface) =>
Assert.DoesNotThrow(() => new DuckGenerator(iface, iface).GetGeneratedType());
[Test]
public void DuckGenerator_ShouldAssembleTheProxyOnce() =>
Assert.AreSame(DuckGenerator<ICloneable, ICloneable>.GetGeneratedType(), DuckGenerator<ICloneable, ICloneable>.GetGeneratedType());
[Test]
public void DuckGenerator_ShouldAssembleTheProxyOnce2() =>
Assert.AreSame(DuckGenerator<IQueryable, IQueryable>.GetGeneratedType(), new DuckGenerator(typeof(IQueryable), typeof(IQueryable)).GetGeneratedType());
#if NET8_0_OR_GREATER
[Test]
public void DuckGenerator_ShouldThrowInStaticAbstractMember() =>
Assert.Throws<NotSupportedException>(() => new DuckGenerator(typeof(IUtf8SpanParsable<int>), typeof(IUtf8SpanParsable<int>)).GetGeneratedType());
#endif
public interface IBase
{
void Foo();
}
public interface IDescendant : IBase
{
new void Foo();
}
public class MockDescendant
{
public void Foo() { }
}
[Test]
public void DuckGenerator_ShouldHandleOverrides() =>
Assert.DoesNotThrow(() => DuckGenerator<IDescendant, MockDescendant>.Activate(new MockDescendant()));
}
}