Example #1
0
        public void GeneratedTextIsCorrect(string pattern)
        {
            var sut    = new Fare.Xeger(pattern);
            var result = Enumerable.Range(1, 3).Select(i => sut.Generate()).ToArray();

            Array.ForEach(result, regex => Assert.True(Regex.IsMatch(regex, pattern)));
        }
Example #2
0
        public void GeneratedTextIsCorrect(string pattern)
        {
            // Arrange
            const int repeatCount = 3;

            var randomSeed = Environment.TickCount;

            this._testOutput.WriteLine($"Random seed: {randomSeed}");

            var random = new Random(randomSeed);

            var sut = new Fare.Xeger(pattern, random);

            // Act
            var result = Enumerable.Repeat(0, repeatCount)
                         .Select(_ =>
            {
                var generatedValue = sut.Generate();
                this._testOutput.WriteLine($"Generated value: {generatedValue}");
                return(generatedValue);
            })
                         .ToArray();

            // Assert
            Assert.All(result, regex => Assert.Matches(pattern, regex));
        }
Example #3
0
        public void GeneratedTextIsCorrectCharset(string pattern, string output)
        {
            // Arrange
            const int repeatCount = 3;

            var randomSeed = Environment.TickCount;

            this._testOutput.WriteLine($"Random seed: {randomSeed}");

            var random = new Random(randomSeed);

            var sut = new Fare.Xeger(pattern, random);

            // Act
            Tuple <string, string>[] result = Enumerable.Repeat(0, repeatCount)
                                              .Select(_ =>
            {
                var generatedValue0 = sut.Generate();
                var generatedValue1 = sut.UsedAlphabet;
                this._testOutput.WriteLine($"charset value: {generatedValue1}");
                return(new Tuple <string, string>(generatedValue0, generatedValue1));
            })
                                              .ToArray();

            // Assert
            Assert.All(result, regex => Assert.True(output == null || regex.Item2 == new string(output.Cast <char>().Distinct().OrderBy(x => x).ToArray())));
        }
Example #4
0
        public void GeneratedTextIsCorrect(string pattern)
        {
            const int repeatCount = 3;
            var       sut         = new Fare.Xeger(pattern);

            var result = Enumerable.Repeat(0, repeatCount).Select(_ => sut.Generate()).ToArray();

            Assert.All(result, regex => Assert.Matches(pattern, regex));
        }
Example #5
0
        private void Restriction(XElement element, Historico historico)
        {
            if (!gerarComentarios)
            {
                return;                    // tudo que é gerado pelas restrições são comentários, se não quer gerar, então nem precisa processar...
            }
            var enumeration = element.Descendants().FirstOrDefault(d => d.Name.LocalName == "enumeration");

            if (enumeration != null)
            {
                historico.elemento.Add(new XComment("Exemplo: " + enumeration.Attribute("value")?.Value));
            }
            var pattern = element.Descendants().FirstOrDefault(d => d.Name.LocalName == "pattern");

            if (pattern != null)
            {
                var regex = pattern.Attribute("value")?.Value;
                try
                {
                    bool   temCaractereEspecial = true;
                    string exemplo = "";
                    for (int i = 0; i < 10 && temCaractereEspecial; i++)
                    {
                        exemplo = new Fare.Xeger(regex).Generate();
                        temCaractereEspecial = false;
                        for (int j = 0; j < exemplo.Length; j++)
                        {
                            if (exemplo[j] < 32)
                            {
                                temCaractereEspecial = true;
                                break;
                            }
                        }
                    }
                    historico.elemento.Add(new XComment("Exemplo: " + exemplo));
                }
                catch
                {
                    historico.elemento.Add(new XComment("Pattern: " + regex));
                }
            }
            var minLength = element.Descendants().FirstOrDefault(d => d.Name.LocalName == "minLength")?.Attribute("value")?.Value;
            var maxLength = element.Descendants().FirstOrDefault(d => d.Name.LocalName == "maxLength")?.Attribute("value")?.Value;

            if (!string.IsNullOrEmpty(minLength) || !string.IsNullOrEmpty(maxLength))
            {
                historico.elemento.Add(new XComment(string.Format("Tamanho: de {0} a {1} caracteres", minLength ?? "0", maxLength ?? "infinitos")));
            }
            var atributoBase = element.Attribute("base")?.Value;

            if (!string.IsNullOrEmpty(atributoBase))
            {
                //restricoesDesconhecidas.Add(historico.elemento, atributoBase);
                historico.elemento.Add(new XAttribute("RestricaoDesconhecidaNaoIdentificadoEmNenhumaAnalise", atributoBase));
            }
        }
