Exemple #1
0
        public void Test_Get_Found()
        {
            var    mockCache = new Mock <IMemoryCache>();
            Har    toReturn  = GenerateSimpleHarObject();
            object h         = (object)toReturn;

            mockCache.Setup(repo => repo.TryGetValue(1, out h)).Returns(true);

            HarController controller = new HarController(mockCache.Object);
            IActionResult result     = controller.Get(1, null);

            Assert.NotNull(result);

            ObjectResult objectResult = result as ObjectResult;

            Assert.NotNull(objectResult);
            Assert.Equal(200, objectResult.StatusCode);

            Object val     = objectResult.Value;
            bool   success = GetProperty <bool>(val, "Success");

            Assert.Equal(true, success);

            int status = GetProperty <int>(val, "Status");

            Assert.Equal(200, status);

            Har model = GetProperty <Har>(val, "Model");

            Assert.Equal(toReturn, model);
        }
Exemple #2
0
        public void Test_Get_Found_Query_UnknownQuery()
        {
            var    mockCache = new Mock <IMemoryCache>();
            Har    toReturn  = GenerateSimpleHarObject();
            object h         = (object)toReturn;

            mockCache.Setup(repo => repo.TryGetValue(1, out h)).Returns(true);

            HarController controller = new HarController(mockCache.Object);
            IActionResult result     = controller.Get(1, "adfsdafsd");

            Assert.NotNull(result);

            ObjectResult objectResult = result as ObjectResult;

            Assert.NotNull(objectResult);
            Assert.Equal(400, objectResult.StatusCode);

            Object val = objectResult.Value;

            bool success = GetProperty <bool>(val, "Success");

            Assert.Equal(false, success);


            int status = GetProperty <int>(val, "Status");

            Assert.Equal(400, status);

            string message = GetProperty <string>(val, "Message");

            Assert.Equal("Unknown Query: adfsdafsd", message);
        }
Exemple #3
0
        private BodySizeQuery CalculateBodySizeStats(Har har)
        {
            Entry[] entries = har.Log.Entries;

            int length = entries.Length;

            int totalBodySize = 0;

            for (int i = 0; i < length; ++i)
            {
                totalBodySize += entries[i].Request.BodySize;
            }

            float average = 0.0f;

            if (length != 0)
            {
                average = ((float)totalBodySize) / length;
            }

            BodySizeQuery toReturn = new BodySizeQuery
            {
                AverageSize = average,
                TotalSize   = totalBodySize
            };


            return(toReturn);
        }
        public async Task <IActionResult> Put(long id, [FromBody] Har harData)
        {
            // validating by model
            if (!ModelState.IsValid)
            {
                // could have more robust error object returned
                return(BadRequest(ModelState));
            }

            var existingHarFile = await this._harFilesService.GetByIdAsync(id);

            if (existingHarFile == null)
            {
                // returing 404 in this case, could use 409 or 403
                return(NotFound());
            }
            else
            {
                var firstPage = harData.Log.Pages.First();

                var harFile = new HarFile();
                existingHarFile.URL              = firstPage.Title;
                existingHarFile.StartedDateTime  = firstPage.StartedDateTime;
                existingHarFile.HarContentString = JsonConvert.SerializeObject(harData);

                await this._harFilesService.UpdateAsync(existingHarFile);
            }

            return(Ok());
        }
        public void GetMessagesHar(
            [Frozen] Mock <IHttpClient> httpClientMock,
            [Greedy] CoreComponent sut,
            string baseUrl,
            int start,
            int count,
            Har messages)
        {
            // ARRANGE
            httpClientMock.SetupApiCall(sut, CallType.Other, "messagesHar",
                                        new Parameters
            {
                { "baseurl", baseUrl },
                { "start", start },
                { "count", count }
            }, DataType.Other)
            .Returns(Har.Serialize(messages))
            .Verifiable();

            // ACT
            var result = sut.GetMessagesHar(baseUrl, start, count);

            // ASSERT
            result.ShouldBeEquivalentTo(messages);
            httpClientMock.Verify();
        }
