Пример #1
0
        public Object.AdGroup AddAdGroupForInit(RandomData randomData)
        {
            UIMaps.AdGroupsClasses.AdGroups adversiementUI = testBase.Get<UIMaps.AdGroupsClasses.AdGroups>();
            adversiementUI.ClickAddAdGroupButton();

            Common.UITestFramework.UIMaps.DetailedInfoForUploadClasses.DetailedInfoForUpload uploadWindow = testBase.Get<Common.UITestFramework.UIMaps.DetailedInfoForUploadClasses.DetailedInfoForUpload>();
            string adGroupName = Object.AdGroup.NextAdName(randomData);
            return AddAdGroup(adGroupName, uploadWindow.VerifyUploadOneAdCenterAdvertisement);
        }
Пример #2
0
 public static Keyword NextKeyword(RandomData random)
 {
     Keyword keyword = new Keyword
     {
         Keywords = random.NextEnglishWordLowercase(10),
         DesURL = "http://www." + random.NextEnglishWordLowercase(10) + ".com",
     };
     return keyword;
 }
Пример #3
0
 public static TextAdvertisement NextTextAd(RandomData random)
 {
     TextAdvertisement textAd = new TextAdvertisement
     {
         Title = random.NextEnglishWordsLowercase(5, 4),
         Text = random.NextEnglishWordsLowercase(5, 10),
         DisplayUrl = "www." + random.NextEnglishWordLowercase(10) + ".com",
         DestinationUrl = "http://www." + random.NextEnglishWordLowercase(10, 15) + ".com",
     };
     return textAd;
 }
Пример #4
0
        public GoogleFramework.Object.AdGroup AddAdGroupForInit(RandomData random)
        {
            GoogleUIMaps.AdvertisementClasses.AdGroup adversiementUI = testBase.Get<GoogleUIMaps.AdvertisementClasses.AdGroup>();
            adversiementUI.ClickAddAdGroupButton();

            CommonUIMaps.DetailedInfoForUploadClasses.DetailedInfoForUpload uploadWindow = testBase.Get<CommonUIMaps.DetailedInfoForUploadClasses.DetailedInfoForUpload>();

            return AddAdGroup(
                GoogleFramework.Object.AdGroup.NextAdName(random),
                "10.00",
                uploadWindow.VerifyUploadOneGoogleAdvertisement);
        }
Пример #5
0
 public static TextAdvertisement NextTextAd(RandomData random)
 {
     TextAdvertisement textAd = new TextAdvertisement
     {
         Headline = random.NextEnglishWordLowercase(25),
         DescriptionLine1 = random.NextEnglishWordLowercase(35),
         DescriptionLine2 = random.NextEnglishWordLowercase(35),
         DisplayUrl = "www." + random.NextEnglishWordLowercase(10) + ".com",
         DestinationUrl = "www." + random.NextEnglishWordLowercase(10) + ".com",
     };
     return textAd;
 }
Пример #6
0
 public static Campaign NextCampaign(RandomData randomData)
 {
     Facebook.UITestFramework.Object.Campaign addCampaign = new Object.Campaign
     {
         Name = "CampaignForAFPBVT_" + randomData.NextAsciiWord(2, 3),
         RunStatus = "Active",
         Budget = "1.00",
         BudgetType = "Daily",
         StartTime = DateTime.UtcNow.ToString(),
         StopTime = "0",
     };
     return addCampaign;
 }
Пример #7
0
 public static Advertisement NextExternalAdvertisement(RandomData randomData)
 {
     return new Facebook.UITestFramework.Object.Advertisement
     {
         AdName = "Automation_" + randomData.NextAsciiWord(2, 3),
         AdStatus = AdStatus.Scheduled,
         AdType = AdType.External_URL,
         BidType = BidType.CPC,
         MaxBid = 0.01,
         DestinationUrl = new Uri("http://www.ad-sage.com"),
         Title = "Manage your ads?",
         Body = "Get the latest updates on adSage for Facebook's powerful ad manager. Click like now!",
         SuggestedBid = new SuggestedBid(),
     };
 }
        public void DefaultIfNullOrEmptyTest()
        {
            string testValue = null;

            Assert.IsTrue(testValue.DefaultIfNullOrEmpty(RandomData.GenerateWord(5)).Length == 5);
        }
        public void TrimTest()
        {
            var testValue = RandomData.GenerateWord(25) + "   ";

            Assert.IsTrue(testValue.ToTrimmed().Length == 25);
        }
        public void StartsWithOrdinalTest()
        {
            var testValue = RandomData.GenerateWord(10);

            Assert.IsTrue(testValue.StartsWithOrdinal(testValue));
        }
        public void IsNotEmptyTest()
        {
            Assert.IsTrue(RandomData.GenerateWord(10).IsNotEmpty());

            Assert.IsFalse(string.Empty.IsNotEmpty());
        }
