Пример #1
0
        public static Contact UpdateProperty(this Contact contact, string alias, dynamic value)
        {
            var props = contact.GetProperties().ToList();
            var prop  = props.Where(x => x.alias.ToString().ToLower() == alias.ToLower()).FirstOrDefault();

            if (prop == null)
            {
                var pipelineConfig = PipelineConfig.GetConfig().AppSettings;
                var docType        = ApplicationContext.Current.Services.ContentTypeService.GetContentType(pipelineConfig.ContactDocTypes);
                var typeId         = docType.PropertyTypes.FirstOrDefault(x => x.Alias.ToLower() == alias.ToLower()).Id;

                var newProp = new
                {
                    alias = alias,
                    value = value,
                    id    = typeId
                };
                props.Add(newProp);
            }
            else
            {
                props.Where(x => x.alias.ToString().ToLower() == alias.ToLower()).FirstOrDefault().value = value;
            }

            contact.CustomProps = Newtonsoft.Json.JsonConvert.SerializeObject(props);
            return(contact);
        }
Пример #2
0
        public void WhenStartingAndEndingSessionAndDisposingPipeline_ThenSessionNotAborted()
        {
            using (var pipeline = PipelineConfig.CreatePipeline())
            {
                pipeline.StartSession();
                Assert.True(pipeline.SessionStarted);
                Assert.False(pipeline.SessionAborted);
                pipeline.EndSession();
                Assert.False(pipeline.SessionStarted);
                Assert.False(pipeline.SessionAborted);
            }

            Assert.Equal(8, HistoryOfVisits.Count);

            Assert.Collection(HistoryOfVisits,
                              x => AssertForVisitor.CalledStartSession(VisitorA, x),
                              x => AssertForVisitor.CalledStartSession(VisitorB, x),
                              x => AssertForVisitor.CalledPostStartSession(VisitorB, x),
                              x => AssertForVisitor.CalledPostStartSession(VisitorA, x),
                              x => AssertForVisitor.CalledEndSession(VisitorA, x),
                              x => AssertForVisitor.CalledEndSession(VisitorB, x),
                              x => AssertForVisitor.CalledPostEndSession(VisitorB, x),
                              x => AssertForVisitor.CalledPostEndSession(VisitorA, x)
                              );
        }
        /// <summary>
        /// Get all the properties.
        /// </summary>
        /// <param name="data"></param>
        /// <param name="config">The configuration to use</param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException">
        /// Thrown if the supplied flow data is null.
        /// </exception>
        protected virtual Dictionary <string, object> GetAllProperties(
            IFlowData data,
            PipelineConfig config)
        {
            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }
            if (config == null)
            {
                throw new ArgumentNullException(nameof(config));
            }

            Dictionary <string, object> allProperties = new Dictionary <string, object>();

            foreach (var element in data.ElementDataAsDictionary().Where(elementData =>
                                                                         _elementExclusionList.Contains(elementData.Key) == false))
            {
                if (allProperties.ContainsKey(element.Key.ToLowerInvariant()) == false)
                {
                    var values = GetValues(data,
                                           element.Key.ToLowerInvariant(),
                                           (element.Value as IElementData).AsDictionary(),
                                           config);
                    allProperties.Add(element.Key.ToLowerInvariant(), values);
                }
            }

            return(allProperties);
        }
        /// <summary>
        /// Get the names and values for all the JSON properties required
        /// to represent the given source data.
        /// The method adds meta-properties as required such as
        /// *nullreason, *delayexecution, etc.
        /// </summary>
        /// <param name="flowData">
        /// The <see cref="IFlowData"/> for the current request.
        /// </param>
        /// <param name="dataPath">
        /// The . separated name of the container that the supplied
        /// data will be added to.
        /// For example, 'location' or 'devices.profiles'
        /// </param>
        /// <param name="sourceData">
        /// The source data to use when populating the result.
        /// </param>
        /// <param name="config">
        /// The configuration to use.
        /// </param>
        /// <returns>
        /// A new dictionary with string keys and object values.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// Thrown if required parameters are null
        /// </exception>
        protected virtual Dictionary <string, object> GetValues(
            IFlowData flowData,
            string dataPath,
            IReadOnlyDictionary <string, object> sourceData,
            PipelineConfig config)
        {
            if (dataPath == null)
            {
                throw new ArgumentNullException(nameof(dataPath));
            }
            if (sourceData == null)
            {
                throw new ArgumentNullException(nameof(sourceData));
            }
            if (config == null)
            {
                throw new ArgumentNullException(nameof(config));
            }

            var values = new Dictionary <string, object>();

            foreach (var value in sourceData)
            {
                AddJsonValuesForProperty(flowData, values, dataPath,
                                         value.Key, value.Value, config, false);
            }
            return(values);
        }