Exemple #6
0
        /// <summary>
        /// Executes the parsing operation
        /// </summary>
        /// <param name="pathOfFileToImport"></param>
        /// <param name="currentFile"></param>
        /// <param name="options"></param>
        public void Parse(string pathOfFileToImport, ITrafficDataAccessor currentFile, ParsingOptions options)
        {
            _options = options;
            var exclusions = options.GetExclusions();

            _status = TrafficParserStatus.Running;
            Har har = HarConvert.DeserializeFromFile(pathOfFileToImport);

            foreach (Entry entry in har.Log.Entries)
            {
                try
                {
                    if (!IsExcluded(entry.Request.Url, exclusions))
                    {
                        AddRequest(currentFile, entry);
                    }
                }
                catch (Exception ex)
                {
                    SdkSettings.Instance.Logger.Log(TraceLevel.Error, "URI Parser - Failed to add request: {0}", ex.Message);
                }
            }

            _status = TrafficParserStatus.Stopped;
        }
Exemple #7
0
        public void GetHarByUrl(
            [Frozen] Mock <IHttpClient> httpClientMock,
            [Greedy] SearchComponent sut,
            string regex,
            string baseUrl,
            int start,
            int count,
            Har har)
        {
            // ARRANGE
            httpClientMock.SetupApiCall(sut, CallType.Other, "harByUrlRegex",
                                        new Parameters
            {
                { "regex", regex },
                { "baseurl", baseUrl },
                { "start", start },
                { "count", count }
            }, DataType.Other)
            .Returns(Har.Serialize(har))
            .Verifiable();

            // ACT
            var result = sut.GetHarByUrl(regex, baseUrl, start, count);

            // ASSERT
            result.ShouldBeEquivalentTo(har);
            httpClientMock.Verify();
        }
Exemple #8
0
        /// <summary>
        /// Gets a specific message in the <see cref="Har"/> format.
        /// </summary>
        /// <param name="id">The ID of the message.</param>
        /// <returns>Message in <see cref="Har"/> format.</returns>
        public Har GetMessageHar(int id)
        {
            var result = CallOther("messageHar", new Parameters
            {
                { "id", id }
            });

            return(Har.Deserialize(result));
        }
Exemple #9
0
        /// <summary>
        /// Sends an HTTP request defined in the <see cref="Har"/> format through the ZAP proxy and returns the obtained result messages.
        /// </summary>
        /// <param name="har">The HTTP request defined in the <see cref="Har"/> format.</param>
        /// <param name="followRedirects">Optional choice whether ZAP should follow redirects. Default is false.</param>
        /// <returns>Obtained result messages in <see cref="Har"/> format.</returns>
        public Har SendHarRequest(Har har, bool?followRedirects = false)
        {
            var result = CallOther("sendHarRequest", new Parameters
            {
                { "request", Har.Serialize(har) },
                { "followRedirects", followRedirects }
            });

            return(Har.Deserialize(result));
        }
Exemple #10
0
        public void SerializeRoundtrip()
        {
            // ARRANGE
            var expected = Har.Deserialize(TestData.Sample);

            // ACT
            var actual = Har.Deserialize(Har.Serialize(expected));

            // ASSERT
            actual.ShouldBeEquivalentTo(expected);
        }
Exemple #11
0
        /// <summary>
        /// Gets all messages in the <see cref="Har"/> format. Optionally filtered by a base url and/or paged.
        /// </summary>
        /// <param name="baseUrl">Optional base url of the requested messages.</param>
        /// <param name="start">Optional starting index (1-based).</param>
        /// <param name="count">Optional maximum amount of messages to retrieve.</param>
        /// <returns>All the nessages in <see cref="Har"/> format.</returns>
        public Har GetMessagesHar(string baseUrl = null, int?start = null, int?count = null)
        {
            var result = CallOther("messagesHar", new Parameters
            {
                { "baseurl", baseUrl },
                { "start", start },
                { "count", count }
            });

            return(Har.Deserialize(result));
        }
Exemple #12
0
        private Har Generate(IFixture fixture)
        {
            var har = new Har()
            {
                Log = fixture.Create <Log>()
            };

            har.FixAutoGeneratedReferences();

            return(har);
        }
Exemple #13
0
        /// <summary>
        /// Gets messages in <see cref="Har"/> format by searching the urls. Optionally filtered by a base url and/or paged.
        /// </summary>
        /// <param name="regex">The regex pattern to search for.</param>
        /// <param name="baseUrl">Optional base url of the requested messages.</param>
        /// <param name="start">Optional starting index (1-based).</param>
        /// <param name="count">Optional maximum amount of messages to retrieve.</param>
        /// <returns>All found messages in <see cref="Har"/> format.</returns>
        public Har GetHarByUrl(string regex, string baseUrl = null, int?start = null, int?count = null)
        {
            var result = CallOther("harByUrlRegex", new Parameters
            {
                { "regex", regex },
                { "baseurl", baseUrl },
                { "start", start },
                { "count", count }
            });

            return(Har.Deserialize(result));
        }
