コード例 #1
0
        public AutoGeneratorsFixture()
        {
            var faker  = new Faker();
            var binder = new AutoBinder();

            _context = new AutoGenerateContext(faker, Enumerable.Empty <string>(), binder);
        }
コード例 #2
0
        public override bool CanOverride(AutoGenerateContext context)
        {
            var result = context.GenerateType.IsPrimitive || context.GenerateType == typeof(string) ||
                         context.GenerateType == typeof(decimal) || context.GenerateType.IsEnum;

            return(result);
        }
コード例 #3
0
        object IAutoGenerator.Generate(AutoGenerateContext context)
        {
            // Create an instance of a dictionary (public and non-public)
            IDictionary <TKey, TValue> items;

            try
            {
                items = (IDictionary <TKey, TValue>)Activator.CreateInstance(context.GenerateType, true);
            }
            catch
            {
                items = new Dictionary <TKey, TValue>();
            }

            // Get a list of keys
            var keys = context.GenerateUniqueMany <TKey>();

            foreach (var key in keys)
            {
                // Get a matching value for the current key and add to the dictionary
                var value = context.Generate <TValue>();

                if (value != null)
                {
                    items.Add(key, value);
                }
            }

            return(items);
        }
コード例 #4
0
        public object Generate(AutoGenerateContext context)
        {
            var table = CreateTable(context);

            PopulateRows(table, context);

            return(table);
        }
コード例 #5
0
        object IAutoGenerator.Generate(AutoGenerateContext context)
        {
            IAutoGenerator generator = new DictionaryGenerator <TKey, TValue>();

            // Generate a standard dictionary and create the read only dictionary
            var items = generator.Generate(context) as IDictionary <TKey, TValue>;

            return(new ReadOnlyDictionary <TKey, TValue>(items));
        }
コード例 #6
0
        /// <summary>
        /// Creates an instance of <typeparamref name="TType"/>.
        /// </summary>
        /// <typeparam name="TType">The type of instance to create.</typeparam>
        /// <param name="context">The <see cref="AutoGenerateContext"/> instance for the generate request.</param>
        /// <returns>The created instance of <typeparamref name="TType"/>.</returns>
        public override TType CreateInstance <TType>(AutoGenerateContext context)
        {
            var type = typeof(TType);

            if (ReflectionHelper.IsInterface(type) || ReflectionHelper.IsAbstract(type))
            {
                return((TType)Substitute.For(new[] { type }, new object[0]));
            }

            return(base.CreateInstance <TType>(context));
        }
コード例 #7
0
        /// <summary>
        /// Creates an instance of <typeparamref name="TType"/>.
        /// </summary>
        /// <typeparam name="TType">The type of instance to create.</typeparam>
        /// <param name="context">The <see cref="AutoGenerateContext"/> instance for the generate request.</param>
        /// <returns>The created instance of <typeparamref name="TType"/>.</returns>
        public override TType CreateInstance <TType>(AutoGenerateContext context)
        {
            var type = typeof(TType);

            if (ReflectionHelper.IsInterface(type) || ReflectionHelper.IsAbstract(type))
            {
                return(A.Fake <TType>());
            }

            return(base.CreateInstance <TType>(context));
        }
コード例 #8
0
 public GenerateMany_Internal()
 {
     _value = _faker.Random.Int();
     _items = new List <int> {
         _value
     };
     _context = new AutoGenerateContext(_faker, _config)
     {
         RuleSets = _ruleSets
     };
 }
コード例 #9
0
        object IAutoGenerator.Generate(AutoGenerateContext context)
        {
            // Note that all instances are converted to object to cater for boxing and struct population
            // When setting a value via reflection on a struct a copy is made
            // This means the changes are applied to a different instance to the one created here
            object instance = context.Binder.CreateInstance <TType>(context);

            // Populate the generated instance
            context.Binder.PopulateInstance <TType>(instance, context);

            return(instance);
        }
コード例 #10
0
ファイル: SetGenerator.cs プロジェクト: wondial/AutoBogus
        object IAutoGenerator.Generate(AutoGenerateContext context)
        {
            var set   = new HashSet <TType>();
            var items = context.GenerateMany <TType>();

            foreach (var item in items)
            {
                set.Add(item);
            }

            return(set);
        }
コード例 #11
0
        public override bool CanOverride(AutoGenerateContext context)
        {
            var isGoingOverride = _objectImplMap.ContainsValue(context.GenerateType);

            if ((context.GenerateType.IsAbstract || context.GenerateType.IsInterface) && !isGoingOverride)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine($"Class {context.GenerateType.Name} hasn't specific implementation, please use AddTypeMap");
                Console.ResetColor();
            }

            return(isGoingOverride);
        }