Пример #12
0
        public static PersistentEvent GenerateEvent(string[] organizationIds = null, string[] projectIds = null, string[] stackIds = null, DateTimeOffset?startDate = null, DateTimeOffset?endDate = null, DateTimeOffset?occurrenceDate = null, int maxErrorNestingLevel = 0, bool generateTags = true, bool generateData = true, bool isFixed = false, bool isHidden = false, string[] referenceIds = null, string type = null, string sessionId = null, string userIdentity = null, decimal?value = -1, string semver = null)
        {
            if (!startDate.HasValue || startDate > SystemClock.OffsetNow.AddHours(1))
            {
                startDate = SystemClock.OffsetNow.AddDays(-30);
            }
            if (!endDate.HasValue || endDate > SystemClock.OffsetNow.AddHours(1))
            {
                endDate = SystemClock.OffsetNow;
            }

            var ev = new PersistentEvent {
                OrganizationId = organizationIds.Random(TestConstants.OrganizationId),
                ProjectId      = projectIds.Random(TestConstants.ProjectId),
                ReferenceId    = referenceIds.Random(),
                Date           = occurrenceDate ?? RandomData.GetDateTimeOffset(startDate, endDate),
                Value          = value.GetValueOrDefault() >= 0 ? value : RandomData.GetDecimal(0, Int32.MaxValue),
                IsFixed        = isFixed,
                IsHidden       = isHidden,
                StackId        = stackIds.Random()
            };

            if (!String.IsNullOrEmpty(userIdentity))
            {
                ev.SetUserIdentity(userIdentity);
            }

            if (generateData)
            {
                for (int i = 0; i < RandomData.GetInt(1, 5); i++)
                {
                    string key = RandomData.GetWord();
                    while (ev.Data.ContainsKey(key) || key == Event.KnownDataKeys.Error)
                    {
                        key = RandomData.GetWord();
                    }

                    ev.Data.Add(key, RandomData.GetWord());
                }
            }

            if (generateTags)
            {
                for (int i = 0; i < RandomData.GetInt(1, 3); i++)
                {
                    string tag = TestConstants.EventTags.Random();
                    if (!ev.Tags.Contains(tag))
                    {
                        ev.Tags.Add(tag);
                    }
                }
            }

            if (String.IsNullOrEmpty(type) || String.Equals(type, Event.KnownTypes.Error, StringComparison.OrdinalIgnoreCase))
            {
                ev.Type = Event.KnownTypes.Error;

                // limit error variation so that stacking will occur
                if (_randomErrors == null)
                {
                    _randomErrors = new List <Error>(Enumerable.Range(1, 25).Select(i => GenerateError(maxErrorNestingLevel)));
                }

                ev.Data[Event.KnownDataKeys.Error] = _randomErrors.Random();
            }
            else
            {
                ev.Type = type.ToLower();
            }

            if (!String.IsNullOrEmpty(sessionId))
            {
                ev.SetSessionId(sessionId);
            }

            if (ev.IsSessionStart())
            {
                ev.Value = null;
            }

            ev.SetVersion(semver);
            return(ev);
        }
Пример #13
0
 public static Advertisement NextPagePostStoryAdvertisement(RandomData randomData)
 {
     return nextPagePostAdvertisement(randomData, AdType.Page_Post_Story);
 }
Пример #14
0
        public AdCenter.UITestFramework.Object.Campaign AddCampaignForInit(RandomData random)
        {
            AdCenter.UITestFramework.UIMaps.CampaignsClasses.Campaigns campaignUI = testBase.Get<UIMaps.CampaignsClasses.Campaigns>();
            campaignUI.ClickAddCampaignButton();
            string campaignName = AdCenter.UITestFramework.Object.Campaign.NextCampaignName(random);

            Common.UITestFramework.UIMaps.DetailedInfoForUploadClasses.DetailedInfoForUpload uploadWindow = testBase.Get<Common.UITestFramework.UIMaps.DetailedInfoForUploadClasses.DetailedInfoForUpload>();
            return AddCampaign(campaignName, uploadWindow.VerifyUploadOneAdCenterCampaign);
        }
Пример #15
0
        public static void Main(string[] args)
        {
            Console.CursorVisible = false;
            StartDisplayingLogMessages();

            ExceptionlessClient.Default.Configuration.UpdateSettingsWhenIdleInterval = TimeSpan.FromSeconds(15);
            ExceptionlessClient.Default.Configuration.UseTraceLogEntriesPlugin();
            ExceptionlessClient.Default.Configuration.AddPlugin <SystemUptimePlugin>();
            ExceptionlessClient.Default.Configuration.UseFolderStorage("store");
            ExceptionlessClient.Default.Configuration.UseLogger(_log);
            //ExceptionlessClient.Default.Configuration.SubmissionBatchSize = 1;
            ExceptionlessClient.Default.Register();

            // test NLog
            GlobalDiagnosticsContext.Set("GlobalProp", "GlobalValue");
            //Log.Info().Message("Hi").Tag("Tag1", "Tag2").Property("LocalProp", "LocalValue").MarkUnhandled("SomeMethod").ContextProperty("Blah", new Event()).Write();

            //ExceptionlessClient.Default.SubmitLog(typeof(Program).Name, "Trace Message", LogLevel.Trace);

            // test log4net
            XmlConfigurator.Configure();
            GlobalContext.Properties["GlobalProp"] = "GlobalValue";
            ThreadContext.Properties["LocalProp"]  = "LocalValue";
            //_log4net.Info("Hi");

            var tokenSource         = new CancellationTokenSource();
            CancellationToken token = tokenSource.Token;

            ExceptionlessClient.Default.Configuration.AddPlugin(ctx => ctx.Event.Data[RandomData.GetWord()] = RandomData.GetWord());
            ExceptionlessClient.Default.Configuration.AddPlugin(ctx => ctx.Event.Data[RandomData.GetWord()] = RandomData.GetWord());
            ExceptionlessClient.Default.Configuration.AddPlugin(ctx => {
                // use server settings to see if we should include this data
                if (ctx.Client.Configuration.Settings.GetBoolean("IncludeConditionalData", true))
                {
                    ctx.Event.AddObject(new {
                        Total     = 32.34,
                        ItemCount = 2,
                        Email     = "*****@*****.**"
                    }, "ConditionalData");
                }
            });
            ExceptionlessClient.Default.Configuration.Settings.Changed += (sender, changedArgs) => Trace.WriteLine($"Action: {changedArgs.Action} Key: {changedArgs.Item.Key} Value: {changedArgs.Item.Value}");

            WriteOptionsMenu();

            while (true)
            {
                Console.SetCursorPosition(0, OPTIONS_MENU_LINE_COUNT + 1);
                ConsoleKeyInfo keyInfo = Console.ReadKey(true);

                if (keyInfo.Key == ConsoleKey.D1)
                {
                    SendEvent();
                }
                else if (keyInfo.Key == ConsoleKey.D2)
                {
                    SendContinuousEvents(50, token, 100);
                }
                else if (keyInfo.Key == ConsoleKey.D3)
                {
                    SendContinuousEvents(_delays[_delayIndex], token);
                }
                else if (keyInfo.Key == ConsoleKey.D4)
                {
                    ExceptionlessClient.Default.SubmitSessionStart();
                }
                else if (keyInfo.Key == ConsoleKey.D5)
                {
                    ExceptionlessClient.Default.Configuration.UseSessions(false, null, true);
                    ExceptionlessClient.Default.SubmitSessionStart();
                }
                else if (keyInfo.Key == ConsoleKey.D6)
                {
                    SendContinuousEvents(250, token, ev: new Event {
                        Type    = Event.KnownTypes.Log,
                        Source  = "SampleConsole.Program.Main",
                        Message = "Sample console application event"
                    });
                }
                else if (keyInfo.Key == ConsoleKey.D7)
                {
                    ExceptionlessClient.Default.SubmitSessionEnd();
                }
                else if (keyInfo.Key == ConsoleKey.D8)
                {
                    ExceptionlessClient.Default.Configuration.SetUserIdentity(Guid.NewGuid().ToString("N"));
                }
                else if (keyInfo.Key == ConsoleKey.P)
                {
                    Console.SetCursorPosition(0, OPTIONS_MENU_LINE_COUNT + 2);
                    Console.WriteLine("Telling client to process the queue...");

                    ExceptionlessClient.Default.ProcessQueue();

                    ClearOutputLines();
                }
                else if (keyInfo.Key == ConsoleKey.F)
                {
                    SendAllCapturedEventsFromDisk();
                    ClearOutputLines();
                }
                else if (keyInfo.Key == ConsoleKey.D)
                {
                    _dateSpanIndex++;
                    if (_dateSpanIndex == _dateSpans.Length)
                    {
                        _dateSpanIndex = 0;
                    }
                    WriteOptionsMenu();
                }
                else if (keyInfo.Key == ConsoleKey.T)
                {
                    _delayIndex++;
                    if (_delayIndex == _delays.Length)
                    {
                        _delayIndex = 0;
                    }
                    WriteOptionsMenu();
                }
                else if (keyInfo.Key == ConsoleKey.Q)
                {
                    break;
                }
                else if (keyInfo.Key == ConsoleKey.S)
                {
                    tokenSource.Cancel();
                    tokenSource = new CancellationTokenSource();
                    token       = tokenSource.Token;
                    ClearOutputLines();
                }
            }
        }