Exemple #14
0
 public void Load(string json)
 {
     try
     {
         document = JsonConvert.DeserializeObject<Har>(json);
     }
     catch
     {
         throw;
     }
     loadFailed = new List<Entrie>();
 }
Exemple #15
0
        private BlockedQuery CalculateBlockedStats(Har har)
        {
            Entry[] entries = har.Log.Entries;

            int length = entries.Length;

            Entry longest = null, shortest = null, secondShortest = null;

            for (int i = 0; i < length; ++i)
            {
                double blocked = entries[i].Timings.Blocked;

                if (blocked < 0.0)
                {
                    continue;
                }

                if (longest == null)
                {
                    longest  = entries[i];
                    shortest = entries[i];
                    continue;
                }


                if (blocked > longest.Timings.Blocked)
                {
                    longest = entries[i];
                }
                else if (blocked < shortest.Timings.Blocked)
                {
                    secondShortest = shortest;
                    shortest       = entries[i];
                }
                else if (secondShortest == null)
                {
                    secondShortest = entries[i];
                }
                else if (blocked < secondShortest.Timings.Blocked)
                {
                    secondShortest = entries[i];
                }
            }

            BlockedQuery toReturn = new BlockedQuery
            {
                Longest        = longest,
                Shortest       = shortest,
                SecondShortest = secondShortest
            };

            return(toReturn);
        }
Exemple #16
0
        public void EntryPageRefNotFound()
        {
            // ARRANGE
            var har = new Har();

            har.Log.Entries.Add(new Entry {
                PageRef = "page_0"
            });

            // ACT
            Action act = () => Har.Serialize(har);

            // ASSERT
            act.ShouldThrow <InvalidOperationException>().WithMessage(Resources.EntryPageRefNotFound);
        }
Exemple #17
0
 public IActionResult Put(int id, [FromBody] Har jsonbody)
 {
     try
     {
         if (ValidateModel(out var postAsync))
         {
             return(postAsync);
         }
         _cache.Set <Har>(id, jsonbody);
         return(StatusCode(201, new { Success = true, Id = id, Status = 201, Model = jsonbody }));
     }
     catch (Exception ex)
     {
         return(StatusCode(500, new { Success = false, Status = 500, Message = ex.Message }));
     }
 }
    private static void ValidateHar(Har har)
    {
        if (har == null)
        {
            throw new ValidationException("The HAR was invalid.");
        }

        if (har.Log == null)
        {
            throw new ValidationException("har.log is not set.");
        }

        if (har.Log.Entries == null || !har.Log.Entries.Any())
        {
            throw new ValidationException("No entries set in HAR.");
        }
    }
Exemple #19
0
        private List <string> GetUrlsWithInputString(Har har)
        {
            Entry[]       entries  = har.Log.Entries;
            int           length   = entries.Length;
            List <string> toReturn = new List <string>();

            for (int i = 0; i < length; ++i)
            {
                Entry entry = entries[i];

                if (entry.Request.Url.Contains('?'))
                {
                    toReturn.Add(entry.Request.Url);
                }
            }

            return(toReturn);
        }
Exemple #20
0
        public void PageIdsNotUnique()
        {
            // ARRANGE
            var har = new Har();

            har.Log.Pages.Add(new Page {
                Id = "page_0"
            });
            har.Log.Pages.Add(new Page {
                Id = "page_0"
            });

            // ACT
            Action act = () => Har.Serialize(har);

            // ASSERT
            act.ShouldThrow <InvalidOperationException>().WithMessage(Resources.PageIdsNotUnique);
        }
