Пример #1
0
        private static void AssertPathIsNotRootedAndExists(string path)
        {
            Assertions.AssertNotEmpty(path, "path");

            if (Path.IsPathRooted(path))
            {
                throw new IOException(Properties.Resources.FilePathIsRootError);
            }

            string localPath = GetLocalPathForRelative(path);

            if (!File.Exists(localPath))
            {
                throw new FileNotFoundException(string.Format(Properties.Resources.FilePathNotFoundError, path));
            }
        }
Пример #2
0
        private void Check10LangLinkElements()
        {
            const int number = 10;

            IList <IWebElement> allElements = _langLinksTextXPath;
            IList <String>      value       = new List <String>();

            foreach (IWebElement element in allElements)
            {
                value.Add(element.Text);
                Console.WriteLine("AA" + element.Text + " - OK!");
            }

            Assertions.AssertIt(() => Assert.AreEqual(value.Count, number));
            Console.WriteLine(number + " language link elements are presented.");
        }
Пример #3
0
        public void Test()
        {
            var expectedTransactionName = @"WebTransaction/WebAPI/My/CustomAttributesKeyNull";

            var unexpectedTransactionEventAttributes = new List <string>
            {
                "keywithnullvalue"
            };

            var transactionEvent = _fixture.AgentLog.TryGetTransactionEvent(expectedTransactionName);

            NrAssert.Multiple
            (
                () => Assertions.TransactionEventDoesNotHaveAttributes(unexpectedTransactionEventAttributes, TransactionEventAttributeType.User, transactionEvent)
            );
        }
Пример #4
0
        public void Test()
        {
            var expectedMetrics = new List <Assertions.ExpectedMetric>
            {
                new Assertions.ExpectedMetric {
                    metricName = @"CPU/User Time"
                },
                new Assertions.ExpectedMetric {
                    metricName = @"CPU/User/Utilization"
                }
            };

            var metrics = _fixture.AgentLog.GetMetrics().ToList();

            Assertions.MetricsExist(expectedMetrics, metrics);
        }
        public void RegisterCustomExpectation(
            string keyForMessage,
            Func <IMockSpan, string> actual,
            string expected)
        {
            Assertions.Add(span =>
            {
                var actualValue = actual(span);
                if (expected != null && actualValue != expected)
                {
                    return(FailureMessage(name: keyForMessage, actual: actualValue, expected: expected));
                }

                return(null);
            });
        }
        void ISettingsServiceInternal.SetSettings(IEnumerable <KeyValuePair <SettingKey, SettingItem> > values)
        {
            Assertions.AssertNotNull(values, "values");

            IEnumerable <SettingKey> savedSettings = null;

            lock (SyncRoot)
            {
                savedSettings = SaveSettings(values);
            }

            if (savedSettings != null && savedSettings.Any())
            {
                OnSettingChanged(new SettingChangedEventArgs(savedSettings));
            }
        }
Пример #7
0
        /// <summary>
        /// Helper method: Sets attribute value in the attribute collection
        /// </summary>
        /// <param name="attName">attribute name</param>
        /// <param name="attValue">attribute value (if null, we will remove the attribute from the collection)</param>
        /// <param name="attributes">collection of attribute</param>
        /// <exception cref="ArgumentNullException">If some of the params is null</exception>
        internal static void SetAttValue(string attName, object attValue, ICollection <ConnectorAttribute> attributes)
        {
            Assertions.NullCheck(attName, "attName");
            Assertions.NullCheck(attributes, "attributes");

            ConnectorAttribute attribute = ConnectorAttributeUtil.Find(attName, attributes);

            if (attribute != null)
            {
                attributes.Remove(attribute);
            }
            if (attValue != null)
            {
                attributes.Add(ConnectorAttributeBuilder.Build(attName, new object[] { attValue }));
            }
        }
