Inheritance: MonoBehaviour
Example #1
0
 void Start()
 {
     GameObject go = GameObject.Find("TimerHUD");
     timeScript = go.transform.FindChild("Timer").GetComponent<Times>();
     level = timeScript.level;
     bestText = go.transform.FindChild("BestTimePopup").gameObject;
 }
 public double Evaluate()
 {
     // normally this is the parser/lexer's job
     // http://pragprog.com/book/tpdsl/language-implementation-patterns
     IExpression expression = new Times(new Plus(new Number(8), new Number(5)), new Minus(new Number(10), new Number(6)));
     return expression.Interpret();
 }
Example #3
0
	/// <summary>Initializes a new instance of the <see cref="Subtitle" /> class, given the
	/// global subtitles' properties and the subtitle's text and style.</summary>
	/// <param name="properties">The subtitles' properties.</param>
	/// <param name="text">The subtitle's text.</param>
	/// <param name="style">The subtitle's style.</param>
	public Subtitle (SubtitleProperties properties, SubtitleText text, Style style) {
		this.properties = properties;
		this.text = text;
		this.style = style;

		times = new Times(this);
		frames = new Frames(this);
	}
        /// <summary>
        /// 
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public Achievement(Identifier id, String name, String description, 
            Times times, ProgressType type, Object init = null)
        {
            this.Id = id;
            this.Name = name;
            this.Description = description;

            this.Scope = times;
            this.Type = type;
            this.InitialValue = init;
            this.Progress = init;
        }
        public void TestTimesForYear()
        {
            PrayerTimesCalculator calc = new PrayerTimesCalculator(47.660918, -122.136371);
            calc.CalculationMethod = CalculationMethods.ISNA;
            calc.AsrJurusticMethod = AsrJuristicMethods.Shafii;
            var times = new Times[365];
            for (int i = 0; i < 365; i ++)
            {
                var date = new DateTimeOffset(new DateTime(2015, 1, 1));
                times[i] = calc.GetPrayerTimes(date.AddDays(i), -7);
            }

            Assert.Equal(new DateTime(2015, 2, 3), times[33].Date);
            Assert.Equal(new TimeSpan(6, 8, 0), times[33].Fajr);
        }
Example #6
0
	/* Private methods */

	private void SetFieldsForDeepClone (SubtitleProperties properties, Times times, Frames frames, SubtitleText text, SubtitleText translation, Style style) {
		this.properties = properties;
		this.times = times;
		this.frames = frames;
		this.text = text;
		this.translation = translation;
		this.style = style;
	}
 private void VerifyServiceDisconnect(Times expected)
 {
     sonarQubeServiceMock.Verify(disconnectMethod, expected);
 }
Example #8
0
        public void GivenRatingIsGreaterThanOrEqualToHalfOfRatingCeiling_ShouldContainHIGH()
        {
            int rating       = 2;
            int ratingCeling = 4;

            externalRatingApprovalService.Setup(mock => mock.IsApproved(rating)).Returns(true);
            moderateClass = new ModerateClass(notificationService.Object, externalRatingApprovalService.Object);
            using (ShimsContext.Create())
            {
                String result = moderateClass.CreateRatingString(rating, ratingCeling);
                Assert.AreEqual("HIGH=2", result);
                externalRatingApprovalService.Verify(mock => mock.IsApproved(rating), Times.Once());
                notificationService.Verify(mock => mock.Notify(rating), Times.Once());
            }
        }
Example #9
0
        public void ViewModelsFromNotCurrentModule()
        {
            var viewModelPartPatcher = new Mock <IViewModelPartPatcher>();
            var viewModelPatcher     = new ViewModelPatcher(new[] { viewModelPartPatcher.Object });
            var viewModel1           = FakeCommonTypeBuilder.Create("ViewModel1", typeof(ViewModelBase)).WhereFrom(MonoCecilModule.Object).Build();
            var viewModel2           = FakeCommonTypeBuilder.Create("ViewModel2", typeof(ViewModelBase)).Build();
            var viewModel3           = FakeCommonTypeBuilder.Create("ViewModel3", typeof(ViewModelBase)).WhereFrom(MonoCecilModule.Object).Build();
            var viewModel4           = FakeCommonTypeBuilder.Create("ViewModel4", typeof(ViewModelBase)).Build();

            viewModelPatcher.Patch(MonoCecilAssembly.Object, new CommonTypeContainer(new[] { ViewModelBase, viewModel1, viewModel2, viewModel3, viewModel4 }));

            viewModelPartPatcher
            .Verify(patcher => patcher.Patch(It.IsAny <MonoCecilAssembly>(), It.IsAny <CommonType>(), It.IsAny <CommonType>(), It.IsAny <ViewModelPatchingType>()), Times.Exactly(2));
            viewModelPartPatcher
            .Verify(patcher => patcher.Patch(MonoCecilAssembly.Object, ViewModelBase, viewModel1, ViewModelPatchingType.All), Times.Once);
            viewModelPartPatcher
            .Verify(patcher => patcher.Patch(MonoCecilAssembly.Object, ViewModelBase, viewModel3, ViewModelPatchingType.All), Times.Once);
        }
        public void ActiveSolutionBoundTracker_When_ConnectAsync_Throws_Write_To_Output()
        {
            // Arrange
            var sonarQubeServiceMock = new Mock <ISonarQubeService>();

            this.host.SonarQubeService = sonarQubeServiceMock.Object;

            using (var activeSolutionBoundTracker = new ActiveSolutionBoundTracker(this.host, this.activeSolutionTracker, this.loggerMock.Object))
            {
                // We want to directly jump to Connect
                sonarQubeServiceMock.SetupGet(x => x.IsConnected).Returns(false);
                ConfigureSolutionBinding(new BoundSonarQubeProject(new Uri("http://test"), "projectkey", "projectName"));

                // ConnectAsync should throw
                sonarQubeServiceMock
                .SetupSequence(x => x.ConnectAsync(It.IsAny <ConnectionInformation>(), It.IsAny <CancellationToken>()))
                .Throws <Exception>()
                .Throws <TaskCanceledException>()
                .Throws(new HttpRequestException("http request", new Exception("something happened")));

                // Act
                // Throwing errors will put the connection and binding out of sync, which
                // cause a Debug.Assert in the product code that we need to suppress
                using (new AssertIgnoreScope())
                {
                    this.activeSolutionTracker.SimulateActiveSolutionChanged(isSolutionOpen: true);
                    this.activeSolutionTracker.SimulateActiveSolutionChanged(isSolutionOpen: false);
                    this.activeSolutionTracker.SimulateActiveSolutionChanged(isSolutionOpen: true);
                }

                // Assert
                this.loggerMock
                .Verify(x => x.WriteLine(It.Is <string>(s => s.StartsWith("SonarQube request failed:")), It.IsAny <object[]>()), Times.Exactly(2));
                this.loggerMock
                .Verify(x => x.WriteLine(It.Is <string>(s => s.StartsWith("SonarQube request timed out or was canceled"))), Times.Once);
            }
        }
        public void SetCustomProperties()
        {
            _settingsMock.Setup(settings => settings.GetValue(AppCenter.EnabledKey, It.IsAny <bool>()))
            .Returns(true);

            // Set before App Center is configured.
            AppCenter.SetCustomProperties(new CustomProperties());
            _channelMock.Verify(channel => channel.EnqueueAsync(It.IsAny <Log>()), Times.Never());

            AppCenter.Configure("appsecret");

            // Set null.
            AppCenter.SetCustomProperties(null);
            _channelMock.Verify(channel => channel.EnqueueAsync(It.IsAny <Log>()), Times.Never());

            // Set empty.
            var empty = new CustomProperties();

            AppCenter.SetCustomProperties(empty);
            _channelMock.Verify(channel => channel.EnqueueAsync(It.IsAny <Log>()), Times.Never());

            // Set normal.
            var properties = new CustomProperties();

            properties.Set("test", "test");
            AppCenter.SetCustomProperties(properties);
            _channelMock.Verify(channel => channel.EnqueueAsync(It.Is <CustomPropertyLog>(log =>
                                                                                          log.Properties == properties.Properties)), Times.Once());
        }