Пример #16
0
 public void PrepareSut()
 {
     _utcTime          = RandomData.GetDateTime();
     SystemTime.UtcNow = () => _utcTime;
     _sut = new WeightEntry();
 }
Пример #17
0
        private static void Main()
        {
            Console.CursorVisible = false;
            StartDisplayingLogMessages();

            ExceptionlessClient.Default.Configuration.UseTraceLogEntriesPlugin();
            ExceptionlessClient.Default.Configuration.AddPlugin <SystemUptimePlugin>();
            ExceptionlessClient.Default.Configuration.UseFolderStorage("store");
            ExceptionlessClient.Default.Configuration.UseLogger(_log);
            //ExceptionlessClient.Default.Configuration.SubmissionBatchSize = 1;
            ExceptionlessClient.Default.Register();

            // test NLog
            GlobalDiagnosticsContext.Set("GlobalProp", "GlobalValue");
            Log.Info().Message("Hi").Tag("Tag1", "Tag2").Property("LocalProp", "LocalValue").MarkUnhandled("SomeMethod").ContextProperty("Blah", new Event()).Write();

            // test log4net
            XmlConfigurator.Configure();
            GlobalContext.Properties["GlobalProp"] = "GlobalValue";
            ThreadContext.Properties["LocalProp"]  = "LocalValue";
            _log4net.Info("Hi");

            var tokenSource         = new CancellationTokenSource();
            CancellationToken token = tokenSource.Token;

            if (false)
            {
                SampleApiUsages();
            }


            ExceptionlessClient.Default.Configuration.AddPlugin(ctx => ctx.Event.Data[RandomData.GetWord()] = RandomData.GetWord());
            ExceptionlessClient.Default.Configuration.AddPlugin(ctx => ctx.Event.Data[RandomData.GetWord()] = RandomData.GetWord());
            ExceptionlessClient.Default.Configuration.AddPlugin(ctx => {
                // use server settings to see if we should include this data
                if (ctx.Client.Configuration.Settings.GetBoolean("IncludeConditionalData", true))
                {
                    ctx.Event.AddObject(new { Total = 32.34, ItemCount = 2, Email = "*****@*****.**" }, "ConditionalData");
                }
            });
            ExceptionlessClient.Default.Configuration.Settings.Changed += (sender, args) => Trace.WriteLine(String.Format("Action: {0} Key: {1} Value: {2}", args.Action, args.Item.Key, args.Item.Value));

            WriteOptionsMenu();

            while (true)
            {
                Console.SetCursorPosition(0, OPTIONS_MENU_LINE_COUNT + 1);
                ConsoleKeyInfo keyInfo = Console.ReadKey(true);

                if (keyInfo.Key == ConsoleKey.D1)
                {
                    SendEvent();
                }
                else if (keyInfo.Key == ConsoleKey.D2)
                {
                    SendContinuousEvents(50, token, 100);
                }
                else if (keyInfo.Key == ConsoleKey.D3)
                {
                    SendContinuousEvents(_delays[_delayIndex], token);
                }
                else if (keyInfo.Key == ConsoleKey.D4)
                {
                    Console.SetCursorPosition(0, OPTIONS_MENU_LINE_COUNT + 2);
                    Console.WriteLine("Telling client to process the queue...");

                    ExceptionlessClient.Default.ProcessQueue();

                    ClearOutputLines();
                }
                else if (keyInfo.Key == ConsoleKey.D5)
                {
                    SendAllCapturedEventsFromDisk();
                    ClearOutputLines();
                }
                else if (keyInfo.Key == ConsoleKey.D)
                {
                    _dateSpanIndex++;
                    if (_dateSpanIndex == _dateSpans.Length)
                    {
                        _dateSpanIndex = 0;
                    }
                    WriteOptionsMenu();
                }
                else if (keyInfo.Key == ConsoleKey.T)
                {
                    _delayIndex++;
                    if (_delayIndex == _delays.Length)
                    {
                        _delayIndex = 0;
                    }
                    WriteOptionsMenu();
                }
                else if (keyInfo.Key == ConsoleKey.Q)
                {
                    break;
                }
                else if (keyInfo.Key == ConsoleKey.S)
                {
                    tokenSource.Cancel();
                    tokenSource = new CancellationTokenSource();
                    token       = tokenSource.Token;
                    ClearOutputLines();
                }
            }
        }