Пример #5
0
        public Log4NetPipeline(string repository = null)
        {
            var logRepository = LogManager.CreateRepository(Assembly.GetEntryAssembly(), typeof(log4net.Repository.Hierarchy.Hierarchy));
            var log4netConfig = new XmlDocument();

            log4netConfig.Load(File.OpenRead("log4net.config"));

            log4net.Config.XmlConfigurator.Configure(logRepository, log4netConfig["log4net"]);

            _log = LogManager.GetLogger(GetType());

            Configuration = new PipelineConfig(c => c
                                               .UseData(new Log4NetPipelineData {
                Log = _log
            })
                                               .AutoRaiseEvents(false)
                                               .Stages()
                                               .RegisterStage("Log")
                                               .ForEvent <OnDebug>()
                                               .ForEvent <OnInfo>()
                                               .ForEvent <OnFatal>()
                                               .ForEvent <OnError>()
                                               .ForEvent <OnWarning>()
                                               .Observers()
                                               .RegisterObserver <LogObserver>()
                                               );
        }
        public void Should_be_able_to_perform_full_config()
        {
            var config = new PipelineConfig() as IPipelineConfig;

            config
            .Name("Pipeline A")
            .AutoRaiseEvents(false)
            .UseData(new PipelineData())
            .Stages()
            .RegisterStage("Stage 1")
            .ForEvent <OnParseEvent>()
            .Observers()
            .RegisterObserver <ParserObserver>();

            var configAccess = config as IPipelineConfigAccess;

            Assert.AreEqual(configAccess.Name, "Pipeline A");
            Assert.AreEqual(configAccess.AutoRaiseEvents, false);
            Assert.IsNotNull(configAccess.Data);

            Assert.IsNotNull(configAccess.Stages[0]);
            Assert.AreEqual(configAccess.Stages[0].Name, "Stage 1");
            Assert.IsNotNull(configAccess.Stages[0].Events[0]);
            Assert.AreEqual(configAccess.Stages[0].Events[0].GetType(), typeof(OnParseEvent));
            Assert.IsNotNull(configAccess.Observers[0]);
            Assert.AreEqual(configAccess.Observers[0].GetType(), typeof(ParserObserver));
        }
Пример #7
0
        public void WhenNotStartingSessionAndDisposingPipeline_ThenNoSessionStartedOrAborted()
        {
            using (var pipeline = PipelineConfig.CreatePipeline())
            {
                // do nothing
            };

            Assert.Equal(0, HistoryOfVisits.Count);
        }
Пример #8
0
        public void WhenStartingSessionAndDisposingPipeline_ThenSessionAborted()
        {
            using (var pipeline = PipelineConfig.CreatePipeline())
            {
                pipeline.StartSession();
            }

            AssertSessionStartedAndAborted();
        }
        // method to get config values needed by the UI
        public Dictionary <string, string> GetConfig()
        {
            var settings = PipelineConfig.GetConfig().AppSettings;
            var config   = new Dictionary <string, string>();

            config["UseBoard"] = settings.UseBoard ? "true" : "false";

            return(config);
        }
        public void WhenCallingRunCommandWithUndefinedCommandName_ThenNoCommandCalled()
        {
            using (var pipeline = PipelineConfig.CreatePipeline())
            {
                pipeline.RunCommand("SomeUndefinedCommandName", "Test");
            }

            Assert.Equal(0, HistoryOfVisits.Count);
        }