Example #12
0
	private void ParseStartTime (Match match, Times times, Times previousTimes, ParsingProperties properties) {
		bool isTimeDefined = false;
		TimeSpan startTime = new TimeSpan(0);

		int result = 0;
		float floatResult = 0;
		if (ParseGroup(match, "StartHours", ref result)) {
			startTime += TimeSpan.FromHours(result);
			isTimeDefined = true;
		}
		if (ParseGroup(match, "StartMinutes", ref result)) {
			startTime += TimeSpan.FromMinutes(result);
			isTimeDefined = true;
		}
		if (ParseGroup(match, "StartSeconds", ref result)) {
			startTime += TimeSpan.FromSeconds(result);
			isTimeDefined = true;
		}
		if (ParseGroup(match, "StartDeciseconds", ref result)) {
			startTime += TimeSpan.FromMilliseconds(result * 100);
			isTimeDefined = true;
		}
		if (ParseGroup(match, "StartCentiseconds", ref result)) {
			startTime += TimeSpan.FromMilliseconds(result * 10);
			isTimeDefined = true;
		}
		if (ParseGroup(match, "StartMilliseconds", ref result)) {
			startTime += TimeSpan.FromMilliseconds(result);
			isTimeDefined = true;
		}
		if (ParseGroup(match, "StartMillisecondsAsFrames", ref result)) {
			startTime += TimingUtil.FramesToTime(result, properties.InputFrameRate);
			isTimeDefined = true;
		}

		if (ParseGroup(match, "StartElapsedTime", ref floatResult)) {
			if (previousTimes != null)
				startTime += previousTimes.PreciseEnd;

			startTime += TimeSpan.FromSeconds(floatResult);
			isTimeDefined = true;
		}
		if (isTimeDefined)
			times.PreciseStart = startTime;
	}
        public void set_cache_to_predefined_value_respect_formatter_through_content_type()
        {
            var client = new HttpClient(_server);
            var req    = new HttpRequestMessage(HttpMethod.Get, _url + "Get_c100_s100");

            req.Content = new StringContent("");
            req.Content.Headers.ContentType = new MediaTypeHeaderValue("text/xml");
            var result = client.SendAsync(req).Result;

            _cache.Verify(s => s.Contains(It.Is <string>(x => x == "sample-get_c100_s100:text/xml")), Times.Exactly(2));
            _cache.Verify(s => s.Add(It.Is <string>(x => x == "sample-get_c100_s100"), It.IsAny <object>(), It.Is <DateTimeOffset>(x => x <= DateTime.Now.AddSeconds(100)), null), Times.Once());
            _cache.Verify(s => s.Add(It.Is <string>(x => x == "sample-get_c100_s100:text/xml"), It.IsAny <object>(), It.Is <DateTimeOffset>(x => x <= DateTime.Now.AddSeconds(100)), It.Is <string>(x => x == "sample-get_c100_s100")), Times.Exactly(1));
        }
        public void set_cache_dont_exclude_querystring_duplicate_action_arg_in_querystring_is_still_excluded()
        {
            var client = new HttpClient(_server);
            var result = client.GetAsync(_url + "Get_s50_exclude_false/1?id=1").Result;

            _cache.Verify(s => s.Contains(It.Is <string>(x => x == "sample-get_s50_exclude_false-id=1:application/json")), Times.Exactly(2));
            _cache.Verify(s => s.Add(It.Is <string>(x => x == "sample-get_s50_exclude_false"), It.IsAny <object>(), It.Is <DateTimeOffset>(x => x <= DateTime.Now.AddSeconds(50)), null), Times.Once());
            _cache.Verify(s => s.Add(It.Is <string>(x => x == "sample-get_s50_exclude_false-id=1:application/json"), It.IsAny <object>(), It.Is <DateTimeOffset>(x => x <= DateTime.Now.AddSeconds(50)), It.Is <string>(x => x == "sample-get_s50_exclude_false")), Times.Once());
        }
        public void controller_level_invalidate_on_three_methods_works_on_put()
        {
            SetupCacheForAutoInvalidate();
            var client = new HttpClient(_server);

            var result2 = client.PutAsync("http://www.strathweb.com/api/autoinvalidate/Put", new StringContent(string.Empty)).Result;

            _cache.Verify(s => s.Contains(It.Is <string>(x => x == "autoinvalidate-get_c100_s100")), Times.Exactly(1));
            _cache.Verify(s => s.Contains(It.Is <string>(x => x == "autoinvalidate-get_s50_exclude_fakecallback")), Times.Exactly(1));
            _cache.Verify(s => s.Contains(It.Is <string>(x => x == "autoinvalidate-etag_match_304")), Times.Exactly(1));
            _cache.Verify(s => s.RemoveStartsWith(It.Is <string>(x => x == "autoinvalidate-get_c100_s100")), Times.Exactly(1));
            _cache.Verify(s => s.RemoveStartsWith(It.Is <string>(x => x == "autoinvalidate-get_s50_exclude_fakecallback")), Times.Exactly(1));
            _cache.Verify(s => s.RemoveStartsWith(It.Is <string>(x => x == "autoinvalidate-etag_match_304")), Times.Exactly(1));
        }
        public void Execute_PreventsSQLInjection()
        {
            _subject.Execute(_user);

            _dbCommand.Verify(c => c.Parameters.Add(It.IsAny <IDbDataParameter>()), Times.AtLeastOnce());
        }
        public void regular_invalidate_on_two_methods_works_on_post()
        {
            SetupCacheForAutoInvalidate();
            var client = new HttpClient(_server);

            var result2 = client.PostAsync(_url + "Post_2_invalidates", new StringContent(string.Empty)).Result;

            _cache.Verify(s => s.Contains(It.Is <string>(x => x == "sample-get_c100_s100")), Times.Exactly(1));
            _cache.Verify(s => s.Contains(It.Is <string>(x => x == "sample-get_s50_exclude_fakecallback")), Times.Exactly(1));
            _cache.Verify(s => s.RemoveStartsWith(It.Is <string>(x => x == "sample-get_c100_s100")), Times.Exactly(1));
            _cache.Verify(s => s.RemoveStartsWith(It.Is <string>(x => x == "sample-get_s50_exclude_fakecallback")), Times.Exactly(1));
        }
        public void controller_level_invalidate_with_type_check_invalidates_only_methods_with_types_matched()
        {
            SetupCacheForAutoInvalidate();
            var client = new HttpClient(_server);

            var result2 = client.PostAsync("http://www.strathweb.com/api/autoinvalidatewithtype/PostString", "hi", new JsonMediaTypeFormatter()).Result;

            _cache.Verify(s => s.Contains(It.Is <string>(x => x == "autoinvalidatewithtype-get_c100_s100")), Times.Exactly(1));
            _cache.Verify(s => s.Contains(It.Is <string>(x => x == "autoinvalidatewithtype-get_c100_s100_array")), Times.Exactly(1));
            _cache.Verify(s => s.Contains(It.Is <string>(x => x == "autoinvalidatewithtype-get_s50_exclude_fakecallback")), Times.Never());
            _cache.Verify(s => s.RemoveStartsWith(It.Is <string>(x => x == "autoinvalidatewithtype-get_c100_s100")), Times.Exactly(1));
            _cache.Verify(s => s.RemoveStartsWith(It.Is <string>(x => x == "autoinvalidatewithtype-get_c100_s100_array")), Times.Exactly(1));
            _cache.Verify(s => s.RemoveStartsWith(It.Is <string>(x => x == "autoinvalidatewithtype-get_s50_exclude_fakecallback")), Times.Never());
        }
        public void SendStartServicesAfterEnable()
        {
            _settingsMock.Setup(settings => settings.GetValue(AppCenter.EnabledKey, It.IsAny <bool>()))
            .Returns(false);

            AppCenter.Start("appsecret", typeof(MockAppCenterService));
            Task.Delay(100).Wait();
            _channelMock.Verify(channel => channel.EnqueueAsync(It.IsAny <StartServiceLog>()), Times.Never());

            _settingsMock.SetupSequence(settings => settings.GetValue(AppCenter.EnabledKey, It.IsAny <bool>()))
            .Returns(false).Returns(true);
            AppCenter.SetEnabledAsync(true).RunNotAsync();
            _channelMock.Verify(channel => channel.EnqueueAsync(It.Is <StartServiceLog>(log =>
                                                                                        log.Services.Count == 1 &&
                                                                                        log.Services[0] == MockAppCenterService.Instance.ServiceName)), Times.Once());
        }
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            dateComboBox.Items.Clear();
            dateComboBox.ResetText();
            timeComboBox.Items.Clear();
            timeComboBox.ResetText();
            timeComboBox.SelectedIndex = -1;
            dateComboBox.Enabled = false;
            timeComboBox.Enabled = false;

            var tutorComboboxItem = tutorComboBox.SelectedItem as ComboBoxHandler.ComboboxItem;

            if (tutorComboboxItem != null)
            {
                var dateDataTable = tutoR_AVAILABLE_TIMES_SEARCH_BY_TUTORTableAdapter1.GetData(Convert.ToInt32(tutorComboboxItem.Value));

                DateTimeCollection datesAndTimes = new DateTimeCollection();
                //add all unique dates
                foreach (var item in dateDataTable.OrderBy(i => i.date_free))
                {
                    var oneDate = new DateTimes { Date = item.date_free };
                    if (datesAndTimes.FindDateCollection(oneDate) != null)
                    {
                        var foundItem = datesAndTimes.FindDateCollection(oneDate);
                        var times = new Times
                        {
                            Time = item.date_free.TimeOfDay,
                            TutorTimesId = item.tutor_time_id
                        };
                        foundItem.Times.Add(times);
                    }
                    else
                    {
                        var times = new Times
                        {
                            Time = item.date_free.TimeOfDay,
                            TutorTimesId = item.tutor_time_id
                        };
                        oneDate.Times.Add(times);
                        datesAndTimes.CollectionOfDateTimes.Add(oneDate);
                    }
                }

                foreach (var date in datesAndTimes.CollectionOfDateTimes)
                {
                    var cmbItem = new ComboBoxHandler.ComboboxItem
                    {
                        Text = date.Date.ToLongDateString(),
                        Value = date
                    };
                    dateComboBox.Items.Add(cmbItem);
                }

                dateComboBox.Enabled = true;
            }
            else
            {
                ClearForm();
            }
        }
        public void set_cache_do_exclude_querystring_do_not_exclude_action_arg_even_if_passed_as_querystring()
        {
            var client = new HttpClient(_server);
            var result = client.GetAsync(_url + "Get_s50_exclude_true?id=1").Result;

            //check
            _cache.Verify(s => s.Contains(It.Is <string>(x => x == "sample-get_s50_exclude_true-id=1:application/json")), Times.Exactly(2));

            //base
            _cache.Verify(s => s.Add(It.Is <string>(x => x == "sample-get_s50_exclude_true"), It.IsAny <object>(), It.Is <DateTimeOffset>(x => x <= DateTime.Now.AddSeconds(50)), null), Times.Once());

            //actual
            _cache.Verify(s => s.Add(It.Is <string>(x => x == "sample-get_s50_exclude_true-id=1:application/json"), It.IsAny <object>(), It.Is <DateTimeOffset>(x => x <= DateTime.Now.AddSeconds(50)), It.Is <string>(x => x == "sample-get_s50_exclude_true")), Times.Once());
        }
 public NumericUpDownTimer(Times time)
     : this()
 {
     this.Time = time;
 }
        public void callback_alone_is_excluded_querystring()
        {
            var client = new HttpClient(_server);
            var result = client.GetAsync(_url + "Get_s50_exclude_fakecallback?callback=abc").Result;

            _cache.Verify(s => s.Contains(It.Is <string>(x => x == "sample-get_s50_exclude_fakecallback:application/json")), Times.Exactly(2));
            _cache.Verify(s => s.Add(It.Is <string>(x => x == "sample-get_s50_exclude_fakecallback"), It.IsAny <object>(), It.Is <DateTimeOffset>(x => x <= DateTime.Now.AddSeconds(50)), null), Times.Once());
            _cache.Verify(s => s.Add(It.Is <string>(x => x == "sample-get_s50_exclude_fakecallback:application/json"), It.IsAny <object>(), It.Is <DateTimeOffset>(x => x <= DateTime.Now.AddSeconds(50)), It.Is <string>(x => x == "sample-get_s50_exclude_fakecallback")), Times.Once());
        }