Exemple #21
0
        public async Task <IActionResult> PostAsync([FromBody] Har jsonbody)
        {
            try
            {
                if (ValidateModel(out var postAsync))
                {
                    return(postAsync);
                }

                int newId = Interlocked.Increment(ref _id);
                _cache.Set <Har>(newId, jsonbody);
                return(StatusCode(201, new { Success = true, Id = newId, Status = 201, Model = jsonbody }));
            }
            catch (Exception ex)
            {
                return(StatusCode(500, new { Success = false, Status = 500, Message = ex.Message }));
            }
        }
        public void GetMessageHar(
            [Frozen] Mock <IHttpClient> httpClientMock,
            [Greedy] CoreComponent sut,
            int id,
            Har message)
        {
            // ARRANGE
            httpClientMock.SetupApiCall(sut, CallType.Other, "messageHar",
                                        new Parameters
            {
                { "id", id }
            }, DataType.Other)
            .Returns(Har.Serialize(message))
            .Verifiable();

            // ACT
            var result = sut.GetMessageHar(id);

            // ASSERT
            result.ShouldBeEquivalentTo(message);
            httpClientMock.Verify();
        }
Exemple #23
0
        private object GetUrlsWithSlowestPage(Har har)
        {
            Entry[] entries = har.Log.Entries;
            int     length  = entries.Length;
            double  slowest = 0.0;
            string  url     = String.Empty;

            for (int i = 0; i < length; ++i)
            {
                Entry entry = entries[i];

                if (entry.Time > slowest)
                {
                    slowest = entry.Time;
                    url     = entry.Request.Url;
                }
            }

            return(new SlowestPageQuery {
                Url = url, Size = slowest
            });
        }
Exemple #24
0
        public void Test_Get_Found_Query_QueryString()
        {
            var    mockCache = new Mock <IMemoryCache>();
            Har    toReturn  = GenerateSimpleHarObject();
            object h         = (object)toReturn;

            mockCache.Setup(repo => repo.TryGetValue(1, out h)).Returns(true);

            HarController controller = new HarController(mockCache.Object);
            IActionResult result     = controller.Get(1, "querystring");

            Assert.NotNull(result);

            ObjectResult objectResult = result as ObjectResult;

            Assert.NotNull(objectResult);
            Assert.Equal(200, objectResult.StatusCode);

            Object val = objectResult.Value;

            bool success = GetProperty <bool>(val, "Success");

            Assert.Equal(true, success);


            int status = GetProperty <int>(val, "Status");

            Assert.Equal(200, status);

            Har model = GetProperty <Har>(val, "Model");

            Assert.Equal(toReturn, model);

            List <string> urls = GetProperty <List <string> >(val, "Query");

            Assert.Equal(2, urls.Count);
            Assert.Equal("www.google.com?b=1", urls[0]);
            Assert.Equal("www.yahoo.com?a=1", urls[1]);
        }
        private bool ValidateHarFile(Har harData)
        {
            try
            {
                var page = harData.Log.Pages.FirstOrDefault();

                if (page == null)
                {
                    return(false);
                }
                else
                {
                    // validate title exists
                    if (string.IsNullOrEmpty(page.Title))
                    {
                        return(false);
                    }

                    // validate startedDateTime exists
                    if (page.StartedDateTime == DateTime.MinValue)
                    {
                        return(false);
                    }
                }

                // validate entries exist
                if (harData.Log.Entries.Count == 0)
                {
                    return(false);
                }
            }
            catch (Exception)
            {
                return(false);
            }

            return(true);
        }
        public void SendHarRequest(
            [Frozen] Mock <IHttpClient> httpClientMock,
            [Greedy] CoreComponent sut,
            Har request,
            bool followRedirects,
            Har response)
        {
            // ARRANGE
            httpClientMock.SetupApiCall(sut, CallType.Other, "sendHarRequest",
                                        new Parameters
            {
                { "request", Har.Serialize(request) },
                { "followRedirects", followRedirects }
            }, DataType.Other)
            .Returns(Har.Serialize(response))
            .Verifiable();

            // ACT
            var result = sut.SendHarRequest(request, followRedirects);

            // ASSERT
            result.ShouldBeEquivalentTo(response);
            httpClientMock.Verify();
        }