Пример #18
0
        public static void Main(string[] args)
        {
            Console.CursorVisible = false;
            if (!Console.IsInputRedirected)
            {
                StartDisplayingLogMessages();
            }

            ExceptionlessClient.Default.Configuration.AddPlugin <SystemUptimePlugin>();
            ExceptionlessClient.Default.Configuration.UseFolderStorage("store");
            ExceptionlessClient.Default.Configuration.UseLogger(_log);
            ExceptionlessClient.Default.Startup();

            if (ExceptionlessClient.Default.Configuration.Settings.GetBoolean("EnableWelcomeMessage", false))
            {
                Console.WriteLine($"Hello {Environment.MachineName}!");
            }

            // Test NLog
            var config = new LoggingConfiguration();
            var exceptionlessTarget = new ExceptionlessTarget();

            config.AddTarget("exceptionless", exceptionlessTarget);
            config.LoggingRules.Add(new LoggingRule("*", global::NLog.LogLevel.Debug, exceptionlessTarget));
            LogManager.Configuration = config;

            var logger = LogManager.GetCurrentClassLogger();

            logger.Warn()
            .Message("App Starting...")
            .Tag("Tag1", "Tag2")
            .Property("LocalProp", "LocalValue")
            .Property("Order", new { Total = 15 })
            .Write();

            // This is how you could log the same message using the fluent api directly.
            //ExceptionlessClient.Default.CreateLog(typeof(Program).Name, "App Starting...", LogLevel.Info)
            //    .AddTags("Tag1", "Tag2")
            //    .SetProperty("LocalProp", "LocalValue")
            //    .SetProperty("Order", new { Total = 15 })
            //    .Submit();
#if NET45
            // Test log4net
            XmlConfigurator.Configure();
            GlobalContext.Properties["GlobalProp"] = "GlobalValue";
            ThreadContext.Properties["LocalProp"]  = "LocalValue";
            //_log4net.Info("Hi");
#endif

            var tokenSource         = new CancellationTokenSource();
            CancellationToken token = tokenSource.Token;

            ExceptionlessClient.Default.Configuration.AddPlugin(ctx => ctx.Event.Data[RandomData.GetWord()] = RandomData.GetWord());
            ExceptionlessClient.Default.Configuration.AddPlugin(ctx => {
                // use server settings to see if we should include this data
                if (ctx.Client.Configuration.Settings.GetBoolean("IncludeConditionalData", true))
                {
                    ctx.Event.AddObject(new { Total = 32.34, ItemCount = 2, Email = "*****@*****.**" }, "ConditionalData");
                }
            });
            ExceptionlessClient.Default.Configuration.Settings.Changed += (sender, changedArgs) => Trace.WriteLine($"Action: {changedArgs.Action} Key: {changedArgs.Item.Key} Value: {changedArgs.Item.Value}");

            WriteOptionsMenu();

            while (true)
            {
                Console.SetCursorPosition(0, OPTIONS_MENU_LINE_COUNT + 1);
                var keyInfo = Console.IsInputRedirected ? GetKeyFromRedirectedConsole() : Console.ReadKey(true);

                if (keyInfo.Key == ConsoleKey.D1)
                {
                    SendEvent();
                }
                else if (keyInfo.Key == ConsoleKey.D2)
                {
                    SendContinuousEvents(50, token, 100);
                }
                else if (keyInfo.Key == ConsoleKey.D3)
                {
                    SendContinuousEvents(_delays[_delayIndex], token);
                }
                else if (keyInfo.Key == ConsoleKey.D4)
                {
                    ExceptionlessClient.Default.SubmitSessionStart();
                }
                else if (keyInfo.Key == ConsoleKey.D5)
                {
                    ExceptionlessClient.Default.Configuration.UseSessions(false, null, true);
                    ExceptionlessClient.Default.SubmitSessionStart();
                }
                else if (keyInfo.Key == ConsoleKey.D6)
                {
                    SendContinuousEvents(250, token, ev: new Event {
                        Type = Event.KnownTypes.Log, Source = "SampleConsole.Program.Main", Message = "Sample console application event"
                    });
                }
                else if (keyInfo.Key == ConsoleKey.D7)
                {
                    ExceptionlessClient.Default.SubmitSessionEnd();
                }
                else if (keyInfo.Key == ConsoleKey.D8)
                {
                    ExceptionlessClient.Default.Configuration.SetUserIdentity(Guid.NewGuid().ToString("N"));
                }
                else if (keyInfo.Key == ConsoleKey.P)
                {
                    Console.SetCursorPosition(0, OPTIONS_MENU_LINE_COUNT + 2);
                    Console.WriteLine("Telling client to process the queue...");

                    ExceptionlessClient.Default.ProcessQueue();

                    ClearOutputLines();
                }
                else if (keyInfo.Key == ConsoleKey.F)
                {
                    SendAllCapturedEventsFromDisk();
                    ClearOutputLines();
                }
                else if (keyInfo.Key == ConsoleKey.D)
                {
                    _dateSpanIndex++;
                    if (_dateSpanIndex == _dateSpans.Length)
                    {
                        _dateSpanIndex = 0;
                    }
                    WriteOptionsMenu();
                }
                else if (keyInfo.Key == ConsoleKey.T)
                {
                    _delayIndex++;
                    if (_delayIndex == _delays.Length)
                    {
                        _delayIndex = 0;
                    }
                    WriteOptionsMenu();
                }
                else if (keyInfo.Key == ConsoleKey.Q)
                {
                    break;
                }
                else if (keyInfo.Key == ConsoleKey.S)
                {
                    tokenSource.Cancel();
                    tokenSource = new CancellationTokenSource();
                    token       = tokenSource.Token;
                    ClearOutputLines();
                }
            }
        }
        public void EqualsOrBothNullOrEmpty()
        {
            var result = RandomData.GenerateWord(10).EqualsOrBothNullOrEmpty(RandomData.GenerateWord(5));

            base.Consumer.Consume(result);
        }
        public void EqualsIgnoreCase()
        {
            var result = RandomData.GenerateWord(10).EqualsIgnoreCase(RandomData.GenerateWord(5));

            base.Consumer.Consume(result);
        }