Example #24
0
 public static Loop Loop(Times times)
 {
     EnsureActiveSequence("Creating a loop");
     return Instance.CreateLoop(times);
 }
        public void no_caching_if_user_authenticated_and_flag_set_to_off()
        {
            SetCurrentThreadIdentity("Filip");
            var client = new HttpClient(_server);
            var result = client.GetAsync(_url + "Get_s50_c50_anonymousonly").Result;

            Assert.True(result.IsSuccessStatusCode);
            Assert.IsNull(result.Headers.CacheControl);
            _cache.Verify(s => s.Add(It.IsAny <string>(), It.IsAny <object>(), It.IsAny <DateTimeOffset>(), It.IsAny <string>()), Times.Never());
        }
Example #26
0
        public void ManyPartPatchersAndViewModels()
        {
            const int viewModelCount   = 5;
            const int partPatcherCount = 4;

            var viewModelPartPatchers = Enumerable.Range(0, partPatcherCount).Select(x => new Mock <IViewModelPartPatcher>()).ToArray();
            var viewModelPatcher      = new ViewModelPatcher(viewModelPartPatchers.Select(patcher => patcher.Object).ToArray());
            var viewModels            = Enumerable.Range(0, viewModelCount)
                                        .Select(x => FakeCommonTypeBuilder.Create($"ViewModel{x + 1}", typeof(ViewModelBase)).WhereFrom(MonoCecilModule.Object).Build())
                                        .ToArray();

            viewModelPatcher.Patch(MonoCecilAssembly.Object, new CommonTypeContainer(new[] { ViewModelBase }.Concat(viewModels).ToArray()));

            foreach (var viewModelPartPatcher in viewModelPartPatchers)
            {
                viewModelPartPatcher
                .Verify(patcher => patcher.Patch(It.IsAny <MonoCecilAssembly>(), It.IsAny <CommonType>(), It.IsAny <CommonType>(), It.IsAny <ViewModelPatchingType>()), Times.Exactly(viewModelCount));
                foreach (var viewModel in viewModels)
                {
                    viewModelPartPatcher
                    .Verify(patcher => patcher.Patch(MonoCecilAssembly.Object, ViewModelBase, viewModel, ViewModelPatchingType.All), Times.Once);
                }
            }
        }
        public void set_cache_to_predefined_value()
        {
            var client = new HttpClient(_server);
            var result = client.GetAsync(_url + "Get_c100_s100").Result;

            _cache.Verify(s => s.Contains(It.Is <string>(x => x == "sample-get_c100_s100:application/json")), Times.Exactly(2));
            _cache.Verify(s => s.Add(It.Is <string>(x => x == "sample-get_c100_s100"), It.IsAny <object>(), It.Is <DateTimeOffset>(x => x <= DateTime.Now.AddSeconds(100)), null), Times.Once());
            _cache.Verify(s => s.Add(It.Is <string>(x => x == "sample-get_c100_s100:application/json"), It.IsAny <object>(), It.Is <DateTimeOffset>(x => x <= DateTime.Now.AddSeconds(100)), It.Is <string>(x => x == "sample-get_c100_s100")), Times.Once());
        }