Пример #8
0
        /// <summary>
        /// This method tries to get name and value from <see cref="PSMemberInfo"/> and
        /// creates <see cref="ConnectorAttribute"/> out of it
        /// </summary>
        /// <param name="info">PSMemberInfo to get the data from</param>
        /// <returns>Created ConnectorAttribute or null if not possible to create it</returns>
        internal static ConnectorAttribute GetAsAttribute(PSMemberInfo info)
        {
            Assertions.NullCheck(info, "param");
            if (info.Value != null)
            {
                string value = info.Value.ToString();

                // TODO: add type recognition, currently only string is supported
                if (value != info.Value.GetType().ToString() && !string.IsNullOrEmpty(value))
                {
                    return(ConnectorAttributeBuilder.Build(info.Name, value));
                }
            }

            return(null);
        }
Пример #9
0
        protected T ExpectMsgPf <T>(TimeSpan?timeout, string hint, Func <object, T> function)
        {
            MessageEnvelope envelope;
            var             success = TryReceiveOne(out envelope, timeout);

            if (!success)
            {
                Assertions.Fail(string.Format("expected message of type {0} but timed out after {1}", typeof(T), GetTimeoutOrDefault(timeout)));
            }
            var message = envelope.Message;

            Assertions.AssertTrue(message != null, string.Format("expected {0} but got null message", hint));
            //TODO: Check next line.
            Assertions.AssertTrue(function.GetMethodInfo().GetParameters().Any(x => x.ParameterType.IsInstanceOfType(message)), string.Format("expected {0} but got {1} instead", hint, message));
            return(function.Invoke(message));
        }
Пример #10
0
        public void AddBotRuntimeTelemetryEnabled()
        {
            // Setup
            IServiceCollection services = new ServiceCollection();

            var telemetrySettings = new TelemetrySettings()
            {
                Options = new ApplicationInsightsServiceOptions()
                {
                    ConnectionString = Guid.NewGuid().ToString()
                }
            };
            IConfiguration configuration = new ConfigurationBuilder().AddRuntimeSettings(new RuntimeSettings()
            {
                Telemetry = telemetrySettings
            }).Build();

            services.AddTransient <IHttpContextAccessor, HttpContextAccessor>();
            services.AddTransient <IHostingEnvironment, TestHostingEnvironment>();

            // Test
            services.AddBotRuntimeTelemetry(configuration);

            // Assert
            IServiceProvider provider = services.BuildServiceProvider();

            Assertions.AssertService <IMiddleware, TelemetryInitializerMiddleware>(services, provider, ServiceLifetime.Singleton);

            Assertions.AssertService <ITelemetryInitializer, OperationCorrelationTelemetryInitializer>(
                services,
                provider,
                ServiceLifetime.Singleton,
                searchOptions: ServiceDescriptorSearchOptions
                .SearchByImplementationType <OperationCorrelationTelemetryInitializer>());

            Assertions.AssertService <ITelemetryInitializer, TelemetryBotIdInitializer>(
                services,
                provider,
                ServiceLifetime.Singleton,
                searchOptions: ServiceDescriptorSearchOptions
                .SearchByImplementationType <TelemetryBotIdInitializer>());

            Assertions.AssertService <IBotTelemetryClient, BotTelemetryClient>(
                services,
                provider,
                ServiceLifetime.Singleton);
        }
        public void PersonsController_Get_Returns_OKResponseCode(PersonSearchCriteria personSearchCriteria)
        {
            #region Arrange
            SetupUserIdentity();
            SetupPersonRepository(personSearchCriteria, out Mock <IPersonRepository> personRepository, out IPaginatedList <TbPerson> expected);

            var httpRequest = new HttpRequestMessage(new HttpMethod(AppSettings.HTTPGET), $"{AppSettings.BASEURL}{RouteHelper.PersonRoutePrefix}/{personSearchCriteria}");

            PersonsController personsController = CreatePersonsController(httpRequest, personRepository.Object);

            #endregion

            #region Act

            var response = personsController.Search(personSearchCriteria);
            //var response = personsController.Get(It.IsAny<int>());
            var contentResult = response as NegotiatedContentResult <ResponsePaginatedCollection <Person> >;


            #endregion

            #region Assert

            #region Expected Data

            var expectedPerson = new Person()
            {
                PersonId    = (personSearchCriteria.PersonId) == 0 ? userIdentity.UserId : 123,
                FirstName   = "John",
                LastName    = "Smith",
                DisplayName = "John Smith"
            };

            #endregion

            Assertions.AssertOkResponse(contentResult);

            var personsData = contentResult.Content.results;
            for (int i = 0; i <= personsData.Count - 1; i++)
            {
                //Data
                var actualPerson = personsData[i].data;
                Assertions.AssertData(expectedPerson, actualPerson);
            }

            #endregion
        }