コード例 #12
0
ファイル: MoqBinder.cs プロジェクト: ryanwersal/AutoBogus
        /// <summary>
        /// Creates an instance of <typeparamref name="TType"/>.
        /// </summary>
        /// <typeparam name="TType">The type of instance to create.</typeparam>
        /// <param name="context">The <see cref="AutoGenerateContext"/> instance for the generate request.</param>
        /// <returns>The created instance of <typeparamref name="TType"/>.</returns>
        public override TType CreateInstance <TType>(AutoGenerateContext context)
        {
            var type = typeof(TType);

            if (ReflectionHelper.IsInterface(type) || ReflectionHelper.IsAbstract(type))
            {
                // Take the cached factory method and make it generic based on the requested type
                // Because this method supports struct and class types, and Moq only supports class types we need to put this 'hack' into place
                var factory = Factory.MakeGenericMethod(type);
                return((TType)factory.Invoke(null, new object[0]));
            }

            return(base.CreateInstance <TType>(context));
        }
コード例 #13
0
        public void PopulateRows(DataTable table, AutoGenerateContext context)
        {
            for (int rowCount = context.Faker.Random.Number(1, 20); rowCount > 0; rowCount--)
            {
                object[] columnValues = new object[table.Columns.Count];

                for (int i = 0; i < table.Columns.Count; i++)
                {
                    columnValues[i] = GenerateColumnValue(table.Columns[i], context);
                }

                table.Rows.Add(columnValues);
            }
        }
コード例 #14
0
            public override object Generate(AutoGenerateContext context)
            {
                var dataSet = (DataSet)Activator.CreateInstance(_dataSetType);

                var allTables       = dataSet.Tables.OfType <DataTable>().ToList();
                var populatedTables = new HashSet <DataTable>();

                while (allTables.Count > 0)
                {
                    bool madeProgress = false;

                    for (int i = 0; i < allTables.Count; i++)
                    {
                        var table = allTables[i];

                        var referencedTables = table.Constraints
                                               .OfType <ForeignKeyConstraint>()
                                               .Select(constraint => constraint.RelatedTable);

                        if (!referencedTables.Where(referencedTable => referencedTable != table).All(populatedTables.Contains))
                        {
                            continue;
                        }

                        if (!DataTableGenerator.TryCreateGenerator(table.GetType(), out var tableGenerator))
                        {
                            throw new Exception($"Couldn't create generator for typed table type {table.GetType()}");
                        }

                        populatedTables.Add(table);

                        context.Instance = table;

                        tableGenerator.PopulateRows(table, context);

                        madeProgress = true;

                        allTables.RemoveAt(i);
                        i--;
                    }

                    if (!madeProgress)
                    {
                        throw new Exception("Couldn't generate data for all tables in data set because there are constraints that can't be satisfied");
                    }
                }

                return(dataSet);
            }
コード例 #15
0
            public override object Generate(AutoGenerateContext context)
            {
                var dataSet = (DataSet)Activator.CreateInstance(_dataSetType);

                foreach (var table in dataSet.Tables.OfType <DataTable>())
                {
                    if (!DataTableGenerator.TryCreateGenerator(table.GetType(), out var tableGenerator))
                    {
                        throw new Exception($"Couldn't create generator for typed table type {table.GetType()}");
                    }

                    tableGenerator.PopulateRows(table, context);
                }

                return(dataSet);
            }
コード例 #16
0
            public override object Generate(AutoGenerateContext context)
            {
                var dataSet = new DataSet();

                if (!DataTableGenerator.TryCreateGenerator(typeof(DataTable), out var tableGenerator))
                {
                    throw new Exception("Internal error: Couldn't create generator for DataTable");
                }

                for (int tableCount = context.Faker.Random.Int(2, 6); tableCount > 0; tableCount--)
                {
                    dataSet.Tables.Add((DataTable)tableGenerator.Generate(context));
                }

                return(dataSet);
            }
コード例 #17
0
            protected override DataTable CreateTable(AutoGenerateContext context)
            {
                var table = new DataTable();

                for (int i = context.Faker.Random.Int(3, 10); i >= 0; i--)
                {
                    table.Columns.Add(
                        new DataColumn()
                    {
                        ColumnName = context.Faker.Database.Column() + i,
                        DataType   = Type.GetType("System." + context.Faker.PickRandom(
                                                      ((TypeCode[])Enum.GetValues(typeof(TypeCode)))
                                                      .Except(new[] { TypeCode.Empty, TypeCode.Object, TypeCode.DBNull })
                                                      .ToArray())),
                    });
                }

                return(table);
            }