Example #28
0
        public async Task TestPeriodicAndCallbackConfigUpdate()
        {
            // Arrange
            string id = "id";
            string iotHub = "foo.azure-devices.net";
            var routerConfig = new RouterConfig(Enumerable.Empty<Route>());

            var messageStore = new Mock<IMessageStore>();
            messageStore.Setup(m => m.SetTimeToLive(It.IsAny<TimeSpan>()));

            TimeSpan updateFrequency = TimeSpan.FromSeconds(10);

            Endpoint GetEndpoint() => new ModuleEndpoint("id", Guid.NewGuid().ToString(), "in1", Mock.Of<IConnectionManager>(), Mock.Of<Core.IMessageConverter<IMessage>>());
            var endpointFactory = new Mock<IEndpointFactory>();
            endpointFactory.Setup(e => e.CreateSystemEndpoint($"$upstream")).Returns(GetEndpoint);
            var routeFactory = new EdgeRouteFactory(endpointFactory.Object);

            var endpointExecutorFactory = new Mock<IEndpointExecutorFactory>();
            endpointExecutorFactory.Setup(e => e.CreateAsync(It.IsAny<Endpoint>()))
                .Returns<Endpoint>(endpoint => Task.FromResult(Mock.Of<IEndpointExecutor>(e => e.Endpoint == endpoint)));
            Router router = await Router.CreateAsync(id, iotHub, routerConfig, endpointExecutorFactory.Object);

            var routes1 = Routes.Take(2)
                .ToDictionary(r => r.Key, r => new RouteConfig(r.Key, r.Value, routeFactory.Create(r.Value)));
            var storeAndForwardConfiguration1 = new StoreAndForwardConfiguration(7200);
            var edgeHubConfig1 = new EdgeHubConfig("1.0", routes1, storeAndForwardConfiguration1);

            var routes2 = Routes.Take(3)
                .ToDictionary(r => r.Key, r => new RouteConfig(r.Key, r.Value, routeFactory.Create(r.Value)));
            var storeAndForwardConfiguration2 = new StoreAndForwardConfiguration(7200);
            var edgeHubConfig2 = new EdgeHubConfig("1.0", routes2, storeAndForwardConfiguration2);

            var routes3 = Routes.Take(4)
                .ToDictionary(r => r.Key, r => new RouteConfig(r.Key, r.Value, routeFactory.Create(r.Value)));
            var storeAndForwardConfiguration3 = new StoreAndForwardConfiguration(7200);
            var edgeHubConfig3 = new EdgeHubConfig("1.0", routes3, storeAndForwardConfiguration3);

            Func<EdgeHubConfig, Task> updateCallback = null;
            var configProvider = new Mock<IConfigSource>();
            configProvider.SetupSequence(c => c.GetConfig())
                .ReturnsAsync(Option.Some(edgeHubConfig1))
                .ReturnsAsync(Option.Some(edgeHubConfig2))
                .ReturnsAsync(Option.Some(edgeHubConfig3));
            configProvider.Setup(c => c.SetConfigUpdatedCallback(It.IsAny<Func<EdgeHubConfig, Task>>()))
                .Callback<Func<EdgeHubConfig, Task>>(callback => { updateCallback = callback; });

            // Act
            var configUpdater = new ConfigUpdater(router, messageStore.Object, updateFrequency, Option.None<IConfigSource>());
            await configUpdater.Init(configProvider.Object);

            // Assert
            configProvider.Verify(c => c.GetConfig(), Times.Once);
            endpointExecutorFactory.Verify(e => e.CreateAsync(It.IsAny<Endpoint>()), Times.Once);
            messageStore.Verify(m => m.SetTimeToLive(It.IsAny<TimeSpan>()), Times.Once);

            // call update with no changes
            await updateCallback(edgeHubConfig1);
            configProvider.Verify(c => c.GetConfig(), Times.Exactly(1));
            endpointExecutorFactory.Verify(e => e.CreateAsync(It.IsAny<Endpoint>()), Times.Once);
            messageStore.Verify(m => m.SetTimeToLive(It.IsAny<TimeSpan>()), Times.Once);

            await Task.Delay(TimeSpan.FromSeconds(12));
            configProvider.Verify(c => c.GetConfig(), Times.Exactly(2));
            endpointExecutorFactory.Verify(e => e.CreateAsync(It.IsAny<Endpoint>()), Times.Once);
            messageStore.Verify(m => m.SetTimeToLive(It.IsAny<TimeSpan>()), Times.Exactly(2));

            // call update with changes
            await updateCallback(edgeHubConfig3);
            configProvider.Verify(c => c.GetConfig(), Times.Exactly(2));
            endpointExecutorFactory.Verify(e => e.CreateAsync(It.IsAny<Endpoint>()), Times.Once);
            messageStore.Verify(m => m.SetTimeToLive(It.IsAny<TimeSpan>()), Times.Exactly(3));

            await Task.Delay(TimeSpan.FromSeconds(10));
            configProvider.Verify(c => c.GetConfig(), Times.Exactly(3));
            endpointExecutorFactory.Verify(e => e.CreateAsync(It.IsAny<Endpoint>()), Times.Once);
            messageStore.Verify(m => m.SetTimeToLive(It.IsAny<TimeSpan>()), Times.Exactly(3));
        }
        public void set_cache_to_predefined_value_c100_s0()
        {
            var client = new HttpClient(_server);
            var result = client.GetAsync(_url + "Get_c100_s0").Result;

            // NOTE: Should we expect the _cache to not be called at all if the ServerTimeSpan is 0?
            _cache.Verify(s => s.Contains(It.Is <string>(x => x == "sample-get_c100_s0:application/json")), Times.Once());
            // NOTE: Server timespan is 0, so there should not have been any Add at all.
            _cache.Verify(s => s.Add(It.Is <string>(x => x == "sample-get_c100_s0"), It.IsAny <object>(), It.Is <DateTimeOffset>(x => x <= DateTime.Now.AddSeconds(100)), null), Times.Never());
            _cache.Verify(s => s.Add(It.Is <string>(x => x == "sample-get_c100_s0:application/json"), It.IsAny <object>(), It.Is <DateTimeOffset>(x => x <= DateTime.Now.AddSeconds(1)), It.Is <string>(x => x == "sample-get_c100_s0")), Times.Never());
        }
        public void ActiveSolutionBoundTracker_Changes()
        {
            var boundProject = new BoundSonarQubeProject(new Uri("http://localhost:9000"), "key", "projectName");

            ConfigureService(isConnected: false);
            ConfigureSolutionBinding(boundProject);

            using (var testSubject = new ActiveSolutionBoundTracker(this.host, this.activeSolutionTracker, loggerMock.Object))
            {
                var solutionBindingChangedEventCount = 0;
                testSubject.SolutionBindingChanged += (obj, args) => { solutionBindingChangedEventCount++; };

                // Sanity
                testSubject.CurrentConfiguration.Mode.Should().Be(SonarLintMode.LegacyConnected, "Initially bound");
                this.errorListController.RefreshCalledCount.Should().Be(0);
                this.errorListController.ResetCalledCount.Should().Be(0);
                solutionBindingChangedEventCount.Should().Be(0, "no events raised during construction");
                VerifyAndResetBoundSolutionUIContextMock(isActive: true);

                // Case 1: Clear bound project
                ConfigureSolutionBinding(null);

                // Act
                host.VisualStateManager.ClearBoundProject();

                // Assert
                testSubject.CurrentConfiguration.Mode.Should().Be(SonarLintMode.Standalone, "Unbound solution should report false activation");
                this.errorListController.RefreshCalledCount.Should().Be(0);
                this.errorListController.ResetCalledCount.Should().Be(0);
                solutionBindingChangedEventCount.Should().Be(1, "Unbind should trigger reanalysis");
                VerifyAndResetBoundSolutionUIContextMock(isActive: false);

                VerifyServiceDisconnect(Times.Never());
                VerifyServiceConnect(Times.Never());

                // Case 2: Set bound project
                ConfigureSolutionBinding(boundProject);
                // Act
                host.VisualStateManager.SetBoundProject(new Uri("http://localhost"), null, "project123");

                // Assert
                testSubject.CurrentConfiguration.Mode.Should().Be(SonarLintMode.LegacyConnected, "Bound solution should report true activation");
                this.errorListController.RefreshCalledCount.Should().Be(0);
                this.errorListController.ResetCalledCount.Should().Be(0);
                solutionBindingChangedEventCount.Should().Be(2, "Bind should trigger reanalysis");
                VerifyAndResetBoundSolutionUIContextMock(isActive: true);

                // Notifications from the Team Explorer should not trigger connect/disconnect
                VerifyServiceDisconnect(Times.Never());
                VerifyServiceConnect(Times.Never());

                // Case 3: Bound solution unloaded -> disconnect
                ConfigureSolutionBinding(null);
                // Act
                activeSolutionTracker.SimulateActiveSolutionChanged(isSolutionOpen: false);

                // Assert
                testSubject.CurrentConfiguration.Mode.Should().Be(SonarLintMode.Standalone, "Should respond to solution change event and report unbound");
                this.errorListController.RefreshCalledCount.Should().Be(1);
                this.errorListController.ResetCalledCount.Should().Be(0);
                solutionBindingChangedEventCount.Should().Be(3, "Solution change should trigger reanalysis");
                VerifyAndResetBoundSolutionUIContextMock(isActive: false);

                // Closing an unbound solution should not call disconnect/connect
                VerifyServiceDisconnect(Times.Never());
                VerifyServiceConnect(Times.Never());

                // Case 4: Load a bound solution
                ConfigureSolutionBinding(boundProject);
                // Act
                activeSolutionTracker.SimulateActiveSolutionChanged(isSolutionOpen: true);

                // Assert
                testSubject.CurrentConfiguration.Mode.Should().Be(SonarLintMode.LegacyConnected, "Bound respond to solution change event and report bound");
                this.errorListController.RefreshCalledCount.Should().Be(2);
                this.errorListController.ResetCalledCount.Should().Be(0);
                solutionBindingChangedEventCount.Should().Be(4, "Solution change should trigger reanalysis");
                VerifyAndResetBoundSolutionUIContextMock(isActive: true);

                // Loading a bound solution should call connect
                VerifyServiceDisconnect(Times.Never());
                VerifyServiceConnect(Times.Once());

                // Case 5: Close a bound solution
                ConfigureSolutionBinding(null);
                // Act
                activeSolutionTracker.SimulateActiveSolutionChanged(isSolutionOpen: false);

                // Assert
                // TODO: this.errorListController.RefreshCalledCount.Should().Be(4);
                this.errorListController.ResetCalledCount.Should().Be(0);
                solutionBindingChangedEventCount.Should().Be(5, "Solution change should trigger reanalysis");
                VerifyAndResetBoundSolutionUIContextMock(isActive: false);

                // SonarQubeService.Disconnect should be called since the WPF DisconnectCommand is not available
                VerifyServiceDisconnect(Times.Once());
                VerifyServiceConnect(Times.Once());

                // Case 6: Dispose and change
                // Act
                testSubject.Dispose();
                ConfigureSolutionBinding(boundProject);
                host.VisualStateManager.ClearBoundProject();

                // Assert
                solutionBindingChangedEventCount.Should().Be(5, "Once disposed should stop raising the event");
                // TODO: this.errorListController.RefreshCalledCount.Should().Be(3);
                this.errorListController.ResetCalledCount.Should().Be(1);
                // SonarQubeService.Disconnect should be called since the WPF DisconnectCommand is not available
                VerifyServiceDisconnect(Times.Once());
                VerifyServiceConnect(Times.Once());
            }
        }
        public void not_cache_when_request_exception()
        {
            var client = new HttpClient(_server);
            var result = client.GetAsync(_url + "Get_request_exception_noCache").Result;

            _cache.Verify(s => s.Contains(It.IsAny <string>()), Times.Once());
            _cache.Verify(s => s.Add(It.IsAny <string>(), It.IsAny <object>(), It.IsAny <DateTimeOffset>(), It.IsAny <string>()), Times.Never());
        }
        public async Task TriesToGetValidationSetFirst()
        {
            ValidationStorageMock
            .Setup(vs => vs.GetValidationSetAsync(ValidationSet.ValidationTrackingId))
            .ReturnsAsync(ValidationSet)
            .Verifiable();

            var provider = CreateProvider();

            var set = await provider.TryGetOrCreateValidationSetAsync(PackageValidationMessageData, PackageValidatingEntity);

            ValidationStorageMock
            .Verify(vs => vs.GetValidationSetAsync(ValidationSet.ValidationTrackingId), Times.Once());

            Assert.Same(ValidationSet, set);

            PackageFileServiceMock.Verify(
                x => x.CopyPackageFileForValidationSetAsync(It.IsAny <PackageValidationSet>()),
                Times.Never);
            PackageFileServiceMock.Verify(
                x => x.CopyValidationPackageForValidationSetAsync(It.IsAny <PackageValidationSet>()),
                Times.Never);
            PackageFileServiceMock.Verify(
                x => x.BackupPackageFileFromValidationSetPackageAsync(It.IsAny <PackageValidationSet>(), SasDefinitionConfiguration.ValidationSetProviderSasDefinition),
                Times.Never);
            TelemetryServiceMock.Verify(
                x => x.TrackDurationToValidationSetCreation(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <Guid>(), It.IsAny <TimeSpan>()),
                Times.Never);
        }
