private static int SendEventsToKeep(Keen.Core.KeenClient keenClient, List <AppModel> eventsToSend, MongoDBWrapper mongoDB)
        {
            try
            {
                // Adding Event to Keen.IO
                keenClient.AddEvents("PlayStore2014", eventsToSend);

                // Incrementing Counter
                _appsCounter += eventsToSend.Count;

                // Console feedback Every 100 Processed Apps
                if (_appsCounter % 100 == 0)
                {
                    Console.WriteLine("Uploaded : " + _appsCounter);
                }

                foreach (var e in eventsToSend)
                {
                    mongoDB.SetUpdated(e.Url);
                }

                return(eventsToSend.Count);
            }
            catch (Exception ex)
            {
                Console.WriteLine("\n\t" + ex.Message);
            }

            return(0);
        }
Esempio n. 2
0
        public async void AvailableQueries_Success()
        {
            var client = new KeenClient(settingsEnv);

            Mock<IQueries> queryMock = null;
            if (UseMocks)
            {
                // A few values that should be present and are unlikely to change
                IEnumerable<KeyValuePair<string,string>> testResult = new List<KeyValuePair<string, string>>() 
                { 
                    new KeyValuePair<string, string>("minimum", "url" ),
                    new KeyValuePair<string, string>("average", "url" ),
                    new KeyValuePair<string, string>("maximum", "url" ),
                    new KeyValuePair<string, string>("count_url", "url" ),
                };

                queryMock = new Mock<IQueries>();
                queryMock.Setup(m=>m.AvailableQueries())
                    .Returns(Task.FromResult(testResult));
                
                client.Queries = queryMock.Object;
            }

            var response = await client.GetQueries();
            Assert.True(response.Any(p => p.Key == "minimum"));
            Assert.True(response.Any(p => p.Key == "average"));
            Assert.True(response.Any(p => p.Key == "maximum"));
            Assert.True(response.Any(p => p.Key == "count_url"));
            if (null != queryMock)
                queryMock.Verify(m => m.AvailableQueries());
        }
Esempio n. 3
0
        public override void Setup()
        {
            base.Setup();

            // If not using mocks, set up conditions on the server
            if (!UseMocks)
            {
                var client = new KeenClient(SettingsEnv);

                client.DeleteCollection(FunnelColA);
                client.DeleteCollection(FunnelColB);
                client.DeleteCollection(FunnelColC);

                client.AddEvent(FunnelColA, new { id = 1, name = new { first = "sam", last = "w" } });
                client.AddEvent(FunnelColA, new { id = 2, name = new { first = "dean", last = "w" } });
                client.AddEvent(FunnelColA, new { id = 3, name = new { first = "crowly", last = "" } });

                client.AddEvent(FunnelColB, new { id = 1, name = new { first = "sam", last = "w" } });
                client.AddEvent(FunnelColB, new { id = 2, name = new { first = "dean", last = "w" } });

                client.AddEvent(FunnelColC, new { id = 1, name = new { first = "sam", last = "w" } });

                Thread.Sleep(8000); // Give it a moment to show up. Queries will fail if run too soon.
            }
        }
Esempio n. 4
0
        public async void Query_InvalidCollection_Throws()
        {
            var client = new KeenClient(settingsEnv);
            var timeframe = QueryRelativeTimeframe.PreviousHour();

            Mock<IQueries> queryMock = null;
            if (UseMocks)
            {
                queryMock = new Mock<IQueries>();
                queryMock.Setup(m => m.Metric(
                        It.Is<QueryType>(q => q == QueryType.Count()),
                        It.Is<string>(c => c == null),
                        It.Is<string>(p => p == ""),
                        It.Is<QueryRelativeTimeframe>(t => t == timeframe),
                        It.Is<IEnumerable<QueryFilter>>(f => f == null),
                        It.Is<string>(z => z == "")
                        ))
                        .Throws(new ArgumentNullException());

                client.Queries = queryMock.Object;
            }

            var count = await client.QueryAsync(QueryType.Count(), null, "", timeframe, null);
            Assert.IsNotNull(count);
        }
Esempio n. 5
0
        public void CachingPCL_AddEvents_Success(IEventCache cache)
        {
            var client = new KeenClient(SettingsEnv, cache);

            Assert.DoesNotThrow(() => client.AddEvent("CachedEventTest", new { AProperty = "AValue" }));
            Assert.DoesNotThrow(() => client.AddEvent("CachedEventTest", new { AProperty = "AValue" }));
            Assert.DoesNotThrow(() => client.AddEvent("CachedEventTest", new { AProperty = "AValue" }));
        }