コード例 #18
0
                public void Should_Handle_Subclasses(Type listType)
                {
                    // Arrange
                    var config = new AutoConfig();

                    var context = new AutoGenerateContext(config);

                    context.GenerateType = listType;

                    // Act
                    var generator = AutoGeneratorFactory.ResolveGenerator(context);

                    var instance = generator.Generate(context);

                    // Arrange
                    generator.Should().BeOfType <ListGenerator <int> >();

                    instance.Should().BeOfType(listType);
                }
コード例 #19
0
                public void Should_Handle_Subclasses(Type readOnlyDictionaryType)
                {
                    // Arrange
                    var config = new AutoConfig();

                    var context = new AutoGenerateContext(config);

                    context.GenerateType = readOnlyDictionaryType;

                    // Act
                    var generator = AutoGeneratorFactory.ResolveGenerator(context);

                    var instance = generator.Generate(context);

                    // Arrange
                    generator.Should().BeOfType <ReadOnlyDictionaryGenerator <int, string> >();

                    instance.Should().BeOfType(readOnlyDictionaryType);
                }
コード例 #20
0
        object IAutoGenerator.Generate(AutoGenerateContext context)
        {
            var items = new Dictionary <TKey, TValue>();

            // Get a list of keys
            var keys = context.GenerateMany <TKey>();

            foreach (var key in keys)
            {
                // Get a matching value for the current key and add to the dictionary
                var value = context.Generate <TValue>();

                if (value != null)
                {
                    items.Add(key, value);
                }
            }

            return(items);
        }
コード例 #21
0
        object IAutoGenerator.Generate(AutoGenerateContext context)
        {
            IAutoGenerator generator = new DictionaryGenerator <TKey, TValue>();

            Type generateType = context.GenerateType;

            if (ReflectionHelper.IsInterface(generateType))
            {
                generateType = typeof(Dictionary <TKey, TValue>);
            }

            // Generate a standard dictionary and create the read only dictionary
            var items = generator.Generate(context) as IDictionary <TKey, TValue>;

#if NET40
            return(null);
#else
            return(Activator.CreateInstance(generateType, new[] { items }));
#endif
        }
コード例 #22
0
        object IAutoGenerator.Generate(AutoGenerateContext context)
        {
            IList <TType> list;

            try
            {
                list = (IList <TType>)Activator.CreateInstance(context.GenerateType);
            }
            catch
            {
                list = new List <TType>();
            }

            var items = context.GenerateMany <TType>();

            foreach (var item in items)
            {
                list.Add(item);
            }

            return(list);
        }
コード例 #23
0
        object IAutoGenerator.Generate(AutoGenerateContext context)
        {
            ISet <TType> set;

            try
            {
                set = (ISet <TType>)Activator.CreateInstance(context.GenerateType);
            }
            catch
            {
                set = new HashSet <TType>();
            }

            var items = context.GenerateMany <TType>();

            foreach (var item in items)
            {
                set.Add(item);
            }

            return(set);
        }
コード例 #24
0
        object IAutoGenerator.Generate(AutoGenerateContext context)
        {
            var instance = context.Instance;

#if !NETSTANDARD1_3
            // Need to copy the target dictionary to avoid mutations during population
            var target     = instance as IDictionary <string, object>;
            var source     = new Dictionary <string, object>(target);
            var properties = source.Where(pair => pair.Value != null);

            foreach (var property in properties)
            {
                // Configure the context
                var type = property.Value.GetType();

                context.ParentType   = context.GenerateType;
                context.GenerateType = type;
                context.GenerateName = property.Key;

                if (ReflectionHelper.IsExpandoObject(type))
                {
                    context.Instance = property.Value;
                }
                else
                {
                    context.Instance = null;
                }

                // Generate the property values
                var generator = AutoGeneratorFactory.GetGenerator(context);
                target[property.Key] = generator.Generate(context);
            }

            // Reset the instance context
            context.Instance = instance;
#endif

            return(instance);
        }
コード例 #25
0
 public override bool CanOverride(AutoGenerateContext context)
 {
     return(context.GenerateType.IsGenericType &&
            context.GenerateType.GetGenericTypeDefinition() == typeof(Product <>));
 }
コード例 #26
0
 protected override DataTable CreateTable(AutoGenerateContext context)
 => new TTable();