Example #33
0
        // PACKETS QUEUING HANDLER
        private void packetToBuffer(int stream_id)
        {
            // Local variables initialization
            Packet packet = streams[stream_id].GeneratePacket();
            Times times = new Times();
            double t = heap.first().time;
            double pom = streams[stream_id].GenerateTime();

            // Here you can test router logic using const values by uncomment next to lines
            //packet.size = 4000;
            //pom = 0.5;

            // Events queue handling
            packet.adding_time = t + pom;
            times.time = pom + t;
            times.action = (int)actions.packet_to_buffer;
            times.stream_id = stream_id;
            if (heap.counter!=0 && heap.first().stream_id==stream_id)
                heap.Delete();
            heap.Add(times);

            int size = buffers[streams[stream_id].buffer_number].data_size;
            // Statistics collecting
            packets_counter[stream_id]++;

            if (buffers[streams[stream_id].buffer_number].Add(packet))      // Adding packet to buffer
            {
                // Send event handling
                if (flag == false)
                {
                    int id = streams[stream_id].buffer_number;
                    if (new_send.time <= t || new_send.time==simulation_time)
                    {
                        Times times1 = new Times();
                        times1.action = 1;
                        times1.time = buffers[id].table[buffers[id].first].adding_time + 0.000001;
                        new_send = times1;
                    }
                    else if (new_send.time > times.time + ((double)buffers[id].table[buffers[id].first].size) * 1000 / channel_capacity)
                    {
                        new_send.time = buffers[id].table[buffers[id].first].adding_time + 0.000001;
                    }
                }

            }
            else
            {
                losted_packets_counter[stream_id]++;        // Statistics of losted packets
            }
        }