Пример #12
0
        public void TypeFinder_Second_Call_Returns_Same_Values_As_First()
        {
            // It can take low-order hundreds of milliseconds to return all types. This
            // doesn't affect real-world use where searches for web API controllers are
            // seldom made but it hammers unit tests.
            //
            // To that end the type finder implementation is at liberty to cache results
            // for a short period of time. This just checks that two calls made quickly
            // after each other contain the same types.

            var typeFinder = Factory.Resolve <ITypeFinder>();

            var results1 = typeFinder.GetAllTypes().ToArray();
            var results2 = typeFinder.GetAllTypes().ToArray();

            Assertions.AreContentsSameUnordered(results1, results2);
        }
Пример #13
0
        public void Test()
        {
            var expectedMetrics = new List <Assertions.ExpectedMetric>
            {
                //transactions
                new Assertions.ExpectedMetric {
                    metricName = @"WebTransaction/MVC/HomeController/Index", CallCountAllHarvests = 1
                },
                new Assertions.ExpectedMetric {
                    metricName = @"WebTransaction/Custom/MyCustomDeleteMetricName", CallCountAllHarvests = 1
                },
                new Assertions.ExpectedMetric {
                    metricName = @"WebTransaction/MVC/RejitController/GetDeleteFile", CallCountAllHarvests = 1
                },

                // Unscoped
                new Assertions.ExpectedMetric {
                    metricName = @"DotNet/HomeController/Index", CallCountAllHarvests = 1
                },
                new Assertions.ExpectedMetric {
                    metricName = @"Custom/MyCustomDeleteMetricName", CallCountAllHarvests = 1
                },
                new Assertions.ExpectedMetric {
                    metricName = @"DotNet/RejitController/GetDeleteFile", CallCountAllHarvests = 2
                },

                // Scoped
                new Assertions.ExpectedMetric {
                    metricName = @"DotNet/HomeController/Index", metricScope = "WebTransaction/MVC/HomeController/Index", CallCountAllHarvests = 1
                },
                new Assertions.ExpectedMetric {
                    metricName = @"Custom/MyCustomDeleteMetricName", metricScope = "WebTransaction/Custom/MyCustomDeleteMetricName", CallCountAllHarvests = 1
                },
                new Assertions.ExpectedMetric {
                    metricName = @"DotNet/RejitController/GetDeleteFile", metricScope = "WebTransaction/MVC/RejitController/GetDeleteFile", CallCountAllHarvests = 1
                }
            };

            var metrics = CommonUtils.GetMetrics(_fixture.AgentLog);

            _fixture.TestLogger?.WriteLine(_fixture.AgentLog.GetFullLogAsString());

            NrAssert.Multiple(
                () => Assertions.MetricsExist(expectedMetrics, metrics)
                );
        }
        public async Task AddBotRuntimeSkills(object settings, string appId, Type exceptionType)
        {
            // Setup
            IServiceCollection services = new ServiceCollection();

            services.AddSingleton <IStorage, MemoryStorage>();
            services.AddSingleton <SkillConversationIdFactoryBase, SkillConversationIdFactory>();
            services.AddSingleton(sp => BotFrameworkAuthenticationFactory.Create());
            services.AddSingleton <BotAdapter, CloudAdapter>();
            services.AddSingleton <IBot, ActivityHandler>();

            var            skillSettings = settings as SkillSettings;
            IConfiguration configuration = new ConfigurationBuilder().AddRuntimeSettings(new RuntimeSettings()
            {
                Skills = skillSettings
            }).Build();

            // Test
            services.AddBotRuntimeSkills(configuration);

            // Assert
            var provider = services.BuildServiceProvider();

            Assertions.AssertService <SkillConversationIdFactoryBase, SkillConversationIdFactory>(services, provider, ServiceLifetime.Singleton);
            Assertions.AssertService <ChannelServiceHandlerBase, CloudSkillHandler>(services, provider, ServiceLifetime.Singleton);
            Assertions.AssertService <AuthenticationConfiguration>(
                services,
                provider,
                ServiceLifetime.Singleton,
                async authConfig =>
            {
                var versionClaim = new Claim(AuthenticationConstants.VersionClaim, "1.0");
                var appIdClaim   = new Claim(AuthenticationConstants.AppIdClaim, appId);

                if (exceptionType == null)
                {
                    await authConfig.ClaimsValidator.ValidateClaimsAsync(new Claim[] { versionClaim, appIdClaim });
                }
                else
                {
                    await Assert.ThrowsAsync(exceptionType, () => authConfig.ClaimsValidator.ValidateClaimsAsync(new Claim[] { versionClaim, appIdClaim }));
                }
            });

            await Task.CompletedTask;
        }
