File: TestBase.cs

package info (click to toggle)
mono-reference-assemblies 3.12.1%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 604,240 kB
  • ctags: 625,505
  • sloc: cs: 3,967,741; xml: 2,793,081; ansic: 418,042; java: 60,435; sh: 14,833; makefile: 11,576; sql: 7,956; perl: 1,467; cpp: 1,446; yacc: 1,203; python: 598; asm: 422; sed: 16; php: 1
file content (512 lines) | stat: -rw-r--r-- 19,975 bytes parent folder | download | duplicates (2)
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
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.

namespace System.Data.Entity
{
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.Configuration;
    using System.Data.Common;
    using System.Data.Entity.Config;
    using System.Data.Entity.Core.EntityClient;
    using System.Data.Entity.Core.Metadata.Edm;
    using System.Data.Entity.Core.Objects;
    using System.Data.Entity.Infrastructure;
    using System.Data.Entity.Internal.ConfigFile;
    using System.Data.Entity.SqlServer;
    using System.Data.Entity.TestHelpers;
    using System.Data.SqlClient;
    using System.IO;
    using System.Reflection;
    using System.Threading.Tasks;
    using System.Transactions;
    using System.Xml.Linq;

    public class TestBase : MarshalByRefObject
    {
        static TestBase()
        {
            DbConfiguration.SetConfiguration(new FunctionalTestsConfiguration());
        }

        internal DbDatabaseMapping BuildMapping(DbModelBuilder modelBuilder)
        {
            OnModelCreating(modelBuilder);
            // Build and clone to check for idempotency issues.

            modelBuilder.Build(ProviderRegistry.Sql2008_ProviderInfo);

            var clone = modelBuilder.Clone();

            return clone.Build(ProviderRegistry.Sql2008_ProviderInfo).DatabaseMapping;
        }

        protected virtual void OnModelCreating(DbModelBuilder modelBuilder)
        {
            // For fixture wide configuration
        }

        internal DbDatabaseMapping BuildCeMapping(DbModelBuilder modelBuilder)
        {
            // Build and clone to check for idempotency issues.

            modelBuilder.Build(ProviderRegistry.SqlCe4_ProviderInfo);

            var clone = modelBuilder.Clone();

            return clone.Build(ProviderRegistry.SqlCe4_ProviderInfo).DatabaseMapping;
        }

        protected static DataRow CreateProviderRow(string name, string invariantName, string assemblyQualifiedName)
        {
            var table = new DataTable();
            table.Columns.AddRange(
                new[]
                    {
                        new DataColumn("Name", typeof(string)),
                        new DataColumn("Description", typeof(string)),
                        new DataColumn("InvariantName", typeof(string)),
                        new DataColumn("AssemblyQualifiedName", typeof(string)),
                    });

            var row = table.NewRow();
            row["Name"] = name;
            row["Description"] = "Name: " + name + " Invariant: " + invariantName;
            row["InvariantName"] = invariantName;
            row["AssemblyQualifiedName"] = assemblyQualifiedName;
            return row;
        }

        protected static void RunTestWithTempMetadata(string csdl, string ssdl, string msl, Action<IEnumerable<string>> test)
        {
            var paths = new[]
                {
                    Path.GetTempFileName() + ".ssdl",
                    Path.GetTempFileName() + ".csdl",
                    Path.GetTempFileName() + ".msl"
                };
            var metadata = new[]
                {
                    ssdl,
                    csdl,
                    msl
                };
            try
            {
                for (var i = 0; i < metadata.Length; i++)
                {
                    using (var file = File.CreateText(paths[i]))
                    {
                        file.Write(metadata[i]);
                    }
                }
                test(paths);
            }
            finally
            {
                foreach (var path in paths)
                {
                    try
                    {
                        File.SetAttributes(path, File.GetAttributes(path) & ~FileAttributes.ReadOnly);
                        File.Delete(path);
                    }
                    catch (FileNotFoundException)
                    {
                    }
                }
            }
        }

        #region Assemblies and exceptions

        /// <summary>
        ///     The assembly containing Code First and the Productivity API.
        /// </summary>
        public static Assembly EntityFrameworkAssembly
        {
            get { return typeof(DbModelBuilder).Assembly; }
        }