Пример #11
0
        public void WhenAbortingSessionWithoutStartingIt_ThenNoSessionCommandsInvoked()
        {
            using (var pipeline = PipelineConfig.CreatePipeline())
            {
                pipeline.AbortSession();
                Assert.False(pipeline.SessionStarted);
                Assert.False(pipeline.SessionAborted);
            }

            Assert.Equal(0, HistoryOfVisits.Count);
        }
Пример #12
0
        private string TaskRow(Task task)
        {
            string notificationEmailRow = PipelineConfig.GetConfig().DigestRow.InnerHtml;
            string baseUrl = Request.Url.GetLeftPart(UriPartial.Authority) + "/umbraco#/pipelineCrm/";

            return(notificationEmailRow
                   .Replace("{0}", baseUrl + task.ParentId.ToString())
                   .Replace("{1}", !string.IsNullOrEmpty(task.Type) ? task.Type + ": " : "")
                   .Replace("{2}", task.Description)
                   .Replace("{3}", "In " + task.ParentName + ", due" + task.DateDue.ToString("dd MMM yyyy")));
        }
Пример #13
0
        private bool PipelineIsUsingResizer(PipelineConfig config)
        {
            foreach (string key in config.ModifiedQueryString.Keys)
            {
                if (config.SupportedQuerystringKeys.Contains(key))
                {
                    return(true);
                }
            }

            return(false);
        }
Пример #14
0
        public PagedSegments GetPagedSegments(int pageNumber, string sortColumn, string sortOrder, string searchTerm, int typeId)
        {
            int itemsPerPage = PipelineConfig.GetConfig().AppSettings.PageSize;
            var items        = new List <Segment>();
            var SegmentType  = typeof(Segment);

            var query = new Sql().Select("*").From("pipelineSegment");

            if (typeId == 0)
            {
                query.Append(" where Archived=0 ", typeId);
            }
            else if (typeId == -1)
            {
                query.Append(" where Archived=1 ", typeId);
            }
            else if (typeId == -2)
            {
                query.Append(" where TypeId=0 and Archived=0 ", typeId);
            }
            else
            {
                query.Append(" where TypeId=@0 and Archived=0 ", typeId);
            }

            if (!string.IsNullOrEmpty(searchTerm))
            {
                query.Append(" and (Name like @0) ", "%" + searchTerm + "%");
            }

            if (!string.IsNullOrEmpty(sortColumn) && !string.IsNullOrEmpty(sortOrder))
            {
                query.OrderBy(sortColumn + " " + sortOrder);
            }
            else
            {
                query.OrderBy("Name asc");
            }

            var p = DbService.db().Page <Segment>(pageNumber, itemsPerPage, query);

            return(new PagedSegments
            {
                TotalPages = p.TotalPages,
                TotalItems = p.TotalItems,
                ItemsPerPage = p.ItemsPerPage,
                CurrentPage = p.CurrentPage,
                Segments = p.Items.ToList()
            });
        }
Пример #15
0
        protected IPipelineConfig ConfigurePipeline()
        {
            IPipelineConfig             pipelineConfig        = new PipelineConfig();
            IStageConfig <SimpleLogger> loggerStageConfig     = new StageConfig <SimpleLogger>("Logger", () => new SimpleLogger());
            IStageConfig <Repository>   repositoryStageConfig = new StageConfig <Repository>("MemoryDb", () => new Repository());

            DefineSimpleLoggerCommands(loggerStageConfig);
            DefineRepositoryCommands(repositoryStageConfig);

            pipelineConfig.AddStage(loggerStageConfig);
            pipelineConfig.AddStage(repositoryStageConfig);
            //todo: add stages to, for example, provide level 1 or level 2 caching solutions
            return(pipelineConfig);
        }
 public PipelineTestRunPublisherL0()
 {
     this._pipelineConfig = new PipelineConfig()
     {
         BuildId      = 1,
         Project      = new Guid(),
         StageName    = "Stage1",
         StageAttempt = 1,
         PhaseName    = "Phase1",
         PhaseAttempt = 1,
         JobName      = "Job1",
         JobAttempt   = 1
     };
 }