Example #6
0
        static void Main(string[] args)
        {
            var data = new Fare.Xeger(ConfigurationManager.AppSettings["pattern"]);

            var tick = TimeSpan.Parse(ConfigurationManager.AppSettings["timespan"]);

            var observable = Observable
                .Timer(TimeSpan.Zero, tick)
                .Select(t => data.Generate());

            new ConsoleSink().Subscribe(observable);
            new FileSink("data.txt").Subscribe(observable);

            Console.ReadLine();
        }
Example #7
0
        static void Main(string[] args)
        {
            var data = new Fare.Xeger(ConfigurationManager.AppSettings["pattern"]);

            var tick = TimeSpan.Parse(ConfigurationManager.AppSettings["timespan"]);

            var observable = Observable
                             .Timer(TimeSpan.Zero, tick)
                             .Select(t => data.Generate());

            new ConsoleSink().Subscribe(observable);
            new FileSink("data.txt").Subscribe(observable);

            Console.ReadLine();
        }
        protected virtual string TransformPattern(string pattern, ScenarioContext context)
        {
            // supports [[key=value]] assignment
            var isAssignment = Regex.Match(pattern, @"(.*)=(.*)");

            if (isAssignment.Success)
            {
                // bottom up travese
                var cxtValue = TransformText(isAssignment.Groups[2].Value.Trim(), context);

                // apply user filter
                foreach (var t in _additonalTransformers)
                {
                    cxtValue = t.Invoke(cxtValue);
                }

                // apply RegEx
                var regExM = Regex.Match(cxtValue, @"RegEx\((.*)\)", RegexOptions.IgnoreCase);
                if (regExM.Success)
                {
                    cxtValue = new Fare.Xeger(regExM.Groups[1].Value).Generate();
                }

                var cxtKey = TransformText(isAssignment.Groups[1].Value.Trim(), context);
                context[cxtKey] = cxtValue;

                Console.WriteLine(string.Format("[[{0}={1}]]", cxtKey, cxtValue));
                return(cxtValue);
            }
            else
            {
                // read value from context
                try
                {
                    var cxtValue = context[pattern] as string;
                    Console.WriteLine(string.Format("[[{0}={1}]]", pattern, cxtValue));
                    return(cxtValue);
                }
                catch (KeyNotFoundException)
                {
                    throw new KeyNotFoundException("can't find key:" + pattern + " in scenario context");
                }
            }
        }
Example #9
0
        // Uses Xeger to generate multiple values which should match the regex pattern
        private string[] GenerateTextOfPattern(string pattern, int repeatCount)
        {
            var randomSeed = Environment.TickCount;

            this._testOutput.WriteLine($"Random seed: {randomSeed}");

            var random = new Random(randomSeed);

            var sut = new Fare.Xeger(pattern, random);

            // Act
            var result = Enumerable.Repeat(0, repeatCount)
                         .Select(_ =>
            {
                var generatedValue = sut.Generate();
                this._testOutput.WriteLine($"Generated value {generatedValue} for {pattern}");
                return(generatedValue);
            })
                         .ToArray();

            return(result);
        }