Example #34
0
 internal Step(Times expectedCount, string action = "")
 {
     this.expectedCount = expectedCount;
     this.action = action;
     maxCount = (int)to.GetValue(expectedCount);
 }
Example #35
0
        // PACKETS SENDING HANDLER
        private bool send()
        {
            Times times = new Times();
            for (int i = 0; i < number_of_buffers; i++)
            {
                if (buffers[i].data_size > 0)       // Looking for not empty buffers in priority order
                {
                    // Local variables intialization
                    double t = heap.first().time;
                    double tmp = ((double)buffers[i].table[buffers[i].first].size) * 1000 / channel_capacity;

                    // Checking if the packet has already arrived
                    if (t < buffers[i].table[buffers[i].first].adding_time)
                        continue;

                    // Events queue handling
                    times.time = tmp + t;
                    times.action = (int)actions.send;
                    if (heap.counter!=0 && heap.first().action==1)
                        heap.Delete();
                    heap.Add(times);

                    // Statistics collecting
                    if (!flag)
                        free_link2 = free_link2 + t - last_link_modify_time;
                    packet_processing_mil += tmp + t - buffers[i].table[buffers[i].first].adding_time;
                    if(tmp != 0)
                        sended_packet_counter++;

                    // Statistics collecting
                    free_buffers2[i] = free_buffers2[i] + (t + tmp - buffers[i].table[buffers[i].first].adding_time) * (double)buffers[i].table[buffers[i].first].size;

                    // Sending packet out of router
                    buffers[i].PullOut();

                    // Send event handling
                    flag = true;
                    wyslane++;
                    return true;
                }
            }
            // Statistics collecting
            last_link_modify_time = heap.first().time;

            // Events queue handling
            if (heap.counter != 0 && heap.first().action == 1)
                heap.Delete();

            // Send event handling
            flag = false;
            return false;
        }
 public void LogUrlIsNotSetByDefault()
 {
     AppCenter.Configure("appsecret");
     _channelGroupMock.Verify(channelGroup => channelGroup.SetLogUrl(It.IsAny <string>()), Times.Never());
 }
Example #37
0
 internal Loop(Times times)
     : base(times)
 {
 }