        /// <summary>
        ///     System.ComponentModel.DataAnnotations.
        /// </summary>
        public static Assembly SystemComponentModelDataAnnotationsAssembly
        {
            get { return typeof(ValidationAttribute).Assembly; }
        }

        /// <summary>
        ///     EntityFramework.SqlServer
        /// </summary>
        public static Assembly EntityFrameworkSqlServerAssembly
        {
            get { return typeof(SqlProviderServices).Assembly; }
        }

        /// <summary>
        ///     Gets an embedded resource string from the specified assembly
        /// </summary>
        public static string LookupString(Assembly assembly, string resourceTable, string resourceKey)
        {
            return new AssemblyResourceLookup(assembly, resourceTable).LookupString(resourceKey);
        }

        /// <summary>
        ///     Executes the given delegate and returns the exception that it throws.
        /// </summary>
        protected Exception GenerateException(Action willThrow)
        {
            return ExceptionHelpers.GenerateException(willThrow);
        }

        /// <summary>
        ///     Executes the given test multiple times in parallel.
        /// </summary>
        /// <param name="test"> The test. </param>
        /// <param name="count"> The number of copies to run in parallel. </param>
        protected static void ExecuteInParallel(Action test, int count = 20)
        {
            var tests = new Action[count];
            for (var i = 0; i < count; i++)
            {
                tests[i] = test;
            }
            Parallel.Invoke(tests);
        }

        #endregion

        #region GetObjectContext

        /// <summary>
        ///     Returns the ObjectContext for the given DbContext.
        /// </summary>
        public static ObjectContext GetObjectContext(DbContext context)
        {
            return ((IObjectContextAdapter)context).ObjectContext;
        }

        #endregion

        #region State entry helpers

        /// <summary>
        ///     Gets all GetStateEntries for the given DbContext,.
        /// </summary>
        /// <param name="dbContext"> A DbContext instance. </param>
        /// <returns> All state entries in the ObjectStateManager. </returns>
        protected static IEnumerable<ObjectStateEntry> GetStateEntries(DbContext dbContext)
        {
            return ModelHelpers.GetStateEntries(dbContext);
        }

        /// <summary>
        ///     Gets all GetStateEntries for the given ObjectContext,.
        /// </summary>
        /// <param name="objectContext"> A ObjectContext instance. </param>
        /// <returns> All state entries in the ObjectStateManager. </returns>
        protected static IEnumerable<ObjectStateEntry> GetStateEntries(ObjectContext objectContext)
        {
            return ModelHelpers.GetStateEntries(objectContext);
        }

        /// <summary>
        ///     Gets the ObjectStateEntry for the given entity in the given DbContext.
        /// </summary>
        /// <param name="dbContext"> A DbContext instance. </param>
        /// <param name="entity"> The entity to lookup. </param>
        /// <returns> The ObjectStateEntry. </returns>
        protected static ObjectStateEntry GetStateEntry(DbContext dbContext, object entity)
        {
            return ModelHelpers.GetStateEntry(dbContext, entity);
        }

        /// <summary>
        ///     Gets the ObjectStateEntry for the given entity in the given ObjectContext.
        /// </summary>
        /// <param name="objectContext"> A ObjectContext instance. </param>
        /// <param name="entity"> The entity to lookup. </param>
        /// <returns> The ObjectStateEntry. </returns>
        protected static ObjectStateEntry GetStateEntry(ObjectContext objectContext, object entity)
        {
            return ModelHelpers.GetStateEntry(objectContext, entity);
        }

        /// <summary>
        ///     Asserts that there's no ObjectStateEntry for the given entity in the given DbContext.
        /// </summary>
        /// <param name="dbContext"> A DbContext instance. </param>
        /// <param name="entity"> The entity to lookup. </param>
        public static void AssertNoStateEntry(DbContext dbContext, object entity)
        {
            ModelHelpers.AssertNoStateEntry(dbContext, entity);
        }

        /// <summary>
        ///     Asserts that there's no ObjectStateEntry for the given entity in the given ObjectContext.
        /// </summary>
        /// <param name="objectContext"> A ObjectContext instance. </param>
        /// <param name="entity"> The entity to lookup. </param>
        public static void AssertNoStateEntry(ObjectContext objectContext, object entity)
        {
            ModelHelpers.AssertNoStateEntry(objectContext, entity);
        }