Пример #15
0
        public void Function()
        {
            CodeRootMap map  = new CodeRootMap();
            CodeRoot    root = CreateFunctionAndClass("i");

            map.AddCodeRoot(root, Version.User);
            map.AddCodeRoot(root, Version.NewGen);
            map.AddCodeRoot(root, Version.PrevGen);

            string result = map.GetMergedCodeRoot().ToString();

            Assert.That(result, Is.EqualTo(root.ToString()));
            Assertions.StringContains(result, "class Class1");
            Assertions.StringContains(result, "namespace ArchAngel.Tests");
            Assertions.StringContains(result, "public int GetVal(int i)");
            Assertions.StringContains(result, "{ return 5; }");
        }
Пример #16
0
        public void TestGameOverWithSunkFleet()
        {
            var game = new BattleshipGameBoard()
                       .PlaceShip(new Destroyer(), 0, 0, Facing.Horizontal)
                       .PlaceShip(new Carrier(), 1, 1, Facing.Vertical);

            game.Attack(0, 0);
            game.Attack(1, 0);

            game.Attack(1, 1);
            game.Attack(1, 2);
            game.Attack(1, 3);
            game.Attack(1, 4);
            game.Attack(1, 5);

            Assertions.AssertThat(game.GameOver).IsTrue();
        }
        public void can_get_by_id()
        {
            GenerateDatabaseSchema();

            Person p = new Person()
            {
                Id = 1, Forename = "Jimmy", Surname = "Choo", BirthdayDay = 1, BirthdayMonth = 1
            };

            AddPersonToDatabase(p);

            IPersonRepository repository     = new PersonRepository();
            Person            databasePerson = repository.GetById(p.Id);

            Assert.IsNotNull(databasePerson, "Person not loaded from Database");
            Assertions.AssertPeopleAreEqual(p, databasePerson);
        }
Пример #18
0
        public void GetCopy1()
        {
            // given
            Series series1 = TestObjects.GetSeries();
            Series series2 = TestObjects.GetSeries(new List <double>()
            {
                -1, 0, 1
            });

            // when
            Series result1 = SeriesAssist.GetCopy(series1, 0, false);
            Series result2 = SeriesAssist.GetCopy(series2);

            // then
            Assertions.SameValues(series1, result1);
            Assertions.SameValues(series2, result2);
        }
Пример #19
0
        public void CedantsController_GetParentCedent_OKResponse(CedantsSearchCriteria criteria)
        {
            #region Arrange

            SetupUserIdentity();
            SetupCedantRepository(out Mock <ICedantRepository> cedantRepository, criteria);
            var httpRequest = new HttpRequestMessage(new HttpMethod(AppSettings.HTTPPOST), $"{AppSettings.BASEURL}{RouteHelper.CedantsRoutePrefix}");
            CedantsController cedantsController = CreateCedantController(httpRequest, cedantRepository.Object);
            #endregion

            #region Act

            #endregion

            #region Expected Data

            var expectedCedants = new Cedant()
            {
                Cedantid         = 56495,
                Name             = "Starr Indemnity & Liability Company",
                Cedantgroupid    = 1019169,
                Cedantgroupname  = "Starr International Company, Inc.",
                Locationid       = 244894,
                Locationaddress  = "8401 N Central Expressway",
                Locationcity     = "Dallas",
                Locationstate    = "TX",
                Locationpostcode = null,
                Country          = "United States"
            };

            #endregion

            #region Assert

            if (cedantsController.Get(criteria.CedantName) is NegotiatedContentResult <ResponseCollection <Cedant> > contentResult)
            {
                Assertions.AssertOkResponse(contentResult);
                for (int i = 0; i <= contentResult.Content.results.Count - 1; i++)
                {
                    Assertions.AssertData(expectedCedants, contentResult.Content.results[i].data);
                    Assert.IsEmpty(contentResult.Content.results[i].messages);
                }
            }

            #endregion
        }