Пример #17
0
            public static IEnumerable <object[]> GetPossibleConstructorCalls()
            {
                var config = new PipelineConfig <int, int>();
                var source = new StaticDataSource <int, int>();
                var stage  = new StaticDataStage <int, int>();

                yield return(new object[] { null, config, new IStage <int, int>[] { stage } });

                yield return(new object[] { source, null, new IStage <int, int>[] { stage } });

                yield return(new object[] { source, config, new IStage <int, int>[] { stage, null } });

                yield return(new object[] { source, config, null });
            }
        public void WhenCallingRunCommandWithNullCommandName_ThenVisitCommandCalledInExpectedStageCommandOrder()
        {
            using (var pipeline = PipelineConfig.CreatePipeline())
            {
                pipeline.RunCommand(null, "Test");
            }

            Assert.Equal(4, HistoryOfVisits.Count);

            Assert.Collection(HistoryOfVisits,
                              x => AssertForVisitor.CalledVisitCommand(VisitorA, "Test", x),
                              x => AssertForVisitor.CalledVisitCommand(VisitorB, "Test", x),
                              x => AssertForVisitor.CalledPostVisitCommand(VisitorB, "Test", x),
                              x => AssertForVisitor.CalledPostVisitCommand(VisitorA, "Test", x));
        }
Пример #19
0
        private string PipelineRow(Pipeline pipeline)
        {
            string notificationEmailRow = PipelineConfig.GetConfig().DigestRow.InnerHtml;
            string baseUrl = Request.Url.GetLeftPart(UriPartial.Authority) + "/umbraco#/pipelineCrm/";

            if (pipeline.Status == null)
            {
                return("");
            }

            return(notificationEmailRow
                   .Replace("{0}", baseUrl + pipeline.Id.ToString())
                   .Replace("{1}", pipeline.Status.Name + ": ")
                   .Replace("{2}", pipeline.Name)
                   .Replace("{3}", "Created at " + pipeline.DateCreated.ToString("dd MMM yyyy")));;
        }
        public void CreateMember(Contact contact, bool approved = true)
        {
            bool createMembers = PipelineConfig.GetConfig().AppSettings.CreateMembers;

            if (createMembers)
            {
                var memberService = UmbracoContext.Application.Services.MemberService;
                if (memberService.GetByEmail(contact.Email) == null)
                {
                    var newMember = memberService.CreateMemberWithIdentity(contact.Email, contact.Email, contact.Name, "Member");
                    newMember.RawPasswordValue = RandomPassword();
                    newMember.IsApproved       = !approved;
                    memberService.Save(newMember);
                }
            }
        }
Пример #21
0
        public override void OnClick()
        {
            string xmlFieldName = SelectXmlDoc();

            if (string.IsNullOrWhiteSpace(xmlFieldName))
            {
                return;
            }
            IPipelineConfig config = new PipelineConfig();

            config.LoadFromXml(xmlFieldName);
            string saveXmlFile = SaveFile();

            config.SaveToXml(saveXmlFile);
            MessageBox.Show(@"执行完成");
        }
        public void WhenCallingRunCommandWithGivenCommandName_ThenDefaultVisitCommandCalledInExpectedStageCommandOrder()
        {
            using (var pipeline = PipelineConfig.CreatePipeline())
            {
                // because the Visitor was defined without specifying command name, it will apply to any command run on pipeline, as long as it matches the command TPayload type
                pipeline.RunCommand(CommandName, "Test");
            }

            Assert.Equal(4, HistoryOfVisits.Count);

            Assert.Collection(HistoryOfVisits,
                              x => AssertForVisitor.CalledVisitCommand(VisitorA, "Test", x),
                              x => AssertForVisitor.CalledVisitCommand(VisitorB, "Test", x),
                              x => AssertForVisitor.CalledPostVisitCommand(VisitorB, "Test", x),
                              x => AssertForVisitor.CalledPostVisitCommand(VisitorA, "Test", x));
        }