Пример #21
0
        private async Task SendEventNoticeAsync(PersistentEvent ev)
        {
            ev.Id             = TestConstants.EventId;
            ev.OrganizationId = TestConstants.OrganizationId;
            ev.ProjectId      = TestConstants.ProjectId;
            ev.StackId        = TestConstants.StackId;
            ev.Date           = SystemClock.OffsetUtcNow;

            await _slackService.SendEventNoticeAsync(ev, _project, RandomData.GetBool(), RandomData.GetBool(), 1);

            await RunWebHookJobAsync();
        }
Пример #22
0
        public Object.TextAdvertisement AddTextAdforInit(RandomData randomData)
        {
            AdCenter.UITestFramework.UIMaps.TextAdClasses.TextAd textAdUI = testBase.Get<UITestFramework.UIMaps.TextAdClasses.TextAd>();
            textAdUI.ClickAddTextAdButton();

            AdCenter.UITestFramework.Object.TextAdvertisement textAdObject = AdCenter.UITestFramework.Object.TextAdvertisement.NextTextAd(randomData);

            CommonUIMaps.DetailedInfoForUploadClasses.DetailedInfoForUpload uploadWindow = testBase.Get<CommonUIMaps.DetailedInfoForUploadClasses.DetailedInfoForUpload>();
            return AddTextAd(textAdObject, uploadWindow.VerifyUploadOneAdCenterTextAd);
        }
Пример #23
0
        public static User GenerateUser(bool generateId = false, string id = null, string organizationId = null, string emailAddress = null, IEnumerable <string> roles = null)
        {
            var user = new User {
                Id                 = id.IsNullOrEmpty() ? generateId ? ObjectId.GenerateNewId().ToString() : TestConstants.UserId : id,
                EmailAddress       = emailAddress.IsNullOrEmpty() ? String.Concat(RandomData.GetWord(false), "@", RandomData.GetWord(false), ".com") : emailAddress,
                Password           = TestConstants.UserPassword,
                FullName           = "Eric Smith",
                PasswordResetToken = Guid.NewGuid().ToString()
            };

            user.OrganizationIds.Add(organizationId.IsNullOrEmpty() ? TestConstants.OrganizationId : organizationId);

            if (roles != null)
            {
                user.Roles.AddRange(roles);
            }

            return(user);
        }
Пример #24
0
 private static Advertisement nextPageSponsorStoryAdvertisement(RandomData randomData, AdType type)
 {
     Advertisement ad=nextSponsorStoryAdvertisement(randomData, type);
     ad.Title = ConfigurationManager.AppSettings.Get("PageName");
     return ad;
 }
        public override void Setup()
        {
            base.Setup();

            this._crlfString = RandomData.GenerateWord(10) + ControlChars.CRLF + RandomData.GenerateWord(10) + ControlChars.CRLF + RandomData.GenerateWord(10) + ControlChars.CRLF;

            this._gzipString   = RandomData.GenerateWord(Count).ToGZipAsync().Result;
            this._brotliString = RandomData.GenerateWord(Count).ToBrotliAsync().Result;

            this._testString = RandomData.GenerateWord(this.Count);
        }
        public void SubstringTrim()
        {
            var result = RandomData.GenerateWord(100).SubstringTrim(25, 25);

            base.Consumer.Consume(result);
        }
        public void CopyAndMoveDirectoryTest()
        {
            var sourcePath      = Path.Combine(_tempPath.FullName, $"{nameof(this.CopyAndMoveDirectoryTest)}{RandomData.GenerateKey()}");
            var destinationPath = Path.Combine(_tempPath.FullName, nameof(this.CopyAndMoveDirectoryTest));

            RandomData.GenerateFiles(sourcePath, 100, 100);

            var folderToCopy = new DirectoryInfo(sourcePath);

            try
            {
                DirectoryHelper.CopyDirectory(folderToCopy.FullName, _tempPath.FullName, false);
                DirectoryHelper.MoveDirectory(folderToCopy.FullName, destinationPath, 2);
            }
            catch (Exception ex)
            {
                Assert.Fail(ex.Message);
            }
            finally
            {
                DirectoryHelper.DeleteDirectory(destinationPath);
            }
        }
        private void Seed()
        {
            using var dataContext = this.CreateDataContext();

            dataContext.Database.EnsureDeleted();
            dataContext.Database.EnsureCreated();

            // Create random blogs.
            var numberOfBlogs = RandomData.GetInt(4, 8);

            this.NextBlogId = numberOfBlogs + 1;
            for (var i = 1; i <= numberOfBlogs; i++)
            {
                var blog = new Blog
                {
                    BlogId = i,
                    Name   = RandomData.GetTitleWords()
                };

                dataContext.BlogTable.Add(blog);
            }

            dataContext.SaveChanges();

            // Create random people.
            var personNameGenerator = new PersonNameGenerator();
            var numberOfPersons     = RandomData.GetInt(16, 32);

            this.NextPersonId = numberOfPersons + 1;
            for (var i = 1; i <= numberOfPersons; i++)
            {
                var firstName = personNameGenerator.GenerateRandomFirstName();
                var lastName  = personNameGenerator.GenerateRandomLastName();
                var twitter   = $"@{firstName.First()}{lastName}".ToLowerInvariant();
                var person    = new Person
                {
                    PersonId  = i,
                    FirstName = firstName,
                    LastName  = lastName,
                    Twitter   = twitter
                };

                dataContext.PersonTable.Add(person);
            }

            dataContext.SaveChanges();

            // Create random articles.
            var numberOfArticles = RandomData.GetInt(8, 16);

            this.NextArticleId = numberOfArticles + 1;
            for (var i = 1; i <= numberOfArticles; i++)
            {
                var blogId   = RandomData.GetLong(1, numberOfBlogs);
                var authorId = RandomData.GetLong(1, numberOfPersons);
                var article  = new Article
                {
                    BlogId    = blogId,
                    AuthorId  = authorId,
                    ArticleId = i,
                    Title     = RandomData.GetTitleWords(),
                    Text      = RandomData.GetParagraphs()
                };

                dataContext.ArticleTable.Add(article);
            }

            dataContext.SaveChanges();

            // Create random comments.
            var numberOfComments = RandomData.GetInt(16, 32);

            this.NextCommentId = numberOfComments + 1;
            for (var i = 1; i <= numberOfComments; i++)
            {
                var articleId = RandomData.GetLong(1, numberOfArticles);
                var authorId  = RandomData.GetLong(0, 2) != 0 ? RandomData.GetLong(1, numberOfPersons) : new long?();
                var comment   = new Comment
                {
                    ArticleId = articleId,
                    AuthorId  = authorId,
                    CommentId = i,
                    Body      = RandomData.GetSentence()
                };

                dataContext.CommentTable.Add(comment);
            }

            dataContext.SaveChanges();
        }