Esempio n. 6
0
        public async Task Funnel_Simple_Success()
        {
            var client = new KeenClient(SettingsEnv);

            IEnumerable<FunnelStep> funnelsteps = new List<FunnelStep>
            {
                new FunnelStep
                {
                    EventCollection = FunnelColA, 
                    ActorProperty = "id",
                },
                new FunnelStep
                {
                    EventCollection = FunnelColB, 
                    ActorProperty = "id"
                },
            };

            var expected = new FunnelResult
            {
                Steps = new []
                {
                    new FunnelResultStep
                    {
                        EventCollection = FunnelColA, 
                    },
                    new FunnelResultStep
                    {
                        EventCollection = FunnelColB, 
                    },
                },
                Result = new[] { 3, 2 }
            };


            Mock<IQueries> queryMock = null;
            if (UseMocks)
            {
                queryMock = new Mock<IQueries>();
                queryMock.Setup(m => m.Funnel(
                        It.Is<IEnumerable<FunnelStep>>(f => f.Equals(funnelsteps)),
                        It.Is<QueryTimeframe>(t => t == null),
                        It.Is<string>(t => t == "")
                      ))
                  .Returns(Task.FromResult(expected));

                client.Queries = queryMock.Object;
            }

            var reply = (await client.QueryFunnelAsync(funnelsteps));
            Assert.NotNull(reply);
            Assert.NotNull(reply.Result);
            Assert.NotNull(reply.Steps);
            Assert.AreEqual(reply.Steps.Count(), 2);

            if (null != queryMock)
                queryMock.VerifyAll();
        }
Esempio n. 7
0
        public void ReadKeyOnly_Success()
        {
            var settings = new ProjectSettingsProvider(SettingsEnv.ProjectId, readKey: SettingsEnv.ReadKey); 
            var client = new KeenClient(settings);

            if (!UseMocks)
            {
                // Server is required for this test
                // Also, test depends on existance of collection "AddEventTest"
                Assert.DoesNotThrow(() => client.Query(QueryType.Count(), "AddEventTest", ""));
            }
        }
Esempio n. 8
0
        public override void Setup()
        {
            base.Setup();

            // If not using mocks, set up conditions on the server
            if (!UseMocks)
            {
                var client = new KeenClient(settingsEnv);
                //client.DeleteCollection(testCol);
                client.AddEvent(testCol, new { field1 = "99999999" });
            }
        }
Esempio n. 9
0
        public void No_AddOn_Success()
        {
            var client = new KeenClient(SettingsEnv);
            if (UseMocks)
                client.EventCollection = new EventCollectionMock(SettingsEnv,
                    addEvent: (c, e, p) =>
                    {
                        if (e["keen"].ToString().Contains("keen:ip_to_geo"))
                            throw new Exception("Unexpected values");
                    });

            Assert.DoesNotThrow(() => client.AddEvent("AddOnTest", new { an_ip = "70.187.8.97" }));
        }
Esempio n. 10
0
        public void IpToGeo_MissingInput_Throws()
        {
            var client = new KeenClient(SettingsEnv);
            if (UseMocks)
                client.EventCollection = new EventCollectionMock(SettingsEnv,
                    addEvent: (c, e, p) =>
                    {
                        if (!e["keen"].ToString().Contains("\"ip\": \"an_ip\""))
                            throw new KeenException("Unexpected values");
                    });

            var a = AddOn.IpToGeo("wrong_field", "geocode");

            Assert.Throws<KeenException>(() => client.AddEvent("AddOnTest", new { an_ip = "70.187.8.97" }, new List<AddOn> { a }));
        }
Esempio n. 11
0
        public void IpToGeo_Send_Success()
        {
            var client = new KeenClient(SettingsEnv);
            if (UseMocks)
                client.EventCollection = new EventCollectionMock(SettingsEnv,
                    addEvent: (c, e, p) =>
                    {
                        if (!e["keen"].ToString().Contains("keen:ip_to_geo"))
                            throw new Exception("Unexpected values");
                    });

            var a = AddOn.IpToGeo("an_ip", "geocode");

            Assert.DoesNotThrow(() => client.AddEvent("AddOnTest", new {an_ip = "70.187.8.97"}, new List<AddOn> {a}));
        }