Пример #23
0
        public void WhenStartingSession_ThenStartSessionCalledInExpectedStageCommandOrder()
        {
            using (var pipeline = PipelineConfig.CreatePipeline())
            {
                pipeline.StartSession();

                Assert.True(pipeline.SessionStarted);

                Assert.Equal(4, HistoryOfVisits.Count);
                Assert.Collection(HistoryOfVisits,
                                  x => AssertForVisitor.CalledStartSession(VisitorA, x),
                                  x => AssertForVisitor.CalledStartSession(VisitorB, x),
                                  x => AssertForVisitor.CalledPostStartSession(VisitorB, x),
                                  x => AssertForVisitor.CalledPostStartSession(VisitorA, x));
            }
        }
Пример #24
0
            public async Task Custom_Query_Requests_Can_Be_Passed_To_Final_Stage()
            {
                var config = new PipelineConfig <int, int> {
                    InitialStateMachine = new CustomStateMachine <int, int>()
                };
                var source = new Mock <ISource <int, int> >();
                var stage  = new Mock <IStage <int, int> >();

                source.Setup(s => s.ReadAsync(It.IsAny <IQuery <int, int> >(), It.IsAny <CancellationToken>()))
                .ReturnsAsync(new Dictionary <int, int>());

                stage.Setup(s => s.Process(It.IsAny <Query <int, int> >(), It.IsAny <CancellationToken>()))
                .Returns <Query <int, int>, CancellationToken>((r, t) => new[] { new CustomQuery <int, int>() });

                await new Pipeline <int, int>(source.Object, config, stage.Object).GetAsync(new[] { 1, 2, 3 });

                source.Verify(s => s.ReadAsync(It.IsAny <IQuery <int, int> >(), It.IsAny <CancellationToken>()), Times.Once);
            }