Пример #20
0
        public void Generalized()
        {
            // given
            IList <double> list1 = new List <double>()
            {
                1, 2, 3, 4, 5
            };
            IList <double> list2 = new List <double>()
            {
                3, 7, 11, 23, 111
            };
            IList <double> list3 = new List <double>()
            {
                -2, 0, 1, 5
            };
            IList <IList <double> > list4 = new List <IList <double> >()
            {
                list1, new List <double>()
                {
                    2, 1
                }
            };
            int            rank1     = 2;
            int            rank2     = 3;
            int            rank3     = 4;
            double         expected1 = Math.Sqrt(11.0);
            double         expected2 = Mathematics.Root(1381499.0 / 5.0, rank2);
            double         expected3 = Mathematics.Root(2217.0 / 2.0, rank3) - (Math.Abs(list3.Min()) + 1.0);
            IList <double> expected4 = new List <double>()
            {
                expected1, Math.Sqrt(5.0 / 2.0)
            };

            // when
            double         result1 = Averages.Generalized(list1, StandardMeanVariants.Straight, rank1).Value;
            double         result2 = Averages.Generalized(list2, StandardMeanVariants.Straight, rank2).Value;
            double         result3 = Averages.Generalized(list3, StandardMeanVariants.Offset, rank3).Value;
            IList <double> result4 = Averages.Generalized(list4, StandardMeanVariants.Straight, rank1);

            // then
            Assert.AreEqual(expected1, result1, Assertions.IBM_FLOAT_SURROUNDING);
            Assert.AreEqual(expected2, result2, Assertions.IBM_FLOAT_SURROUNDING);
            Assert.AreEqual(expected3, result3, Assertions.IBM_FLOAT_SURROUNDING);
            Assertions.SameValues(expected4, result4);
        }
        public void Test()
        {
            var catResponseHeader = _responseHeaders.GetValues(@"X-NewRelic-App-Data")?.FirstOrDefault();

            Assert.NotNull(catResponseHeader);

            var catResponseData = HeaderEncoder.DecodeAndDeserialize <CrossApplicationResponseData>(catResponseHeader, HeaderEncoder.IntegrationTestEncodingKey);

            var transactionSample        = _fixture.AgentLog.TryGetTransactionSample("WebTransaction/MVC/DefaultController/Index");
            var transactionEventIndex    = _fixture.AgentLog.TryGetTransactionEvent("WebTransaction/MVC/DefaultController/Index");
            var transactionEventRedirect = _fixture.AgentLog.TryGetTransactionEvent("WebTransaction/MVC/DefaultController/DoRedirect");
            var metrics = _fixture.AgentLog.GetMetrics();

            NrAssert.Multiple
            (
                () => Assert.NotNull(transactionSample),
                () => Assert.NotNull(transactionEventRedirect),
                () => Assert.NotNull(transactionEventIndex)
            );

            NrAssert.Multiple
            (
                () => Assert.Equal(_fixture.AgentLog.GetCrossProcessId(), catResponseData.CrossProcessId),
                () => Assert.Equal("WebTransaction/MVC/DefaultController/Index", catResponseData.TransactionName),
                () => Assert.True(catResponseData.QueueTimeInSeconds >= 0),
                () => Assert.True(catResponseData.ResponseTimeInSeconds >= 0),
                () => Assert.Equal(-1, catResponseData.ContentLength),
                () => Assert.NotNull(catResponseData.TransactionGuid),
                () => Assert.False(catResponseData.Unused),

                // Trace attributes
                () => Assertions.TransactionTraceHasAttributes(Expectations.ExpectedTransactionTraceIntrinsicAttributesCatEnabled, TransactionTraceAttributeType.Intrinsic, transactionSample),
                () => Assertions.TransactionTraceDoesNotHaveAttributes(Expectations.UnexpectedTransactionTraceIntrinsicAttributesCatEnabled, TransactionTraceAttributeType.Intrinsic, transactionSample),

                // transactionEventIndex attributes
                () => Assertions.TransactionEventHasAttributes(Expectations.ExpectedTransactionEventIntrinsicAttributesCatEnabled, TransactionEventAttributeType.Intrinsic, transactionEventIndex),
                () => Assertions.TransactionEventDoesNotHaveAttributes(Expectations.UnexpectedTransactionEventIntrinsicAttributesCatEnabled, TransactionEventAttributeType.Intrinsic, transactionEventIndex),

                // transactionEventRedirect attributes
                () => Assertions.TransactionEventHasAttributes(Expectations.ExpectedTransactionEventIntrinsicAttributesCatEnabled, TransactionEventAttributeType.Intrinsic, transactionEventRedirect),
                () => Assertions.TransactionEventDoesNotHaveAttributes(Expectations.UnexpectedTransactionEventIntrinsicAttributesCatEnabled, TransactionEventAttributeType.Intrinsic, transactionEventRedirect),

                () => Assertions.MetricsExist(Expectations.ExpectedMetricsCatEnabled, metrics)
            );
        }
        public void PersonManager_DeletePerson_RemovesFromRepository()
        {
            //Arrange
            FakePersonRepository mockRepository = new FakePersonRepository();
            PersonManager        manager        = new PersonManager(mockRepository);

            Person p = new Person()
            {
                Id = 1, Forename = "Ted", Surname = "Smith", BirthdayDay = 1, BirthdayMonth = 12
            };

            //Act
            manager.DeletePerson(p);

            //Assert
            Assert.IsNotNull(mockRepository.DeletedPerson, "Person not removed from repository");
            Assertions.AssertPeopleAreEqual(p, mockRepository.DeletedPerson);
        }
        public async Task Test()
        {
            var server          = new NetworkedMultiplayerENet();
            var boolEvent       = AwaitResponse(LanBoolEvent, (bool payload) => payload);
            var stringEvent     = AwaitResponse(LanStringEvent, (string payload) => payload == "true");
            var intEvent        = AwaitResponse(LanIntEvent, (int payload) => payload == 1);
            var floatEvent      = AwaitResponse(LanFloatEvent, (float payload) => payload == 1.0f);
            var serializedEvent =
                AwaitResponse(LanSerializedEvent, (SerializedClass payload) => payload.Field == "true");
            var error = server.CreateClient("127.0.0.1", ServerPort);

            Assertions.AssertTrue(error == Error.Ok, "Connection without errors");
            GetTree().NetworkPeer = server;
            var results = await Task.WhenAll(
                boolEvent, stringEvent, intEvent, floatEvent, serializedEvent);

            Assertions.AssertTrue(results.All(result => result), "All Lan events done");
        }