Пример #29
0
        public async Task CanHandleMultipleWorkItemInstances()
        {
            const int workItemCount = 1000;

            using (var metrics = new InMemoryMetricsClient(loggerFactory: Log)) {
                using (var queue = new InMemoryQueue <WorkItemData>(retries: 0, retryDelay: TimeSpan.Zero, loggerFactory: Log)) {
                    queue.AttachBehavior(new MetricsQueueBehavior <WorkItemData>(metrics, loggerFactory: Log));
                    using (var messageBus = new InMemoryMessageBus(Log)) {
                        var handlerRegistry = new WorkItemHandlers();
                        var j1     = new WorkItemJob(queue, messageBus, handlerRegistry, Log);
                        var j2     = new WorkItemJob(queue, messageBus, handlerRegistry, Log);
                        var j3     = new WorkItemJob(queue, messageBus, handlerRegistry, Log);
                        int errors = 0;

                        var jobIds = new ConcurrentDictionary <string, int>();

                        handlerRegistry.Register <MyWorkItem>(async ctx => {
                            var jobData = ctx.GetData <MyWorkItem>();
                            Assert.Equal("Test", jobData.SomeData);

                            var jobWorkTotal = jobIds.AddOrUpdate(ctx.JobId, 1, (key, value) => value + 1);
                            if (jobData.Index % 100 == 0)
                            {
                                _logger.Trace("Job {jobId} processing work item #: {jobWorkTotal}", ctx.JobId, jobWorkTotal);
                            }

                            for (int i = 0; i < 10; i++)
                            {
                                await ctx.ReportProgressAsync(10 * i);
                            }

                            if (RandomData.GetBool(1))
                            {
                                Interlocked.Increment(ref errors);
                                throw new Exception("Boom!");
                            }
                        });

                        for (int i = 0; i < workItemCount; i++)
                        {
                            await queue.EnqueueAsync(new MyWorkItem {
                                SomeData = "Test",
                                Index    = i
                            }, true);
                        }

                        var    completedItems     = new List <string>();
                        object completedItemsLock = new object();
                        messageBus.Subscribe <WorkItemStatus>(status => {
                            if (status.Progress == 100)
                            {
                                _logger.Trace("Progress: {progress}", status.Progress);
                            }

                            if (status.Progress < 100)
                            {
                                return;
                            }

                            lock (completedItemsLock)
                                completedItems.Add(status.WorkItemId);
                        });

                        var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(10));
                        var tasks = new List <Task> {
                            Task.Run(async() => {
                                await j1.RunUntilEmptyAsync(cancellationTokenSource.Token);
                                cancellationTokenSource.Cancel();
                            }, cancellationTokenSource.Token),
                            Task.Run(async() => {
                                await j2.RunUntilEmptyAsync(cancellationTokenSource.Token);
                                cancellationTokenSource.Cancel();
                            }, cancellationTokenSource.Token),
                            Task.Run(async() => {
                                await j3.RunUntilEmptyAsync(cancellationTokenSource.Token);
                                cancellationTokenSource.Cancel();
                            }, cancellationTokenSource.Token)
                        };

                        try {
                            await Task.WhenAll(tasks);

                            await SystemClock.SleepAsync(100);
                        } catch (OperationCanceledException) {}

                        _logger.Info("Completed: {completedItems} Errors: {errors}", completedItems.Count, errors);

                        Assert.Equal(workItemCount, completedItems.Count + errors);
                        Assert.Equal(3, jobIds.Count);
                        Assert.Equal(workItemCount, jobIds.Sum(kvp => kvp.Value));
                    }
                }
            }
        }
        public void SplitTest()
        {
            var testValue = RandomData.GenerateWord(25) + ',' + RandomData.GenerateWord(25);

            Assert.IsTrue(testValue.Split(',').Count() == 2);
        }