        #endregion

        #region Connection helpers

        /// <summary>
        ///     Returns a simple SQL Server connection string to the local machine with the given database name.
        /// </summary>
        /// <param name="databaseName"> The database name. </param>
        /// <returns> The connection string. </returns>
        protected static string SimpleConnectionString(string databaseName)
        {
            return ModelHelpers.SimpleConnectionString(databaseName);
        }

        /// <summary>
        ///     Returns a simple SQL Server connection string with the specified credentials.
        /// </summary>
        /// <param name="databaseName"> The database name. </param>
        /// <param name="userId"> User ID to be use when connecting to SQL Server. </param>
        /// <param name="password"> Password for the SQL Server account. </param>
        /// <param name="persistSecurityInfo">
        ///     Indicates if security-sensitive information is not returned as part of the 
        ///     connection if the connection has ever been opened.
        /// </param>
        /// <returns> The connection string. </returns>
        protected static string SimpleConnectionStringWithCredentials(
            string databaseName,
            string userId,
            string password,
            bool persistSecurityInfo = false)
        {
            return ModelHelpers.SimpleConnectionStringWithCredentials(
                databaseName,
                userId,
                password,
                persistSecurityInfo);
        }

        /// <summary>
        ///     Returns the default name that will be created for the context of the given type.
        /// </summary>
        /// <typeparam name="TContext"> The type of the context to create a name for. </typeparam>
        /// <returns> The name. </returns>
        protected static string DefaultDbName<TContext>() where TContext : DbContext
        {
            return ModelHelpers.DefaultDbName<TContext>();
        }

        /// <summary>
        ///     Returns the transaction count from the server.
        /// </summary>
        /// <param name="connection"> Database connection to connect against. </param>
        /// <returns> The transaction count. </returns>
        protected int GetTransactionCount(DbConnection connection)
        {
            var closeconn = false;

            if (connection.State
                != ConnectionState.Open)
            {
                connection.Open();
                closeconn = true;
            }

            var cmd = connection.CreateCommand();
            cmd.CommandText = "select @@TranCount";
            var trancount = (int)cmd.ExecuteScalar();

            if (closeconn)
            {
                connection.Close();
            }

            return trancount;
        }

        /// <summary>
        ///     Returns a local transaction.
        /// </summary>
        /// <param name="context"> </param>
        /// <returns> </returns>
        protected DbTransaction BeginLocalTransaction(DbContext context)
        {
            return OpenEntityConnection(context).BeginTransaction();
        }

        /// <summary>
        ///     Opens the underlying <see cref="EntityConnection" /> obtained from the underlying
        ///     <see cref="ObjectContext" /> and creates a new <see cref="CommittableTransaction" />.
        /// </summary>
        /// <param name="context"> </param>
        /// <returns> </returns>
        protected CommittableTransaction BeginCommittableTransaction(DbContext context)
        {
            OpenEntityConnection(context);

            return new CommittableTransaction();
        }

        /// <summary>
        ///     Opens the underlying <see cref="EntityConnection" /> obtained from the underlying
        ///     <see cref="ObjectContext" /> and returns it.
        /// </summary>
        /// <param name="context"> The context. </param>
        /// <returns> The connection. </returns>
        private static EntityConnection OpenEntityConnection(DbContext context)
        {
            var connection = (EntityConnection)((IObjectContextAdapter)context).ObjectContext.Connection;
            if (connection.State
                != ConnectionState.Open)
            {
                connection.Open();
            }

            return connection;
        }

        /// <summary>
        ///     Closes the underlying <see cref="EntityConnection" /> obtained from the underlying
        ///     <see cref="ObjectContext" /> if the connection is open.
        /// </summary>
        protected void CloseEntityConnection(DbContext context)
        {
            var connection = ((IObjectContextAdapter)context).ObjectContext.Connection;
            if (connection.State
                == ConnectionState.Open)
            {
                connection.Close();
            }
        }

        /// <summary>
        ///     Returns a simple SQL Server connection string to the local machine for the given context type.
        /// </summary>
        /// <typeparam name="TContext"> The type of the context to create a connection string for. </typeparam>
        /// <returns> The connection string. </returns>
        protected static string SimpleConnectionString<TContext>() where TContext : DbContext
        {
            return ModelHelpers.SimpleConnectionString<TContext>();
        }