Пример #25
0
        public async Task PipelineTestRunPublisher_PublishTestRun()
        {
            var clientFactory  = new Mock <IClientFactory>();
            var logger         = new Mock <ITraceLogger>();
            var telemetry      = new Mock <ITelemetryDataCollector>();
            var testClient     = new Mock <TestResultsHttpClient>(new Uri("http://dummyurl"), new VssCredentials());
            var pipelineConfig = new PipelineConfig()
            {
                BuildId = 1,
                Project = new Guid()
            };

            clientFactory.Setup(x => x.GetClient <TestResultsHttpClient>()).Returns(testClient.Object);
            testClient.Setup(x =>
                             x.CreateTestRunAsync(It.IsAny <RunCreateModel>(), It.IsAny <Guid>(), null, It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(new Microsoft.TeamFoundation.TestManagement.WebApi.TestRun()));
            testClient.Setup(x =>
                             x.AddTestResultsToTestRunAsync(It.IsAny <TestCaseResult[]>(), It.IsAny <Guid>(), It.IsAny <int>(), null, It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(new List <TestCaseResult>()));
            testClient.Setup(x =>
                             x.UpdateTestRunAsync(It.IsAny <RunUpdateModel>(), It.IsAny <Guid>(), It.IsAny <int>(), null, It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(new Microsoft.TeamFoundation.TestManagement.WebApi.TestRun()));

            var publisher = new PipelineTestRunPublisher(clientFactory.Object, pipelineConfig, logger.Object, telemetry.Object);
            await publisher.PublishAsync(new TestRun("FakeTestResultParser/1", "Fake", 1)
            {
                PassedTests = new List <TestResult>()
                {
                    new TestResult()
                    {
                        Name    = "pass",
                        Outcome = TestOutcome.Passed
                    }
                }
            });

            testClient.Verify(x =>
                              x.CreateTestRunAsync(It.Is <RunCreateModel>(run => run.Name.Equals("Fake test run 1 - automatically inferred results", StringComparison.OrdinalIgnoreCase)),
                                                   It.IsAny <Guid>(), null, It.IsAny <CancellationToken>()));
            testClient.Verify(x => x.AddTestResultsToTestRunAsync(It.Is <TestCaseResult[]>(res => res.Length == 1),
                                                                  It.IsAny <Guid>(), It.IsAny <int>(), null, It.IsAny <CancellationToken>()));
            testClient.Verify(x => x.UpdateTestRunAsync(It.Is <RunUpdateModel>(run => run.State.Equals("completed", StringComparison.OrdinalIgnoreCase)),
                                                        It.IsAny <Guid>(), It.IsAny <int>(), null, It.IsAny <CancellationToken>()));
        }
Пример #26
0
        public void WhenStartingSessionTwice_ThenSessionOnlyStartedOnce()
        {
            using (var pipeline = PipelineConfig.CreatePipeline())
            {
                pipeline.StartSession();
                pipeline.StartSession();

                Assert.True(pipeline.SessionStarted);

                Assert.Equal(4, HistoryOfVisits.Count);
                Assert.Collection(HistoryOfVisits,
                                  x => AssertForVisitor.CalledStartSession(VisitorA, x),
                                  x => AssertForVisitor.CalledStartSession(VisitorB, x),
                                  x => AssertForVisitor.CalledPostStartSession(VisitorB, x),
                                  x => AssertForVisitor.CalledPostStartSession(VisitorA, x));
            }

            Assert.Equal(8, HistoryOfVisits.Count); // and it has been aborted
        }
Пример #27
0
        /// <summary>
        /// Executed on first request in order to build some collections
        /// from the meta-data exposed by the Pipeline.
        /// </summary>
        private PipelineConfig PopulateConfig(IPipeline pipeline)
        {
            var config = new PipelineConfig();

            // Populate the collection that contains a list of the
            // properties with names starting with 'SetHeader'
            foreach (var element in pipeline.ElementAvailableProperties)
            {
                foreach (var property in element.Value.Where(p =>
                                                             p.Key.StartsWith(SET_HEADER_PROPERTY_PREFIX, StringComparison.OrdinalIgnoreCase)))
                {
                    PropertyDetails details = new PropertyDetails()
                    {
                        PropertyMetaData   = property.Value,
                        ResponseHeaderName = GetResponseHeaderName(property.Key)
                    };
                    config.SetHeaderProperties.Add(property.Key, details);
                }
            }

            return(config);
        }
Пример #28
0
        public static Contact UpdateArrayProperties(this Contact contact, Dictionary <string, string[]> updates)
        {
            var props = contact.GetProperties().ToList();

            foreach (var update in updates)
            {
                var    prop   = props.Where(x => x.alias.ToString().ToLower() == update.Key.ToLower()).FirstOrDefault();
                JArray jValue = JArray.FromObject(update.Value);

                if (prop == null)
                {
                    // get doc type from pipeline config
                    string alias          = update.Key;
                    var    pipelineConfig = PipelineConfig.GetConfig().AppSettings;
                    var    docType        = ApplicationContext.Current.Services.ContentTypeService.GetContentType(pipelineConfig.ContactDocTypes);

                    if (docType != null)
                    {
                        var type = docType.PropertyTypes.SingleOrDefault(x => x.Alias.ToLower() == alias.ToLower());
                        if (type != null)
                        {
                            var newProp = new
                            {
                                alias = alias,
                                value = jValue,
                                id    = type.Id
                            };
                            props.Add(newProp);
                        }
                    }
                }
                else
                {
                    prop.value = jValue;
                }
            }
            contact.CustomProps = Newtonsoft.Json.JsonConvert.SerializeObject(props);
            return(contact);
        }
Пример #29
0
        private Dictionary <string, string> BuildResponseHeaderDictionary(
            IFlowData data, PipelineConfig config)
        {
            Dictionary <string, string> result = new Dictionary <string, string>();

            // Iterate through 'SetHeader*' properties
            foreach (var property in config.SetHeaderProperties)
            {
                // Get the value for this property.
                var elementData   = data.Get(property.Value.PropertyMetaData.Element.ElementDataKey);
                var propertyValue = elementData[property.Key];
                // Extract the string value.
                var headerValue = GetHeaderValue(propertyValue);

                // If value is not blank, null or 'unknown' then
                // add it to the complete value for the associated
                // header.
                if (string.IsNullOrEmpty(headerValue) == false &&
                    headerValue.Equals("Unknown", StringComparison.OrdinalIgnoreCase) == false)
                {
                    if (result.TryGetValue(property.Value.ResponseHeaderName,
                                           out string currentValue))
                    {
                        // There is already an entry for this header name
                        // so concatenate the value.
                        result[property.Value.ResponseHeaderName] =
                            $"{currentValue},{headerValue}";
                    }
                    else
                    {
                        // No entry for this header name so create it.
                        result.Add(property.Value.ResponseHeaderName, headerValue);
                    }
                }
            }

            return(result);
        }
Пример #30
0
        public async Task PipelineTestRunPublisher_PublishTestRun_EmptyTestResults()
        {
            var clientFactory  = new Mock <IClientFactory>();
            var logger         = new Mock <ITraceLogger>();
            var telemetry      = new Mock <ITelemetryDataCollector>();
            var testClient     = new Mock <TestResultsHttpClient>(new Uri("http://dummyurl"), new VssCredentials());
            var pipelineConfig = new PipelineConfig()
            {
                BuildId = 1,
                Project = new Guid()
            };

            clientFactory.Setup(x => x.GetClient <TestResultsHttpClient>()).Returns(testClient.Object);
            testClient.Setup(x =>
                             x.CreateTestRunAsync(It.IsAny <RunCreateModel>(), It.IsAny <Guid>(), null, It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(new Microsoft.TeamFoundation.TestManagement.WebApi.TestRun()
            {
                Id = 1
            }));
            testClient.Setup(x =>
                             x.AddTestResultsToTestRunAsync(It.IsAny <TestCaseResult[]>(), It.IsAny <Guid>(), It.IsAny <int>(), null, It.IsAny <CancellationToken>()))
            .Throws <Exception>();
            testClient.Setup(x =>
                             x.UpdateTestRunAsync(It.IsAny <RunUpdateModel>(), It.IsAny <Guid>(), It.IsAny <int>(), null, It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(new Microsoft.TeamFoundation.TestManagement.WebApi.TestRun()
            {
                Id = 1
            }));

            var publisher = new PipelineTestRunPublisher(clientFactory.Object, pipelineConfig, logger.Object, telemetry.Object);
            await publisher.PublishAsync(new TestRun("FakeTestResultParser/1", "Fake", 1));

            testClient.Verify(x =>
                              x.CreateTestRunAsync(It.IsAny <RunCreateModel>(), It.IsAny <Guid>(), null, It.IsAny <CancellationToken>()));
            testClient.Verify(x => x.AddTestResultsToTestRunAsync(It.IsAny <TestCaseResult[]>(), It.IsAny <Guid>(), It.IsAny <int>(), null, It.IsAny <CancellationToken>()), Times.Never);
            testClient.Verify(x => x.UpdateTestRunAsync(It.Is <RunUpdateModel>(run => run.State.Equals("completed", StringComparison.OrdinalIgnoreCase)),
                                                        It.IsAny <Guid>(), It.IsAny <int>(), null, It.IsAny <CancellationToken>()));
        }