コード例 #27
0
        public void PopulateRows(DataTable table, AutoGenerateContext context)
        {
            bool rowCountIsSpecified = false;

            int rowCount = -1;

            if (context.Config.DataTableRowCount != null)
            {
                rowCountIsSpecified = true;
                rowCount            = context.Config.DataTableRowCount(context);
            }

            if (rowCount < 0)
            {
                rowCount = context.Faker.Random.Number(1, 20);
            }

            var constrainedColumns         = new Dictionary <DataColumn, ConstrainedColumnInformation>();
            var constraintHasUniqueColumns = new HashSet <ForeignKeyConstraint>();
            var referencedRowByConstraint  = new Dictionary <ForeignKeyConstraint, DataRow>();

            foreach (var foreignKey in table.Constraints.OfType <ForeignKeyConstraint>())
            {
                bool containsUniqueColumns = foreignKey.Columns.Any(col =>
                                                                    col.Unique ||
                                                                    table.Constraints.OfType <UniqueConstraint>().Any(constraint => constraint.Columns.Contains(col)));

                for (int i = 0; i < foreignKey.Columns.Length; i++)
                {
                    var column        = foreignKey.Columns[i];
                    var relatedColumn = foreignKey.RelatedColumns[i];

                    if (constrainedColumns.ContainsKey(column))
                    {
                        throw new Exception($"Column is constrained in multiple foreign key relationships simultaneously: {column.ColumnName} in DataTable {table.TableName}");
                    }

                    constrainedColumns[column] =
                        new ConstrainedColumnInformation()
                    {
                        Constraint    = foreignKey,
                        RelatedColumn = relatedColumn,
                    };
                }

                if ((foreignKey.RelatedTable == table) &&
                    foreignKey.Columns.Any(col => !col.AllowDBNull))
                {
                    throw new Exception($"Self-reference columns must be nullable so that at least one record can be added when the table is initially empty: DataTable {table.TableName}");
                }

                if (containsUniqueColumns)
                {
                    constraintHasUniqueColumns.Add(foreignKey);
                }

                // Prepare a slot to be filled per-row.
                referencedRowByConstraint[foreignKey] = default;

                if (containsUniqueColumns &&
                    (foreignKey.RelatedTable != table) &&
                    (foreignKey.RelatedTable.Rows.Count < rowCount))
                {
                    if (rowCountIsSpecified)
                    {
                        string remoteSubject = foreignKey.RelatedTable.TableName;

                        if (string.IsNullOrEmpty(remoteSubject))
                        {
                            remoteSubject = "another DataTable";
                        }

                        throw new ArgumentException($"Unable to satisfy the requested row count of {rowCount} because this table has a foreign key constraint on {remoteSubject} that must be unique, and that table only has {foreignKey.RelatedTable.Rows.Count} row(s).");
                    }

                    rowCount = foreignKey.RelatedTable.Rows.Count;
                }
            }

            var allConstraints = referencedRowByConstraint.Keys.ToList();

            while (rowCount > 0)
            {
                int rowIndex = table.Rows.Count;

                foreach (var foreignKey in allConstraints)
                {
                    referencedRowByConstraint[foreignKey] =
                        constraintHasUniqueColumns.Contains(foreignKey)
            ? foreignKey.RelatedTable.Rows[rowIndex]
            : (foreignKey.RelatedTable.Rows.Count == 0)
              ? null
              : foreignKey.RelatedTable.Rows[context.Faker.Random.Number(0, foreignKey.RelatedTable.Rows.Count - 1)];
                }

                object[] columnValues = new object[table.Columns.Count];

                for (int i = 0; i < table.Columns.Count; i++)
                {
                    if (constrainedColumns.TryGetValue(table.Columns[i], out var constraintInfo))
                    {
                        columnValues[i] = referencedRowByConstraint[constraintInfo.Constraint]?[constraintInfo.RelatedColumn] ?? DBNull.Value;
                    }
                    else
                    {
                        columnValues[i] = GenerateColumnValue(table.Columns[i], context);
                    }
                }

                table.Rows.Add(columnValues);

                rowCount--;
            }
        }
コード例 #28
0
ファイル: DoubleGenerator.cs プロジェクト: wondial/AutoBogus
 object IAutoGenerator.Generate(AutoGenerateContext context)
 {
     return(context.Faker.Random.Double());
 }
コード例 #29
0
 object IAutoGenerator.Generate(AutoGenerateContext context)
 {
     return(context.Faker.Random.UShort());
 }
コード例 #30
0
 public override bool CanOverride(AutoGenerateContext context)
 {
     return(false);
 }