Exemple #27
0
        IEnumerableAsync <Message[]> ToText(Har har, CancellationToken cancellation)
        {
            var buffer = new List <Message>();

            int lastEntryId = 0;

            foreach (var e in har.Log.Entries)
            {
                if (e.Request == null || e.Timings == null)
                {
                    continue;
                }
                var entryId = (++lastEntryId).ToString();
                Action <double?, string, string, string> add = (timeOffset, sev, msgType, msg) =>
                {
                    buffer.Add(new Message(buffer.Count, 0, e.StartedDateTime.AddMilliseconds(timeOffset ?? 0),
                                           new StringSlice(Message.ENTRY), new StringSlice(entryId), new StringSlice(msgType),
                                           new StringSlice(sev ?? Message.INFO), msg));
                };
                Func <string, string> trimValue = s =>
                {
                    var limit = 4000;
                    if (s.Length <= limit)
                    {
                        return(s);
                    }
                    return(string.Format("{0}...(trimmed)", s.Substring(0, limit)));
                };

                add(0, null, Message.START,
                    string.Format("{0} {1} {2}", e.Request.Method, e.Request.Url, e.Request.HttpVersion));

                foreach (var h in e.Request.Headers)
                {
                    add(0, null, Message.HEADER, string.Format("{0}: {1}", h.Name, trimValue(h.Value)));
                }
                add(0, null, Message.META, string.Format("headersSize: {0}", e.Request.HeadersSize));
                add(0, null, Message.META, string.Format("connection: {0}", e.Connection));
                add(0, null, Message.META, string.Format("serverIPAddress: {0}", e.ServerIPAddress));
                if (e.Request.PostData != null)
                {
                    add(0, null, Message.BODY, e.Request.PostData.Text);
                }

                Predicate <double?> isGoodTimeOffset = v => v != null && v >= 0;

                double lastPhaseOffset = 0;
                Action <double?, string> tryAddStage = (timeOffset, stage) =>
                {
                    if (isGoodTimeOffset(timeOffset))
                    {
                        lastPhaseOffset += timeOffset.Value;
                        add(lastPhaseOffset, null, stage, "");
                    }
                };
                tryAddStage(e.Timings.Blocked, Message.BLOCKED);
                tryAddStage(e.Timings.Dns, Message.DNS);
                if (isGoodTimeOffset(e.Timings.Ssl) && isGoodTimeOffset(e.Timings.Connect))
                {
                    tryAddStage(e.Timings.Ssl, Message.SSL);
                    tryAddStage(e.Timings.Connect.Value - e.Timings.Ssl.Value, Message.CONNECT);
                }
                else
                {
                    tryAddStage(e.Timings.Connect, Message.CONNECT);
                }
                tryAddStage(e.Timings.Send, Message.SEND);
                tryAddStage(e.Timings.Wait, Message.WAIT);

                if (e.Response != null)
                {
                    var rspTime = e.Timings.Receive + lastPhaseOffset;
                    lastPhaseOffset = rspTime;
                    add(
                        rspTime,
                        e.Response.Status >= 200 && e.Response.Status < 400 ? Message.INFO : Message.WARN,
                        Message.RECEIVE, string.Format("{0} {1} {2}", e.Response.HttpVersion, e.Response.Status, e.Response.StatusText)
                        );
                    foreach (var h in e.Response.Headers)
                    {
                        add(rspTime, null, Message.HEADER, string.Format("{0}: {1}", h.Name, trimValue(h.Value)));
                    }
                    add(rspTime, null, Message.META, string.Format("headersSize: {0}", e.Response.HeadersSize));
                    add(rspTime, null, Message.META, string.Format("bodySize: {0}", e.Response.BodySize));
                    if (e.Response.Content != null && !string.IsNullOrEmpty(e.Response.Content.Text))
                    {
                        add(rspTime, null, Message.BODY, trimValue(e.Response.Content.Text));
                    }
                }
                add(lastPhaseOffset, null, Message.END, "");
            }


            buffer.Sort((m1, m2) =>
            {
                int c = DateTime.Compare(m1.Timestamp, m2.Timestamp);
                if (c != 0)
                {
                    return(c);
                }
                return(m1.Index - m2.Index);
            });
            return((new[] { buffer.ToArray() }).ToAsync());
        }
 public void InitializeFixture()
 {
     m_actual = HarConvert.Deserialize(Resources.Sample);
 }
Exemple #29
0
 public Bar(Gar g, Har h, Tar t)
 {
     Console.WriteLine("Bar ctor with gar, har and tar.");
 }
Exemple #30
0
 public Foo(Bar b, Har h)
 {
     Console.WriteLine("Foo Ctor with Bar and Har");
 }
Exemple #31
0
 // [Inject]
 public Gar(Har h)
 {
     Console.WriteLine("Har");
 }
Exemple #32
0
 public Gar(Har h, FileInfo f)
 {
     Console.WriteLine("Har and FileInfo. f.Name = " + f.Name);
 }