Пример #24
0
        public void Test()
        {
            var metrics = Fixture.AgentLog.GetMetrics().ToList();

            var metricNames = metrics.Select(x => x.MetricSpec.Name).OrderBy(x => x).ToList();

            Assert.NotNull(metrics);

            NrAssert.Multiple(
                () => Assertions.MetricsExist(_generalMetrics, metrics),
                () => Assertions.MetricsExist(_expectedMetrics_Async_AwaitedAsync, metrics),
                () => Assertions.MetricsExist(_expectedMetrics_Async_Sync, metrics),
                () => Assertions.MetricsExist(_expectedMetrics_Sync_AwaitedAsync, metrics),
                () => Assertions.MetricsExist(_expectedMetrics_Sync_Sync, metrics),
                () => Assert.Empty(Fixture.AgentLog.GetErrorTraces()),
                () => Assert.Empty(Fixture.AgentLog.GetErrorEvents())
                );
        }
Пример #25
0
        public void ExpectedMetrics()
        {
            var expectedMetrics = new List <Assertions.ExpectedMetric>
            {
                new Assertions.ExpectedMetric()
                {
                    callCount = 1, metricName = "Supportability/ApiInvocation/TraceMetadata"
                },
                new Assertions.ExpectedMetric()
                {
                    callCount = 1, metricName = "Supportability/ApiInvocation/GetLinkingMetadata"
                }
            };

            var actualMetrics = Fixture.AgentLog.GetMetrics().ToList();

            Assertions.MetricsExist(expectedMetrics, actualMetrics);
        }