Esempio n. 12
0
        public void UserAgentParser_Send_Success()
        {
            var client = new KeenClient(SettingsEnv);
            if (UseMocks)
                client.EventCollection = new EventCollectionMock(SettingsEnv,
                    addEvent: (c, e, p) =>
                    {
                        if (!e["keen"].ToString().Contains("keen:ua_parser"))
                            throw new Exception("Unexpected values");
                    });

            var a = AddOn.UserAgentParser("user_agent_string", "user_agent_parsed");

            Assert.DoesNotThrow(() => client.AddEvent("AddOnTest", new { user_agent_string = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36" }, new List<AddOn> { a }));
        }
Esempio n. 13
0
        public void UrlParser_Send_Success()
        {
            var client = new KeenClient(SettingsEnv);
            if (UseMocks)
                client.EventCollection = new EventCollectionMock(SettingsEnv,
                    addEvent: (c, e, p) =>
                    {
                        if (!e["keen"].ToString().Contains("keen:url_parser"))
                            throw new Exception("Unexpected values");
                    });

            var a = AddOn.UrlParser("url", "url_parsed");

            Assert.DoesNotThrow(() => client.AddEvent("AddOnTest", new { url = "https://keen.io/docs/data-collection/data-enrichment/#anchor" }, new List<AddOn> { a }));
        }
        static void Main (string[] args)
        {
            // Loading Keen.IO Keys and Misc. from Config File
            _keenIOProjectID = ConfigurationManager.AppSettings["keenIOProjectID"];
            _keenIOMasterKey = ConfigurationManager.AppSettings["keenIOMasterKey"];
            _keenIOWriteKey  = ConfigurationManager.AppSettings["keenIOWriteKey"];
            _keenIOReadKey   = ConfigurationManager.AppSettings["keenIOReadKey"];
            _bucketName      = ConfigurationManager.AppSettings["keenIOBucketName"];
            
            // Creating Keen.IO Variables - Yes, i am setting my read key as the master key, so that you can read the bucket I have created with data
            var projectSettings = new ProjectSettingsProvider (_keenIOProjectID,masterKey:_keenIOReadKey);
            var keenClient      = new KeenClient (projectSettings);


            /*********************************************************************
             *          EXECUTING SIMPLE ANALYTICS QUERIES ON KEEN.IO 
             **********************************************************************/

            // Query 1 - Average App Price grouped by Category
            Dictionary<String,String> parameters = new Dictionary<String,String>();
            parameters.Add ("event_collection", "PlayStore2014");
            parameters.Add ("target_property", "Price");
            parameters.Add ("group_by", "Category");

            JObject keenResponse = keenClient.Query (KeenConstants.QueryAverage, parameters);

            PrintQueryTitle ("Query 1 - Average App Price grouped by Category");
            Console.WriteLine (keenResponse.ToSafeString ());
            PrintSeparator ();

            // Query 2 - Most Expensive app for sale of each category
            keenResponse = keenClient.Query (KeenConstants.QueryMaximum, parameters);

            PrintQueryTitle ("Query 2 - Most Expensive app for sale of each category");
            Console.WriteLine (keenResponse.ToSafeString ());
            PrintSeparator ();
            
            // Query 3 - Most Expensive App for sale of all (without group by)
            parameters.Remove ("group_by");
            keenResponse = keenClient.Query (KeenConstants.QueryMaximum, parameters);

            PrintQueryTitle ("Query 3 - Most Expensive App for sale of all (without group by)");
            Console.WriteLine (keenResponse.ToSafeString ());
            PrintSeparator ();

            Console.ReadKey ();

        }
Esempio n. 15
0
 public void AddEvents_InvalidProject_Throws()
 {
     var settings = new ProjectSettingsProvider(projectId: "X", writeKey: settingsEnv.WriteKey);
     var client = new KeenClient(settings);
     if (UseMocks)
         client.Event = new EventMock(settings,
             AddEvents: new Func<JObject, IProjectSettings, IEnumerable<CachedEvent>>((e, p) =>
             {
                 if ((p == settings)
                     &&(p.ProjectId=="X"))
                     throw new KeenException();
                 else
                     throw new Exception("Unexpected value");
             }));
     Assert.Throws<KeenException>(() => client.AddEvents("AddEventTest", new []{ new {AProperty = "AValue" }}));
 }
Esempio n. 16
0
        static void Main (string[] args)
        {
            // Loading Keen.IO Keys and Misc. from Config File
            _keenIOProjectID = ConfigurationManager.AppSettings["keenIOProjectID"];
            _keenIOMasterKey = ConfigurationManager.AppSettings["keenIOMasterKey"];
            _keenIOWriteKey  = ConfigurationManager.AppSettings["keenIOWriteKey"];
            _keenIOReadKey   = ConfigurationManager.AppSettings["keenIOReadKey"];
            _bucketName      = ConfigurationManager.AppSettings["keenIOBucketName"];

            // Configuring MongoDB Wrapper for connection and queries
            MongoDBWrapper mongoDB   = new MongoDBWrapper ();
            string fullServerAddress = String.Join (":", Consts.MONGO_SERVER, Consts.MONGO_PORT);
            mongoDB.ConfigureDatabase (Consts.MONGO_USER, Consts.MONGO_PASS, Consts.MONGO_AUTH_DB, fullServerAddress, Consts.MONGO_TIMEOUT, Consts.MONGO_DATABASE, Consts.MONGO_COLLECTION);

            // Creating Keen.IO Variables
            var projectSettings = new ProjectSettingsProvider (_keenIOProjectID, _keenIOMasterKey, _keenIOWriteKey, _keenIOReadKey);
            var keenClient      = new KeenClient (projectSettings);

            // From This point on, you can change your code to reflect your own "Reading" logic
            // What I've done is simply read the records from the MongoDB database and Upload them to Keen.IO
            foreach (var currentApp in mongoDB.FindMatch<AppModel> (Query.NE ("Uploaded", true)))
            {
                try
                {
                    // Adding Event to Keen.IO
                    keenClient.AddEvent ("PlayStore2014", currentApp);

                    // Incrementing Counter
                    _appsCounter++;

                    // Console feedback Every 100 Processed Apps
                    if (_appsCounter % 100 == 0)
                    {
                        Console.WriteLine ("Uploaded : " + _appsCounter);
                    }

                    mongoDB.SetUpdated (currentApp.Url);
                }
                catch (Exception ex)
                {
                    Console.WriteLine ("\n\t" + ex.Message);
                }
            }
        }
Esempio n. 17
0
        public void AddEvents_PartialFailure_Throws()
        {
            var client = new KeenClient(settingsEnv);
            if (UseMocks)
                client.Event = new EventMock(settingsEnv,
                    AddEvents: new Func<JObject, IProjectSettings, IEnumerable<CachedEvent>>((e, p) =>
                    {
                        var err = e.SelectToken("$.AddEventTest[2]") as JObject;
                        if (null == err)
                            throw new Exception("Unexpected error, test data not found");

                        return new List<CachedEvent>(){new CachedEvent("AddEventTest", e)};
                    }));

            object invalidEvent = new ExpandoObject();
            ((IDictionary<string, object>)invalidEvent).Add("$" + new string('.', 260), "AValue");

            var events = (from i in Enumerable.Range(1, 2)
                         select new { AProperty = "AValue" + i }).ToList<object>();
            events.Add(invalidEvent);

            Assert.Throws<KeenBulkException>(() => client.AddEvents("AddEventTest", events));
        }
Esempio n. 18
0
        public async void SelectUnique_ValidRelativeInterval_Success()
        {
            var client = new KeenClient(settingsEnv);
            var prop = "field1";
            var interval = QueryInterval.EveryNMinutes(5);
            var timeframe = QueryRelativeTimeframe.ThisMinute();
            var resultl = "hello,goodbye,I'm late";
            IEnumerable<QueryIntervalValue<string>> result =
                new List<QueryIntervalValue<string>>() { new QueryIntervalValue<string>(resultl, DateTime.Now.AddMinutes(-5), DateTime.Now) };

            Mock<IQueries> queryMock = null;
            if (UseMocks)
            {
                queryMock = new Mock<IQueries>();
                queryMock.Setup(m => m.Metric(
                        It.Is<QueryType>(q => q == QueryType.SelectUnique()),
                        It.Is<string>(c => c == testCol),
                        It.Is<string>(p => p == prop),
                        It.Is<QueryRelativeTimeframe>(t => t == timeframe),
                        It.Is<QueryInterval>(i => i == interval),
                        It.Is<IEnumerable<QueryFilter>>(f => f == null),
                        It.Is<string>(t => t == "")
                        ))
                    .Returns(Task.FromResult(result));

                client.Queries = queryMock.Object;
            }

            var reply = (await client.QueryIntervalAsync(QueryType.SelectUnique(), testCol, prop, timeframe, interval)).ToList();

            if (null != queryMock)
                queryMock.VerifyAll();
        }
Esempio n. 19
0
        public async void SelectUnique_ValidAbsoluteIntervalGroup_Success()
        {
            var client = new KeenClient(settingsEnv);
            var prop = "field1";
            var timeframe = new QueryAbsoluteTimeframe(DateTime.Now.AddDays(-1), DateTime.Now);
            var interval = QueryInterval.EveryNHours(4);
            var groupby = "field1";
            var resultl = "hello,goodbye,I'm late";

            IEnumerable<QueryIntervalValue<IEnumerable<QueryGroupValue<string>>>> result =
                new List<QueryIntervalValue<IEnumerable<QueryGroupValue<string>>>>() 
                { 
                    new QueryIntervalValue<IEnumerable<QueryGroupValue<string>>>(
                        new List<QueryGroupValue<string>>(){
                            new QueryGroupValue<string>(resultl, "abc"),
                            new QueryGroupValue<string>(resultl, "def")
                        }, 
                        timeframe.Start, timeframe.End
                        ),
                    new QueryIntervalValue<IEnumerable<QueryGroupValue<string>>>(
                        new List<QueryGroupValue<string>>(){
                            new QueryGroupValue<string>(resultl, "abc"),
                            new QueryGroupValue<string>(resultl, "def")
                        }, 
                        timeframe.Start, timeframe.End
                        ),
                };

            Mock<IQueries> queryMock = null;
            if (UseMocks)
            {
                queryMock = new Mock<IQueries>();
                queryMock.Setup(m => m.Metric(
                        It.Is<QueryType>(q => q == QueryType.SelectUnique()),
                        It.Is<string>(c => c == testCol),
                        It.Is<string>(p => p == prop),
                        It.Is<string>(g => g == groupby),
                        It.Is<QueryAbsoluteTimeframe>(t => t == timeframe),
                        It.Is<QueryInterval>(i => i == interval),
                        It.Is<IEnumerable<QueryFilter>>(f => f == null),
                        It.Is<string>(t => t == "")
                        ))
                    .Returns(Task.FromResult(result));

                client.Queries = queryMock.Object;
            }

            var counts = (await client.QueryIntervalGroupAsync(QueryType.SelectUnique(), testCol, prop, groupby, timeframe, interval)).ToList();

            if (null != queryMock)
                queryMock.VerifyAll();
        }
Esempio n. 20
0
        public async void SelectUnique_ValidFilter_Success()
        {
            var client = new KeenClient(settingsEnv);
            var prop = "field1";
            var filters = new List<QueryFilter>() { new QueryFilter("field1", QueryFilter.FilterOperator.GreaterThan(), "1") };
            var result = "hello,goodbye,I'm late";

            Mock<IQueries> queryMock = null;
            if (UseMocks)
            {
                queryMock = new Mock<IQueries>();
                queryMock.Setup(m => m.Metric(
                      It.Is<QueryType>(q => q == QueryType.SelectUnique()),
                      It.Is<string>(c => c == testCol),
                      It.Is<string>(p => p == prop),
                      It.Is<QueryRelativeTimeframe>(t => t == null),
                      It.Is<IEnumerable<QueryFilter>>(f => f == filters),
                      It.Is<string>(t => t == "")
                      ))
                  .Returns(Task.FromResult(result));

                client.Queries = queryMock.Object;
            }

            var reply = (await client.QueryAsync(QueryType.SelectUnique(), testCol, prop, null, filters)).ToList();

            if (null != queryMock)
                queryMock.VerifyAll();
        }
Esempio n. 21
0
        public async void SelectUnique_ValidRelativeGroup_Success()
        {
            var client = new KeenClient(settingsEnv);
            var prop = "field1";
            var groupby = "field1";
            var timeframe = QueryRelativeTimeframe.PreviousNDays(5);
            IEnumerable<QueryGroupValue<string>> reply = new List<QueryGroupValue<string>>()
            {
                new QueryGroupValue<string>( "hello,goodbye,I'm late", "field1" ),
                new QueryGroupValue<string>( "hello,goodbye,I'm late", "field1" ),
            };

            Mock<IQueries> queryMock = null;
            if (UseMocks)
            {
                queryMock = new Mock<IQueries>();
                queryMock.Setup(m => m.Metric(
                        It.Is<QueryType>(q => q == QueryType.SelectUnique()),
                        It.Is<string>(c => c == testCol),
                        It.Is<string>(p => p == prop),
                        It.Is<string>(g => g == groupby),
                        It.Is<QueryRelativeTimeframe>(t => t == timeframe),
                        It.Is<IEnumerable<QueryFilter>>(f => f == null),
                        It.Is<string>(t => t == "")
                        ))
                    .Returns(Task.FromResult(reply));

                client.Queries = queryMock.Object;
            }

            (await client.QueryGroupAsync(QueryType.SelectUnique(), testCol, prop, groupby, timeframe, null)).ToList();

            if (null != queryMock)
                queryMock.VerifyAll();
        }
Esempio n. 22
0
        public async void SelectUnique_ValidRelative_Success()
        {
            var client = new KeenClient(settingsEnv);
            var prop = "field1";
            var timeframe = QueryRelativeTimeframe.ThisMinute();
            var result = "hello,goodbye,I'm late";

            Mock<IQueries> queryMock = null;
            if (UseMocks)
            {
                queryMock = new Mock<IQueries>();
                queryMock.Setup(m => m.Metric(
                        It.Is<QueryType>(q => q == QueryType.SelectUnique()),
                        It.Is<string>(c => c == testCol),
                        It.Is<string>(p => p == prop),
                        It.Is<QueryRelativeTimeframe>(t => t == timeframe),
                        It.Is<IEnumerable<QueryFilter>>(f => f == null),
                        It.Is<string>(t => t == "")
                        ))
                    .Returns(Task.FromResult(result));

                client.Queries = queryMock.Object;
            }

            await client.QueryAsync(QueryType.SelectUnique(), testCol, prop, timeframe);

            if (null != queryMock)
                queryMock.VerifyAll();
        }
Esempio n. 23
0
        public async void Sum_ValidAbsolute_Success()
        {
            var client = new KeenClient(settingsEnv);
            var timeframe = new QueryAbsoluteTimeframe(DateTime.Now.AddDays(-1), DateTime.Now);
            var prop = "field1";

            Mock<IQueries> queryMock = null;
            if (UseMocks)
            {
                queryMock = new Mock<IQueries>();
                queryMock.Setup(m => m.Metric(
                        It.Is<QueryType>(q => q == QueryType.Sum()),
                        It.Is<string>(c => c == testCol),
                        It.Is<string>(p => p == prop),
                        It.Is<QueryAbsoluteTimeframe>(t => t == timeframe),
                        It.Is<IEnumerable<QueryFilter>>(f => f == null),
                        It.Is<string>(t => t == "")
                        ))
                    .Returns(Task.FromResult("0.0"));

                client.Queries = queryMock.Object;
            }

            await client.QueryAsync(QueryType.Sum(), testCol, prop, timeframe);

            if (null != queryMock)
                queryMock.VerifyAll();
        }
Esempio n. 24
0
        public async void Query_ValidFilter_Success()
        {
            var client = new KeenClient(settingsEnv);
            var filters = new List<QueryFilter>(){ new QueryFilter("field1", QueryFilter.FilterOperator.GreaterThan(), "1") };

            Mock<IQueries> queryMock = null;
            if (UseMocks)
            {
                queryMock = new Mock<IQueries>();
                queryMock.Setup(m => m.Metric(
                        It.Is<QueryType>(q => q == QueryType.Count()),
                        It.Is<string>(c => c == testCol),
                        It.Is<string>(p => p == ""),
                        It.Is<QueryTimeframe>(t => t == null),
                        It.Is<IEnumerable<QueryFilter>>(f => f == filters),
                        It.Is<string>(z => z == "")))
                    .Returns(Task.FromResult("1"));

                client.Queries = queryMock.Object;
            }

            var count = await client.QueryAsync(QueryType.Count(), testCol, "", null, filters);
            Assert.IsNotNull(count);

            if (null != queryMock)
            {
                queryMock.VerifyAll();
            }
        }
Esempio n. 25
0
        public async void Query_ValidRelativeInterval_Success()
        {
            var client = new KeenClient(settingsEnv);
            var interval = QueryInterval.EveryNMinutes(5);
            var timeframe = QueryRelativeTimeframe.ThisMinute();
            IEnumerable<QueryIntervalValue<string>> result =
                new List<QueryIntervalValue<string>>() { new QueryIntervalValue<string>("0", DateTime.Now.AddMinutes(-5), DateTime.Now) };

            Mock<IQueries> queryMock = null;
            if (UseMocks)
            {
                queryMock = new Mock<IQueries>();
                queryMock.Setup(m => m.Metric(
                        It.Is<QueryType>(q => q == QueryType.Count()),
                        It.Is<string>(c => c == testCol),
                        It.Is<string>(p => p == ""),
                        It.Is<QueryTimeframe>(t => t == timeframe),
                        It.Is<QueryInterval>(i => i == interval),
                        It.Is<IEnumerable<QueryFilter>>(f => f == null),
                        It.Is<string>(z => z == "")))
                    .Returns(Task.FromResult(result));

                client.Queries = queryMock.Object;
            }

            var counts = (await client.QueryIntervalAsync(QueryType.Count(), testCol, "", timeframe, interval)).ToList();
            Assert.IsNotNull(counts);

            if (null != queryMock)
                queryMock.VerifyAll();
        }
Esempio n. 26
0
        public async void Funnel_ValidTimeframe_Success()
        {
            var client = new KeenClient(settingsEnv);
            var filters = new List<QueryFilter>() { new QueryFilter("field1", QueryFilter.FilterOperator.GreaterThan(), "1") };

            var funnelColA = "FunnelTestA";
            var funnelColB = "FunnelTestB";
            var funnelColC = "FunnelTestC";

            try
            {
                if (!UseMocks)
                {
                    client.DeleteCollection(funnelColA);
                    client.DeleteCollection(funnelColB);
                    client.DeleteCollection(funnelColC);
                }
            }
            catch (Exception)
            {
            }

            var timeframe = new QueryAbsoluteTimeframe(DateTime.Now, DateTime.Now.AddSeconds(2));

            if (!UseMocks)
            {
                client.AddEvent(funnelColA, new { id = "1" });
                client.AddEvent(funnelColA, new { id = "2" });
                client.AddEvent(funnelColA, new { id = "3" });

                client.AddEvent(funnelColB, new { id = "1" });
                client.AddEvent(funnelColB, new { id = "2" });

                client.AddEvent(funnelColC, new { id = "1" });
            }
            IEnumerable<FunnelStep> funnelsteps = new List<FunnelStep>()
            {
                new FunnelStep(){ EventCollection = funnelColA, ActorProperty = "id" },
                new FunnelStep(){ EventCollection = funnelColB, ActorProperty = "id" },
                new FunnelStep(){ EventCollection = funnelColC, ActorProperty = "id" },
            };
            IEnumerable<int> result = new List<int>() { 3, 2, 1 };


            Mock<IQueries> queryMock = null;
            if (UseMocks)
            {
                queryMock = new Mock<IQueries>();
                queryMock.Setup(m => m.Funnel(
                        It.IsAny<string>(),
                        It.Is<IEnumerable<FunnelStep>>(f => f == funnelsteps),
                        It.Is<QueryTimeframe>(t => t == null),
                        It.Is<string>(t => t == "")
                      ))
                  .Returns(Task.FromResult(result));

                client.Queries = queryMock.Object;
            }

            var reply = (await client.QueryFunnelAsync(testCol, funnelsteps, null)).ToList();

            if (null != queryMock)
                queryMock.VerifyAll();
        }
Esempio n. 27
0
        public async void ExtractResource_ValidRelative_Success()
        {
            var client = new KeenClient(settingsEnv);
            var timeframe = QueryRelativeTimeframe.ThisMinute();
            dynamic eo = new ExpandoObject();
            eo.field1 = "8888";
            IEnumerable<dynamic> result = new List<dynamic>() { eo, eo };

            Mock<IQueries> queryMock = null;
            if (UseMocks)
            {
                queryMock = new Mock<IQueries>();
                queryMock.Setup(m => m.Extract(
                        It.Is<string>(c => c == testCol),
                        It.Is<QueryRelativeTimeframe>(t => t == timeframe),
                        It.Is<IEnumerable<QueryFilter>>(f => f == null),
                        It.Is<int>(l => l == 0),
                        It.Is<string>(t => t == "")
                        ))
                    .Returns(Task.FromResult(result));

                client.Queries = queryMock.Object;
            }

            var reply = (await client.QueryExtractResourceAsync(testCol, timeframe)).ToList();

            if (null != queryMock)
                queryMock.VerifyAll();
        }
Esempio n. 28
0
        public async void ExtractResource_ValidFilter_Success()
        {
            var client = new KeenClient(settingsEnv);
            var filters = new List<QueryFilter>() { new QueryFilter("field1", QueryFilter.FilterOperator.GreaterThan(), "1") };
            dynamic eo = new ExpandoObject();
            eo.field1 = "8888";
            IEnumerable<dynamic> result = new List<dynamic>() { eo, eo };

            Mock<IQueries> queryMock = null;
            if (UseMocks)
            {
                queryMock = new Mock<IQueries>();
                queryMock.Setup(m => m.Extract(
                        It.Is<string>(c => c == testCol),
                        It.Is<QueryAbsoluteTimeframe>(t => t == null),
                        It.Is<IEnumerable<QueryFilter>>(f => f == filters),
                        It.Is<int>(l => l == 0),
                        It.Is<string>(t => t == "")
                      ))
                  .Returns(Task.FromResult(result));

                client.Queries = queryMock.Object;
            }

            var reply = (await client.QueryExtractResourceAsync(testCol, null, filters)).ToList();

            if (null != queryMock)
                queryMock.VerifyAll();
        }
Esempio n. 29
0
        public async void Query_ValidRelativeGroupInterval_Success()
        {
            var client = new KeenClient(settingsEnv);
            var timeframe = QueryRelativeTimeframe.PreviousNDays(2);
            var interval = QueryInterval.EveryNHours(2);
            var groupby = "field1";

            IEnumerable<QueryIntervalValue<IEnumerable<QueryGroupValue<string>>>> reply = new List<QueryIntervalValue<IEnumerable<QueryGroupValue<string>>>>()
            {
                new QueryIntervalValue<IEnumerable<QueryGroupValue<string>>>( 
                    new List<QueryGroupValue<string>>()
                    {
                        new QueryGroupValue<string>( "1", "field1" ),
                        new QueryGroupValue<string>( "1", "field1" ),
                    }, 
                    DateTime.Now, DateTime.Now.AddSeconds(2)
                ),
                new QueryIntervalValue<IEnumerable<QueryGroupValue<string>>>( 
                    new List<QueryGroupValue<string>>()
                    {
                        new QueryGroupValue<string>( "2", "field1" ),
                        new QueryGroupValue<string>( "2", "field1" ),
                    }, 
                    DateTime.Now, DateTime.Now.AddSeconds(2)
                ),
            };

            Mock<IQueries> queryMock = null;
            if (UseMocks)
            {
                queryMock = new Mock<IQueries>();
                queryMock.Setup(m => m.Metric(
                        It.Is<QueryType>(q => q == QueryType.Count()),
                        It.Is<string>(c => c == testCol),
                        It.Is<string>(p => p == ""),
                        It.Is<string>(g => g == groupby),
                        It.Is<QueryTimeframe>(t => t == timeframe),
                        It.Is<QueryInterval>(i => i == interval),
                        It.Is<IEnumerable<QueryFilter>>(f => f == null),
                        It.Is<string>(z => z == "")))
                    .Returns(Task.FromResult(reply));

                client.Queries = queryMock.Object;
            }

            var count = (await client.QueryIntervalGroupAsync(QueryType.Count(), testCol, "", groupby, timeframe, interval)).ToList();
            Assert.IsNotNull(count);

            if (null != queryMock)
            {
                queryMock.VerifyAll();
            }
        }
Esempio n. 30
0
        public async void MultiAnalysis_ValidRelativeTimeFrame_Success()
        {
            var client = new KeenClient(settingsEnv);
            var timeframe = QueryRelativeTimeframe.PreviousNDays(2);
            IEnumerable<MultiAnalysisParam> param = new List<MultiAnalysisParam>() 
            { 
                new MultiAnalysisParam("first", MultiAnalysisParam.Metric.Count()),
                new MultiAnalysisParam("second", MultiAnalysisParam.Metric.Maximum("field1")),
                new MultiAnalysisParam("third", MultiAnalysisParam.Metric.Minimum("field1")),
            };
            IDictionary<string, string> result = new Dictionary<string, string>();
            result.Add("second", "fff");
            result.Add("third", "aaa");
            result.Add("first", "123");

            Mock<IQueries> queryMock = null;
            if (UseMocks)
            {
                queryMock = new Mock<IQueries>();
                queryMock.Setup(m => m.MultiAnalysis(
                        It.Is<string>(c => c == testCol),
                        It.Is<IEnumerable<MultiAnalysisParam>>(p => p == param),
                        It.Is<QueryTimeframe>(t => t == timeframe),
                        It.Is<IEnumerable<QueryFilter>>(f => f == null),
                        It.Is<string>(tz => tz == "")
                      ))
                    .Returns(Task.FromResult(result));

                client.Queries = queryMock.Object;
            }

            var reply = await client.QueryMultiAnalysisAsync(testCol, param, timeframe, null, "");

            if (null != queryMock)
            {
                Assert.AreEqual(reply.Count(), result.Count());
                queryMock.VerifyAll();
            }
        }
Esempio n. 31
0
        public async void Query_ValidRelative_Success()
        {
            var client = new KeenClient(settingsEnv);
            var timeframe = QueryRelativeTimeframe.ThisMinute();

            Mock<IQueries> queryMock = null;
            if (UseMocks)
            {
                queryMock = new Mock<IQueries>();
                queryMock.Setup(m => m.Metric(
                        It.Is<QueryType>(q => q == QueryType.Count()),
                        It.Is<string>(c => c == testCol),
                        It.Is<string>(p => p == ""),
                        It.Is<QueryTimeframe>(t => t == timeframe),
                        It.Is<IEnumerable<QueryFilter>>(f => f == null),
                        It.Is<string>(z => z == "")))
                    .Returns(Task.FromResult("0"));

                client.Queries = queryMock.Object;
            }

            var count = await client.QueryAsync(QueryType.Count(), testCol, "", timeframe, null);
            Assert.IsNotNull(count);

            if (null != queryMock)
            {
                queryMock.VerifyAll();
            }
        }