Example #10
0
        bool Collide(string regex1, string regex2)
        {
            var regexStriped1 = StripNameGroups(regex1);
            var regexStriped2 = StripNameGroups(regex2);

            var automaton1 = new Fare.RegExp(regexStriped1).ToAutomaton();
            var automaton2 = new Fare.RegExp(regexStriped2).ToAutomaton();

            var intersection = automaton1.Intersection(automaton2);

            var random1 = new Random(Environment.TickCount);
            var sut1    = new Fare.Xeger(regexStriped1, random1);

            var random2 = new Random(Environment.TickCount);
            var sut2    = new Fare.Xeger(regexStriped2, random2);

            var gen1 = sut1.Generate();
            var gen2 = sut2.Generate();

            var result1 = intersection.Run(gen1);
            var result2 = intersection.Run(gen2);

            return(result1 || result2);
        }
Example #11
0
        /// <summary>
        /// Creates the template.
        /// </summary>
        /// <param name="objectType">Type of the object.</param>
        /// <returns>The template.</returns>
        protected object CreateTemplate(Type objectType)
        {
            if (objectType == null || ExcludeTypes.Contains(objectType))
            {
                return(null);
            }
            if (objectType == typeof(string))
            {
                return("abc");
            }
            if (objectType == typeof(bool))
            {
                return(false);
            }
            if (objectType == typeof(short) || objectType == typeof(int) || objectType == typeof(long) ||
                objectType == typeof(double) || objectType == typeof(float) || objectType == typeof(decimal))
            {
                return(Convert.ChangeType(1, objectType));
            }
            if (objectType == typeof(DateTime))
            {
                return(DefaultDateTime);
            }
            if (objectType == typeof(DateTimeOffset))
            {
                return(DefaultDateTimeOffset);
            }
            if (objectType == typeof(Timestamp))
            {
                return(new Timestamp(DefaultDateTimeOffset));
            }
            if (objectType.IsEnum)
            {
                return(Enum.GetValues(objectType).GetValue(0));
            }
            if (objectType.IsGenericType)
            {
                var genericType = objectType.GetGenericTypeDefinition();

                if (genericType == typeof(Nullable <>))
                {
                    return(Activator.CreateInstance(objectType, CreateTemplate(Nullable.GetUnderlyingType(objectType))));
                }
                if (genericType == typeof(List <>))
                {
                    var childType = objectType.GetGenericArguments()[0];
                    var list      = Activator.CreateInstance(objectType) as IList;
                    list?.Add(CreateTemplate(childType));
                    return(list);
                }
            }
            if (objectType.IsAbstract)
            {
                var concreteType = objectType.Assembly.GetTypes()
                                   .FirstOrDefault(x => !x.IsAbstract && objectType.IsAssignableFrom(x));

                return(CreateTemplate(concreteType));
            }

            var dataObject = Activator.CreateInstance(objectType);

            foreach (var property in objectType.GetProperties())
            {
                try
                {
                    if (property.CanWrite && !IsIgnored(property))
                    {
                        var regex = property.GetCustomAttribute <RegularExpressionAttribute>();

                        if (property.PropertyType == typeof(string) && regex != null && !UidPattern.Equals(regex.Pattern))
                        {
                            var attribute = property.GetCustomAttribute <RegularExpressionAttribute>();
                            var xeger     = new Fare.Xeger(attribute.Pattern);
                            property.SetValue(dataObject, xeger.Generate());
                            continue;
                        }

                        property.SetValue(dataObject, CreateTemplate(property.PropertyType));
                    }
                }
                catch
                {
                    _log.WarnFormat("Error setting property value. Type: {0}; Property: {1}", objectType.FullName, property.Name);
                }
            }

            return(dataObject);
        }
Example #12
0
 public void GeneratedTextIsCorrect(string pattern)
 {
     var sut = new Fare.Xeger(pattern);
     var result = Enumerable.Range(1, 3).Select(i => sut.Generate()).ToArray();
     Array.ForEach(result, regex => Assert.True(Regex.IsMatch(regex, pattern)));
 }