Пример #31
0
        private async Task FindDocumentsSamples()
        {
            var database       = Client.GetDatabase(Constants.SamplesDatabase);
            var collection     = database.GetCollection <User>(Constants.UsersCollection);
            var bsonCollection = database.GetCollection <BsonDocument>(Constants.UsersCollection);

            #region Prepare data

            var users = RandomData.GenerateUsers(1000);
            for (int i = 0; i < users.Count; i++)
            {
                if (i >= 30 && i < 50)
                {
                    users[i].Address.City = "Athens";
                }
            }

            await collection.InsertManyAsync(users);

            var sampleUser = RandomData.GenerateUsers(1).First();
            sampleUser.Email = "*****@*****.**";
            sampleUser.Phone = "123-456-789";
            await collection.InsertOneAsync(sampleUser);

            #endregion

            #region Typed classes commands

            // empty filter
            var emptyFilter = Builders <User> .Filter.Empty;

            // first user
            var firstUser = await collection.Find(emptyFilter).FirstOrDefaultAsync();

            // all users
            var allUsers = await collection.Find(emptyFilter).ToListAsync();

            // Get the first document with equality filter on a simple property
            var sampleUserFilter = Builders <User> .Filter.Eq(u => u.Email, sampleUser.Email);

            var dbSampleUser = await collection.Find(sampleUserFilter).FirstOrDefaultAsync();

            // Find multiple documents with equality filter on a simple property
            var doctorsFilter = Builders <User> .Filter.Eq(u => u.Profession, "Doctor");

            var doctors = await collection.Find(doctorsFilter).ToListAsync();

            // same result with .Find
            // doctors = collection.Find(doctorsFilter).ToCursor();
            Utils.Log($"{doctors.Count} doctors found");

            // Query on an embedded field, eg. address.city

            // find all users with address.city = Athens
            var athensCityFilter = Builders <User> .Filter.Eq(u => u.Address.City, "Athens");

            var athensUsers = await collection.Find(athensCityFilter).ToListAsync();

            Utils.Log($"{athensUsers.Count} total users live in Athens");

            // Query on array property

            // find all users that have Basketball on their favorite sports -
            // doesn't have to be the only item on the array, may have more favorite sports as well
            var basketballFilter = Builders <User> .Filter.AnyEq(u => u.FavoriteSports, "Basketball");

            var usersHaveBasketball = await collection.Find(basketballFilter).ToListAsync();

            Utils.Log($"{usersHaveBasketball.Count} have Basketball on their favorite sports collection");

            // find all users that have ONLY Soccer on their favorite sports
            var onlySoccerFilter = Builders <User> .Filter
                                   .Eq(u => u.FavoriteSports, new List <string> {
                "Soccer"
            });

            var soccerUsers = await collection.Find(onlySoccerFilter).ToListAsync();

            Utils.Log($"{soccerUsers.Count} have only Soccer on their favorite sports collection");

            #endregion

            #region BsonDocument commands

            var bsonEmptyDocument = Builders <BsonDocument> .Filter.Empty;

            var bsonFirstUser = await bsonCollection.Find(new BsonDocument()).FirstOrDefaultAsync();

            var bsonAllUsers = await bsonCollection.Find(bsonEmptyDocument).ToListAsync();

            var sampleBsonUserFilter = Builders <BsonDocument> .Filter.Eq("email", sampleUser.Email);

            var dbBsonSampleUser = await bsonCollection.Find(sampleBsonUserFilter).FirstOrDefaultAsync();

            var bsonDoctorsFilter = Builders <BsonDocument> .Filter.Eq("profession", "Doctor");

            var bsonDoctors = await bsonCollection.Find(bsonDoctorsFilter).FirstOrDefaultAsync();

            var bsonAthensCityFilter = Builders <BsonDocument> .Filter.Eq("address.city", "Athens");

            var bsonAthensUsers = await bsonCollection.Find(bsonAthensCityFilter).ToListAsync();

            var bsonBasketballFilter = Builders <BsonDocument> .Filter.AnyEq("favoriteSports", "Basketball");

            var bsonUsersHaveBasketball = await bsonCollection.Find(bsonBasketballFilter).ToListAsync();

            var bsonOnlySoccerFilter = Builders <BsonDocument> .Filter
                                       .Eq("favoriteSports", new List <string>() { "Soccer" });

            var bsonSoccerUsers = await bsonCollection.Find(bsonOnlySoccerFilter).ToListAsync();

            #endregion

            #region Shell commands

#if false
            db.users.findOne({})
        public void ToBase64Test()
        {
            var testValue = RandomData.GenerateWord(25);

            Assert.IsTrue(testValue.ToBase64().IsNotEmpty());
        }
Пример #33
0
        public virtual async Task CanConcurrentlyManageFilesAsync()
        {
            await ResetAsync();

            var storage = GetStorage();

            if (storage == null)
            {
                return;
            }

            using (storage) {
                const string queueFolder = "q";
                var          queueItems  = new BlockingCollection <int>();

                var info = await storage.GetFileInfoAsync("nope");

                Assert.Null(info);

                await Run.InParallelAsync(10, async i => {
                    var ev = new PostInfo {
                        ApiVersion      = 2,
                        CharSet         = "utf8",
                        ContentEncoding = "application/json",
                        Data            = Encoding.UTF8.GetBytes("{}"),
                        IpAddress       = "127.0.0.1",
                        MediaType       = "gzip",
                        ProjectId       = i.ToString(),
                        UserAgent       = "test"
                    };

                    await storage.SaveObjectAsync(Path.Combine(queueFolder, i + ".json"), ev);
                    queueItems.Add(i);
                });

                Assert.Equal(10, (await storage.GetFileListAsync()).Count());

                await Run.InParallelAsync(10, async i => {
                    string path   = Path.Combine(queueFolder, queueItems.Random() + ".json");
                    var eventPost = await storage.GetEventPostAndSetActiveAsync(Path.Combine(queueFolder, RandomData.GetInt(0, 25) + ".json"), _logger);
                    if (eventPost == null)
                    {
                        return;
                    }

                    if (RandomData.GetBool())
                    {
                        await storage.CompleteEventPostAsync(path, eventPost.ProjectId, SystemClock.UtcNow, true, _logger);
                    }
                    else
                    {
                        await storage.SetNotActiveAsync(path, _logger);
                    }
                });
            }
        }
        public void ComputeSha256HashTest()
        {
            var testValue = RandomData.GenerateWord(10);

            Assert.IsTrue(string.IsNullOrEmpty(testValue.ComputeSHA256Hash()) == false);
        }
        public void HasItemsTest02()
        {
            var collection = RandomData.GeneratePersonCollection <PersonProper>(10).AsEnumerable();

            Assert.IsFalse(collection.HasItems(5));
        }
        public void EqualsIgnoreCaseTest()
        {
            var testValue = RandomData.GenerateWord(10);

            Assert.IsTrue(testValue.EqualsIgnoreCase(testValue));
        }
        public void ToDelimitedStringTest()
        {
            var words = RandomData.GenerateWords(10, 25, 50);

            Assert.IsNotNull(words.ToDelimitedString(','));
        }
Пример #38
0
 public static Advertisement NextAppUsedStoryAdvertisement(RandomData randomData)
 {
     return nextAppSponsorStoryAdvertisement(randomData, AdType.App_Used_Story);
 }
        public void ToLinkedListTest()
        {
            var people = RandomData.GeneratePersonCollection <PersonProper>(50);

            Assert.IsTrue(people.ToLinkedList().HasItems());
        }
Пример #40
0
 private static Advertisement nextSponsorStoryAdvertisement(RandomData randomData, AdType type)
 {
     return new Facebook.UITestFramework.Object.Advertisement
     {
         AdName = "Automation_" + randomData.NextAsciiWord(2, 3),
         AdStatus = AdStatus.Scheduled,
         BidType = BidType.CPC,
         MaxBid = 0.01,
         DestinationUrl = null,//new Uri(ConfigurationManager.AppSettings.Get("PageUrl")),
         Body = string.Empty,
         SuggestedBid = new SuggestedBid(),
         AdType = type,
     };
 }
Пример #41
0
 public static Advertisement NextPagePostLikeStoryAdvertisement(RandomData randomData)
 {
     return nextPageSponsorStoryAdvertisement(randomData, AdType.Page_Post_Like_Story);
 }
Пример #42
0
        public GoogleFramework.Object.TextAdvertisement AddTextAdForInit(RandomData random)
        {
            Google.UITestFramework.UIMaps.TextAdClasses.TextAd textAdUI = testBase.Get<UITestFramework.UIMaps.TextAdClasses.TextAd>();
            textAdUI.ClickAddTextAdButton();

            Google.UITestFramework.Object.TextAdvertisement textAdObject = Google.UITestFramework.Object.TextAdvertisement.NextTextAd(random);

            CommonUIMaps.DetailedInfoForUploadClasses.DetailedInfoForUpload uploadWindow = testBase.Get<CommonUIMaps.DetailedInfoForUploadClasses.DetailedInfoForUpload>();
            return AddTextAd(textAdObject, false, uploadWindow.VerifyUploadOneGoogleTextAd);
        }
Пример #43
0
        private async Task SendEventNoticeAsync(PersistentEvent ev)
        {
            var user    = UserData.GenerateSampleUser();
            var project = ProjectData.GenerateSampleProject();

            ev.Id             = TestConstants.EventId;
            ev.OrganizationId = TestConstants.OrganizationId;
            ev.ProjectId      = TestConstants.ProjectId;
            ev.StackId        = TestConstants.StackId;

            await _mailer.SendEventNoticeAsync(user, ev, project, RandomData.GetBool(), RandomData.GetBool(), 1);

            await RunMailJobAsync();
        }
Пример #44
0
        public GoogleFramework.Object.Campaign AddCampaignForInit(RandomData random)
        {
            GoogleUIMaps.CampaignsClasses.Campaigns campaignUI = testBase.Get<GoogleUIMaps.CampaignsClasses.Campaigns>();
            campaignUI.ClickAddCPMCampaignButton();
            string campaignName = GoogleFramework.Object.Campaign.NextCampaignName(random);

            CommonUIMaps.DetailedInfoForUploadClasses.DetailedInfoForUpload uploadWindow = testBase.Get<CommonUIMaps.DetailedInfoForUploadClasses.DetailedInfoForUpload>();
            return AddCampaign(campaignName, uploadWindow.VerifyUploadOneGoogleCampaign);
        }
Пример #45
0
        public virtual async Task CanRunMultipleQueueJobsAsync()
        {
            const int jobCount      = 5;
            const int workItemCount = 100;

            Log.SetLogLevel <SampleQueueJob>(LogLevel.Information);
            Log.SetLogLevel <InMemoryMetricsClient>(LogLevel.None);

            using (var metrics = new InMemoryMetricsClient(new InMemoryMetricsClientOptions {
                LoggerFactory = Log, Buffered = true
            })) {
                var queues = new List <IQueue <SampleQueueWorkItem> >();
                try {
                    for (int i = 0; i < jobCount; i++)
                    {
                        var q = GetSampleWorkItemQueue(retries: 1, retryDelay: TimeSpan.Zero);
                        await q.DeleteQueueAsync();

                        q.AttachBehavior(new MetricsQueueBehavior <SampleQueueWorkItem>(metrics, "test", loggerFactory: Log));
                        queues.Add(q);
                    }
                    _logger.LogInformation("Done setting up queues");

                    var enqueueTask = Run.InParallelAsync(workItemCount, index => {
                        var queue = queues[RandomData.GetInt(0, jobCount - 1)];
                        return(queue.EnqueueAsync(new SampleQueueWorkItem {
                            Created = SystemClock.UtcNow,
                            Path = RandomData.GetString()
                        }));
                    });
                    _logger.LogInformation("Done enqueueing");

                    var cancellationTokenSource = new CancellationTokenSource();
                    await Run.InParallelAsync(jobCount, async index => {
                        var queue = queues[index - 1];
                        var job   = new SampleQueueJob(queue, metrics, Log);
                        await job.RunUntilEmptyAsync(cancellationTokenSource.Token);
                        cancellationTokenSource.Cancel();
                    });

                    _logger.LogInformation("Done running jobs until empty");

                    await enqueueTask;

                    var queueStats = new List <QueueStats>();
                    for (int i = 0; i < queues.Count; i++)
                    {
                        var stats = await queues[i].GetQueueStatsAsync();
                        if (_logger.IsEnabled(LogLevel.Information))
                        {
                            _logger.LogInformation("Queue#{Id}: Working: {Working} Completed: {Completed} Abandoned: {Abandoned} Error: {Errors} Deadletter: {Deadletter}", i, stats.Working, stats.Completed, stats.Abandoned, stats.Errors, stats.Deadletter);
                        }
                        queueStats.Add(stats);
                    }
                    _logger.LogInformation("Done getting queue stats");

                    await metrics.FlushAsync();

                    _logger.LogInformation("Done flushing metrics");

                    var queueSummary = await metrics.GetQueueStatsAsync("test.samplequeueworkitem");

                    Assert.Equal(queueStats.Sum(s => s.Completed), queueSummary.Completed.Count);
                    Assert.InRange(queueStats.Sum(s => s.Completed), 0, workItemCount);
                } finally {
                    foreach (var q in queues)
                    {
                        await q.DeleteQueueAsync();

                        q.Dispose();
                    }
                }
            }
        }
Пример #46
0
 public static string NextCampaignName(RandomData randomData)
 {
     return "___" + randomData.NextAsciiWord(5, 7);
 }
        public void GetHashCodeTest()
        {
            var person = RandomData.GenerateRefPerson <PersonProper>();

            Assert.IsTrue(person.GetHashCode().IsInRange(int.MinValue, int.MaxValue));
        }