Example #38
0
	private void ParseEndTime (Match match, Times times, Times previousTimes, ParsingProperties properties) {
		bool isTimeDefined = false;
		TimeSpan endTime = new TimeSpan(0);

		int result = 0;
		float floatResult = 0;
		if (ParseGroup(match, "EndHours", ref result)) {
			endTime += TimeSpan.FromHours(result);
			isTimeDefined = true;
		}
		if (ParseGroup(match, "EndMinutes", ref result)) {
			endTime += TimeSpan.FromMinutes(result);
			isTimeDefined = true;
		}
		if (ParseGroup(match, "EndSeconds", ref result)) {
			endTime += TimeSpan.FromSeconds(result);
			isTimeDefined = true;
		}
		if (ParseGroup(match, "EndDeciseconds", ref result)) {
			endTime += TimeSpan.FromMilliseconds(result * 100);
			isTimeDefined = true;
		}
		if (ParseGroup(match, "EndCentiseconds", ref result)) {
			endTime += TimeSpan.FromMilliseconds(result * 10);
			isTimeDefined = true;
		}
		if (ParseGroup(match, "EndMilliseconds", ref result)) {
			endTime += TimeSpan.FromMilliseconds(result);
			isTimeDefined = true;
		}
		if (ParseGroup(match, "EndMillisecondsAsFrames", ref result)) {
			endTime += TimingUtil.FramesToTime(result, properties.InputFrameRate);
			isTimeDefined = true;
		}
		if (ParseGroup(match, "EndElapsedTime", ref floatResult)) {
			endTime += times.PreciseStart + TimeSpan.FromSeconds(floatResult);
			isTimeDefined = true;
		}
		if (isTimeDefined)
			times.PreciseEnd = endTime;
	}
Example #39
0
 internal Step CreateStep(object setup, Times expectedCalls)
 {
     var step = new Step(expectedCalls, "''" + setup + "'");
     LastCreatedActiveLoop().steps.Add(step);
     return step;
 }
        public void not_cache_add_when_no_content()
        {
            var client = new HttpClient(_server);
            var result = client.GetAsync(_url + "Get_request_noContent").Result;

            _cache.Verify(s => s.Contains(It.Is <string>(x => x == "sample-get_request_nocontent:application/json")), Times.Exactly(2));
            _cache.Verify(s => s.Add(It.IsAny <string>(), It.IsAny <object>(), It.IsAny <DateTimeOffset>(), It.IsAny <string>()), Times.Never());
        }
        public void SetLogUrlAfterConfigure()
        {
            AppCenter.Configure("appsecret");
            var customLogUrl = "www dot log url dot com";

            AppCenter.SetLogUrl(customLogUrl);

            _channelGroupMock.Verify(channelGroup => channelGroup.SetLogUrl(customLogUrl), Times.Once());
        }
Example #42
0
        // LOADING INPUT DATA FROM FILE
        private void ReadFromFile()
        {
            Console.WriteLine("Przeciagnij plik inicjalizacyjny i wcisnij enter:");
            string str = Console.ReadLine();
            if (str[0] == '"')
               str = str.Substring(1,str.Length-2);
            //string str = "F:\\Multimedia\\Dokumenty\\Studia\\PW Notatki\\Semestr 3\\AISDE\\Projekty\\Projekt1\\AISDE_nr1\\AISDE_nr1\\bin\\Debug\\Download\\Input\\router.txt";
            FileStream fs = new FileStream(str, FileMode.OpenOrCreate, FileAccess.ReadWrite);
            System.IO.StreamReader filestream = new System.IO.StreamReader(fs);

            string tmp = "";
            string[] words;

            bool logic = true;
            while (logic)
            {
                tmp = filestream.ReadLine();
                if(!string.IsNullOrEmpty(tmp))
                    if (tmp[0] != '#')
                    {
                        logic = false;
                    }
            }
            logic = true;
            while (logic)
            {
                tmp = filestream.ReadLine();
                if (!string.IsNullOrEmpty(tmp))
                    if (tmp[0] != '#')
                    {
                        logic = false;
                    }
            }
            words = tmp.Split(' ');
            channel_capacity = int.Parse(words[2]);
            logic = true;
            while (logic)
            {
                tmp = filestream.ReadLine();
                if (!string.IsNullOrEmpty(tmp))
                    if (tmp[0] != '#')
                    {
                        logic = false;
                    }
            }
            words = tmp.Split(' ');
            number_of_buffers = int.Parse(words[2]);
            int[] lbuffers = new int[number_of_buffers];
            string[] buffers_names = new string[number_of_buffers];
            for(int i=0;i< number_of_buffers; i++)
            {
                tmp = filestream.ReadLine();
                words = tmp.Split(' ');
                lbuffers[i]= int.Parse(words[5]);
                buffers_names[i] = words[2];
            }
            logic = true;
            while (logic)
            {
                tmp = filestream.ReadLine();
                if (!string.IsNullOrEmpty(tmp))
                    if (tmp[0] != '#')
                    {
                        logic = false;
                    }
            }
            words = tmp.Split(' ');
            int R = int.Parse(words[2]);
            float[] lambdas = new float[R];
            for (int i = 0; i < R; i++)
            {
                tmp = filestream.ReadLine();
                tmp = filestream.ReadLine();
                words = tmp.Split(' ');
                words[2] = words[2].Replace(".",",");
                lambdas[i] = float.Parse(words[2]);
            }
            logic = true;
            while (logic)
            {
                tmp = filestream.ReadLine();
                if (!string.IsNullOrEmpty(tmp))
                    if (tmp[0] != '#')
                    {
                        logic = false;
                    }
            }
            words = tmp.Split(' ');
            number_of_streams = int.Parse(words[2]);
            names_of_streams = new string[number_of_streams];
            string[] names_of_buffers = new string[number_of_streams];
            string[] time_lambdas = new string[number_of_streams];
            string[] size_lambdas = new string[number_of_streams];
            for (int i = 0; i < number_of_streams; i++)
            {
                tmp = filestream.ReadLine();
                words = tmp.Split(' ');
                names_of_streams[i] = words[2];
                names_of_buffers[i] = words[5];
                time_lambdas[i] = words[8];
                size_lambdas[i] = words[11];
            }
            filestream.Close();
            // End of file reading

            // Setting up initial values
            flag = true;
            buffers = new Buffer[number_of_buffers];
            streams = new Stream[number_of_streams];
            for (int i = 0; i < number_of_buffers; i++)
            {
                buffers[i] = new Buffer();
                buffers[i].SetSize(lbuffers[i]);
            }
            for (int i = 0; i < number_of_streams; i++)
            {
                streams[i] = new Stream();
                for (int j = 0; j < R; j++)
                    if("WYK"+(j+1)==time_lambdas[i])
                        streams[i].time_lambda = lambdas[j];
                for (int j = 0; j < R; j++)
                    if ("WYK" + (j+1) == size_lambdas[i])
                        streams[i].size_lambda = lambdas[j];
                for (int j = 0; j < number_of_buffers; j++)
                    if ("KOL" + (j + 1) == names_of_buffers[i])
                        streams[i].buffer_number = j;
            }
            heap = new Heap2<Times>();
            Times times1 = new Times();
            times1.action = 1;
            times1.time = 0;
            heap.Add(times1);
            for (int i = 0; i < number_of_streams; i++)
            {
                Times times = new Times();
                times.action = 0;
                times.time = 0;
                times.stream_id = i;
                heap.Add(times);
            }

            // Statistics init
            simulation_timer = new Stopwatch();
            last_buffer_modify_time = new double[number_of_buffers];
            free_buffers2 = new double[number_of_buffers];
            for (int i = 0; i < number_of_buffers; i++)
            {
                last_buffer_modify_time[i] = new double();
                free_buffers2[i] = new double();
            }
            losted_packets_counter = new int[number_of_streams];
            packets_counter = new int[number_of_streams];
            for (int i = 0; i < number_of_streams; i++)
            {
                packets_counter[i] = new int();
                losted_packets_counter[i] = new int();
            }

            packet_processing_mil = new double();

            last_link_modify_time = new double();
            free_link2 = new double();
        }
        public void TestUpdateFromDb()
        {
            // Arrange.
            var dataServiceMock = new Mock <IDataService>();
            var service         = new CachedSubscriptionsManager(GetMockLogger(), dataServiceMock.Object, GetMockStatisticsService())
            {
                UpdatePeriodMilliseconds = 100
            };

            service.Prepare();

            // Act.
            service.Start();
            Thread.Sleep(150);
            service.Stop();

            // Assert.
            dataServiceMock.Verify(f => f.LoadObjects(It.Is <LoadingCustomizationStruct>(lcs => lcs.View.DefineClassType == typeof(Subscription))), Times.AtLeast(2));
        }