        /// <summary>
        ///     Returns a simple SQL Server connection string to the local machine using attached database for the given context type.
        /// </summary>
        /// <typeparam name="TContext"> The type of the context to create a connection string for. </typeparam>
        /// <returns> The connection string. </returns>
        protected static string SimpleAttachConnectionString<TContext>() where TContext : DbContext
        {
            return ModelHelpers.SimpleAttachConnectionString<TContext>();
        }

        /// <summary>
        ///     Returns a simple SQLCE connection string to the local machine for the given context type.
        /// </summary>
        /// <typeparam name="TContext"> The type of the context. </typeparam>
        /// <returns> The connection string. </returns>
        protected static string SimpleCeConnectionString<TContext>() where TContext : DbContext
        {
            return ModelHelpers.SimpleCeConnectionString<TContext>();
        }

        /// <summary>
        ///     Returns a simple SQL Server connection to the local machine for the given context type.
        /// </summary>
        /// <typeparam name="TContext"> The type of the context to create a connection for. </typeparam>
        /// <returns> The connection. </returns>
        protected static SqlConnection SimpleConnection<TContext>() where TContext : DbContext
        {
            return ModelHelpers.SimpleConnection<TContext>();
        }

        /// <summary>
        ///     Returns a simple SQL CE connection for the given context type.
        /// </summary>
        /// <typeparam name="TContext"> The type of the context to create a connection for. </typeparam>
        /// <returns> The connection. </returns>
        protected static DbConnection SimpleCeConnection<TContext>() where TContext : DbContext
        {
            return ModelHelpers.SimpleCeConnection<TContext>();
        }

        #endregion

        #region Entity set name helpers

        /// <summary>
        ///     Gets the entity set name for the given CLR type, assuming no MEST.
        /// </summary>
        /// <param name="dbContext"> The context to look in. </param>
        /// <param name="clrType"> The type to lookup. </param>
        /// <returns> The entity set name. </returns>
        protected static string GetEntitySetName(DbContext dbContext, Type clrType)
        {
            return ModelHelpers.GetEntitySetName(dbContext, clrType);
        }

        /// <summary>
        ///     Gets the entity set name for the given CLR type, assuming no MEST.
        /// </summary>
        /// <param name="objetContext"> The context to look in. </param>
        /// <param name="clrType"> The type to lookup. </param>
        /// <returns> The entity set name. </returns>
        protected static string GetEntitySetName(ObjectContext objetContext, Type clrType)
        {
            return ModelHelpers.GetEntitySetName(objetContext, clrType);
        }

        #endregion

        #region Entity Type helpers

        /// <summary>
        ///     Gets the EntityType of the given CLR type
        /// </summary>
        /// <param name="dbContext"> The context to look in. </param>
        /// <param name="clrType"> The CLR type </param>
        /// <returns> The entity type corresponding to the CLR type </returns>
        protected static EntityType GetEntityType(DbContext dbContext, Type clrType)
        {
            return ModelHelpers.GetEntityType(dbContext, clrType);
        }

        /// <summary>
        ///     Gets the EntityType of the given CLR type
        /// </summary>
        /// <param name="objectContext"> The context to look in. </param>
        /// <param name="clrType"> The CLR type </param>
        /// <returns> The entity type corresponding to the CLR type </returns>
        protected static EntityType GetEntityType(ObjectContext objectContext, Type clrType)
        {
            return ModelHelpers.GetStructuralType<EntityType>(objectContext, clrType);
        }

        #endregion

        #region Creating config documents

        public static Configuration CreateEmptyConfig()
        {
            var tempFileName = Path.GetTempFileName();
            var doc = new XDocument(new XElement("configuration"));
            doc.Save(tempFileName);

            var config = ConfigurationManager.OpenMappedExeConfiguration(
                new ExeConfigurationFileMap
                    {
                        ExeConfigFilename = tempFileName
                    },
                ConfigurationUserLevel.None);

            config.Sections.Add("entityFramework", new EntityFrameworkSection());

            return config;
        }

        #endregion
    }
}