Пример #26
0
        /// <summary>
        /// Manually closes the specified service instance. This method is a counterpart to GetServiceInstance().
        /// </summary>
        /// <param name="serviceInstance">The service instance to close.</param>
        public static void CloseServiceInstance(object serviceInstance)
        {
            Assertions.AssertNotNull(serviceInstance, "serviceInstance");

            ICommunicationObject obj = serviceInstance as ICommunicationObject;

            if (obj == null)
            {
                throw new ArgumentException(Properties.Resources.ServiceFactoryInstanceIsNotAServiceObject);
            }
            // Pessimistic: Don't continue if this object is faulted (don't throw an exception here)
            if (obj.State == CommunicationState.Faulted)
            {
                return;
            }

            obj.Close();
        }
Пример #27
0
        public void Reciprocal()
        {
            // given
            IList <double> list1 = new List <double>()
            {
                1.0, 2.0, 3.0, 4.0, Math.Sqrt(5.0 / 6.0)
            };
            IList <double> expected1 = new List <double>()
            {
                1.0 / list1[0], 1.0 / list1[1], 1.0 / list1[2], 1.0 / list1[3], 1.0 / list1[4]
            };

            // when
            Lists.Reciprocal(list1);

            // then
            Assertions.SameValues(list1, expected1);
        }
Пример #28
0
        /// <summary>
        /// Helper method - Replaces specified collection Items
        /// </summary>
        /// <param name="col">Input <see cref="ArrayList"/> to be searched for replacement</param>
        /// <param name="map">Replace mappings</param>
        /// <returns>Replaced <see cref="ArrayList"/></returns>
        /// <exception cref="ArgumentNullException">If some of the params is null</exception>
        internal static ICollection <string> FilterReplace(ICollection <string> col, IDictionary <string, string> map)
        {
            Assertions.NullCheck(col, "col");
            Assertions.NullCheck(map, "map");

            ICollection <string> newcol = CollectionUtil.NewList(col);

            foreach (KeyValuePair <string, string> pair in map)
            {
                if (newcol.Contains(pair.Key))
                {
                    newcol.Remove(pair.Key);
                    newcol.Add(pair.Value);
                }
            }

            return(newcol);
        }
Пример #29
0
        public void TestApplyDamage()
        {
            var ship = new BaseShip(3);

            Assertions.AssertThat(ship.Damage).ContainsExactly(false, false, false);

            ship.ApplyDamage(0);
            Assertions.AssertThat(ship.Damage).ContainsExactly(true, false, false);
            Assertions.AssertThat(ship.IsSunk).IsFalse();

            ship.ApplyDamage(2);
            Assertions.AssertThat(ship.Damage).ContainsExactly(true, false, true);
            Assertions.AssertThat(ship.IsSunk).IsFalse();

            ship.ApplyDamage(1);
            Assertions.AssertThat(ship.Damage).ContainsExactly(true, true, true);
            Assertions.AssertThat(ship.IsSunk).IsTrue();
        }
Пример #30
0
        public void InterfaceMethod()
        {
            CodeRoot root = CreateInterfaceAndMethod("i");

            CodeRootMap map = new CodeRootMap();

            map.AddCodeRoot(root, Version.User);
            map.AddCodeRoot(root, Version.NewGen);
            map.AddCodeRoot(root, Version.PrevGen);

            string result = map.GetMergedCodeRoot().ToString();

            Assert.That(result, Is.EqualTo(root.ToString()));
            Assertions.StringContains(result, "public interface Interface1");
            Assertions.StringContains(result, "[Serializable(true)]");
            Assertions.StringContains(result, "namespace ArchAngel.Tests");
            Assertions.StringContains(result, "int Method1 (int i);");
        }