Example #44
0
 public virtual void VisitTimes(Times n)
 {
 }
        public MockLeagueService VerifyIsValid(Times times)
        {
            Verify(x => x.IsValid(It.IsAny <int>()), times);

            return(this);
        }
Example #46
0
 internal Loop CreateLoop(Times times)
 {
     var loop = new Loop(times);
     LastCreatedActiveLoop().steps.Add(loop);
     return loop;
 }
        public MockLeagueService VerifyGetAll(Times times)
        {
            Verify(x => x.GetAll(), times);

            return(this);
        }
Example #48
0
        public async Task QueryIsBuiltFromFileStartingAtAtSpecificSecondCorrectly()
        {
            const string pathToFile     = "path-to-file";
            const int    startAtSecond  = 120;
            const int    secondsToQuery = 20;
            QueryResult  dummyResult    = new QueryResult(new List <ResultEntry>(), new QueryStats(0, 0, 0, 0));
            var          hashDatas      = new Hashes(new List <HashedFingerprint>(
                                                         new[]
            {
                new HashedFingerprint(GenericHashBuckets(), 0, 0),
                new HashedFingerprint(GenericHashBuckets(), 1, 0.928f),
                new HashedFingerprint(GenericHashBuckets(), 2, 0.928f * 2)
            }), 0.928 * 3);

            fingerprintCommandBuilder.Setup(builder => builder.BuildFingerprintCommand()).Returns(fingerprintingSource.Object);
            fingerprintingSource.Setup(source => source.From(pathToFile, secondsToQuery, startAtSecond)).Returns(withAlgorithmConfiguration.Object);
            withAlgorithmConfiguration.Setup(config => config.WithFingerprintConfig(It.IsAny <DefaultFingerprintConfiguration>())).Returns(usingFingerprintServices.Object);
            usingFingerprintServices.Setup(u => u.UsingServices(audioService.Object)).Returns(fingerprintCommand.Object);
            fingerprintCommand.Setup(fingerprintingUnit => fingerprintingUnit.Hash()).Returns(Task.Factory.StartNew(() => hashDatas));
            queryFingerprintService.Setup(service => service.Query(hashDatas, It.IsAny <DefaultQueryConfiguration>(), It.IsAny <DateTime>(), modelService.Object)).Returns(dummyResult);

            _ = await queryCommandBuilder.BuildQueryCommand()
                .From(pathToFile, secondsToQuery, startAtSecond)
                .WithQueryConfig(
                config =>
            {
                config.FingerprintConfiguration.SpectrogramConfig.LogBase = 64;
                config.ThresholdVotes = 20;
                return(config);
            })
                .UsingServices(modelService.Object, audioService.Object)
                .Query();

            fingerprintingSource.Verify(source => source.From(pathToFile, secondsToQuery, startAtSecond), Times.Once());
        }
Example #49
0
        public void ManyViewModelsWithPatchingTypes()
        {
            var viewModelPartPatcher = new Mock <IViewModelPartPatcher>();
            var viewModelPatcher     = new ViewModelPatcher(new[] { viewModelPartPatcher.Object });
            var viewModel1           = FakeCommonTypeBuilder.Create("ViewModel1", typeof(ViewModelBase))
                                       .AddAttribute(new FakeAttribute(new PatchingViewModelAttribute(ViewModelPatchingType.Selectively)))
                                       .WhereFrom(MonoCecilModule.Object)
                                       .Build();
            var viewModel2 = FakeCommonTypeBuilder.Create("ViewModel2", typeof(ViewModelBase))
                             .AddAttribute(new FakeAttribute(new PatchingViewModelAttribute()))
                             .WhereFrom(MonoCecilModule.Object)
                             .Build();
            var viewModel3 = FakeCommonTypeBuilder.Create("ViewModel2", typeof(ViewModelBase))
                             .WhereFrom(MonoCecilModule.Object)
                             .Build();
            var viewModel4 = FakeCommonTypeBuilder.Create("ViewModel3", typeof(ViewModelBase))
                             .AddAttribute(new FakeAttribute(new PatchingViewModelAttribute(ViewModelPatchingType.Selectively)))
                             .Build();

            viewModelPatcher.Patch(MonoCecilAssembly.Object, new CommonTypeContainer(new[] { ViewModelBase, viewModel1, viewModel2, viewModel3, viewModel4 }));

            viewModelPartPatcher
            .Verify(patcher => patcher.Patch(It.IsAny <MonoCecilAssembly>(), It.IsAny <CommonType>(), It.IsAny <CommonType>(), It.IsAny <ViewModelPatchingType>()), Times.Exactly(3));
            viewModelPartPatcher
            .Verify(patcher => patcher.Patch(MonoCecilAssembly.Object, ViewModelBase, viewModel1, ViewModelPatchingType.Selectively), Times.Once);
            viewModelPartPatcher
            .Verify(patcher => patcher.Patch(MonoCecilAssembly.Object, ViewModelBase, viewModel2, ViewModelPatchingType.All), Times.Once);
            viewModelPartPatcher
            .Verify(patcher => patcher.Patch(MonoCecilAssembly.Object, ViewModelBase, viewModel3, ViewModelPatchingType.All), Times.Once);
        }
Example #50
0
 internal static Step Step(object setup, Times expectedCalls)
 {
     EnsureActiveSequence("InSequence()");
     return Instance.CreateStep(setup, expectedCalls);
 }
Example #51
0
	private void ParseTimes (Match match, Times times, Times previousTimes, ParsingProperties properties) {
		ParseStartTime(match, times, previousTimes, properties);
		ParseEndTime(match, times, previousTimes, properties);
	}