Exemplo n.º 1
2
        private CustomResponse HttpRequest(IRestRequest request, string url, Dictionary<string, string> parameters = null)
        {
            try
            {
                IRestClient client = new RestClient();
                IRestResponse response = new RestResponse();

                client.BaseUrl = new Uri(url);
                if (parameters != null)
                {
                    foreach (var item in parameters)
                    {
                        request.AddParameter(item.Key, item.Value);
                    }
                }
                response = client.Execute(request);
                var myResponse = new CustomResponse();
                myResponse.StatusCode = response.StatusCode;
                myResponse.Content = response.Content;
                return myResponse;
            }
            catch(Exception ex)
            {
                throw ex;
            }
            
        }
        public void Deserialize_ShouldBeAbleToHandle_NullDateTimeValues()
        {
            var response = new RestResponse { Content = "[{\"closed_at\":null}]" };
            var serializer = new CustomJsonSerializer();
            var issues = serializer.Deserialize<List<Issue>>(response);

            Assert.IsNull(issues[0].ClosedAt);
        }
        public void ListAll_PerformsCorrectRequest()
        {
            //Setup
            var request = new CategoriesStub("DevKey", "api.careerbuilder.com", "", "");

            //Mock crap
            var response = new RestResponse<List<Category>> {Data = new List<Category>()};

            var restReq = new Mock<IRestRequest>();
            restReq.Setup(x => x.AddParameter("DeveloperKey", "DevKey"));
            restReq.Setup(x => x.AddParameter("CountryCode", "NL"));
            restReq.SetupSet(x => x.RootElement = "Categories");

            var restClient = new Mock<IRestClient>();
            restClient.SetupSet(x => x.BaseUrl = "https://api.careerbuilder.com/v1/categories");
            restClient.Setup(x => x.Execute<List<Category>>(It.IsAny<IRestRequest>())).Returns(response);

            request.Request = restReq.Object;
            request.Client = restClient.Object;

            //Assert
            List<Category> cats = request.WhereCountryCode(CountryCode.NL).ListAll();
            Assert.IsTrue(cats.Count == 0);
            restReq.VerifyAll();
            restClient.VerifyAll();
        }
Exemplo n.º 4
0
        private void DeserializeJSONString()
        {
            RestSharp.RestResponse response = new RestSharp.RestResponse();
            response.Content = "{\"has_title\":true,\"title\":\"GoodLuck\",\"entries\":[[\"/getting started.pdf\",{\"thumb_exists\":false,\"path\":\"/Getting Started.pdf\",\"client_mtime\":\"Wed, 08 Jan 2014 18:00:54 +0000\",\"bytes\":249159}],[\"/task.jpg\",{\"thumb_exists\":true,\"path\":\"/Ta sk.jpg\",\"client_mtime\":\"Tue, 14 Jan 2014 05:53:57 +0000\",\"bytes\":207696}]]}";

            RestSharp.Deserializers.JsonDeserializer deserializer = new RestSharp.Deserializers.JsonDeserializer();
            Store objFromJson = deserializer.Deserialize <Store>(response);

            bool   has_title = objFromJson.has_title;
            string title     = objFromJson.title;
            List <List <object> > entries = objFromJson.entries;

            foreach (List <object> item in entries)
            {
                for (int i = 0; i < item.Count(); i++)
                {
                    Type t = item[i].GetType();
                    if (t == typeof(Dictionary <string, object>))
                    {
                        Dictionary <string, object> entry = (Dictionary <string, object>)item[i];
                        foreach (var obj in entry)
                        {
                            string key   = obj.Key;
                            string value = obj.Value.ToString();
                        }
                    }
                    else
                    {
                        string fileName = item[i].ToString();
                    }
                }
            }
        }
        public void GetRecommendations_PerformsCorrectRequest() {
            //Setup
            var request = new JobRecWithUserPrefRequestStub("J1234567890123456789", "U1234567890123456789",
                "DevKey", "api.careerbuilder.com", "", "");

            //Mock crap
            var response = new RestResponse<List<RecommendJobResult>> { Data = new List<RecommendJobResult>() };

            var restReq = new Mock<IRestRequest>();
            restReq.Setup(x => x.AddParameter("DeveloperKey", "DevKey"));
            restReq.Setup(x => x.AddParameter("JobDID", "J1234567890123456789"));
            restReq.Setup(x => x.AddParameter("UserDID", "U1234567890123456789"));
            restReq.SetupSet(x => x.RootElement = "RecommendJobResults");

            var restClient = new Mock<IRestClient>();
            restClient.SetupSet(x => x.BaseUrl = "https://api.careerbuilder.com/v1/recommendations/forjobwithuserprefs");
            restClient.Setup(x => x.Execute<List<RecommendJobResult>>(It.IsAny<IRestRequest>())).Returns(response);

            request.Request = restReq.Object;
            request.Client = restClient.Object;

            //Assert
            List<RecommendJobResult> resp = request.GetRecommendations();
            restReq.VerifyAll();
            restClient.VerifyAll();
        }
Exemplo n.º 6
0
		private void OnContentReceived(string content) {
			JsonDeserializer deserializer = new JsonDeserializer();

			var response = new RestResponse();
			response.Content = content;

			MessageContent messageContent = null;
			try {
				messageContent = deserializer.Deserialize<MessageContent>(response);
			} catch {
				MessageContent = null;
			}

			if (messageContent != null) {
				MessageContent = messageContent;

				if (Event == "message" || Event == "comment") {
					ExtractedBody = messageContent.Text;
				}
			} else if(Event == "message") {
				ExtractedBody = content;
			}

			Displayable = ExtractedBody != null;

			TimeStamp = UnixTimeToLocal(Sent);
		}
Exemplo n.º 7
0
        public void JSONDeserializationTest() {
            var path = Path.Combine(Environment.CurrentDirectory, "Schedule.json");
            var ds = new JsonDeserializer();
            var response = new RestResponse() { ContentType = "application/json", ResponseStatus = ResponseStatus.Completed, StatusCode = System.Net.HttpStatusCode.OK };

            // Read the file as one string.
            StreamReader myFile = new StreamReader(path);
            string json = myFile.ReadToEnd();
            myFile.Close();

            response.Content = json;

            var mySchedule = ds.Deserialize<Schedule>(response);

            Assert.IsNotNull(mySchedule);
            Assert.IsNotNull(mySchedule.escalation_policies);

            Assert.AreEqual("FS4LEQD", mySchedule.id);
            Assert.AreEqual("24x7 Schedule", mySchedule.name);
            Assert.AreEqual("UTC", mySchedule.time_zone);
            Assert.AreEqual(new DateTime(635726880000000000), mySchedule.today);
            Assert.AreEqual(1, mySchedule.escalation_policies.Count);
            Assert.AreEqual("PAD5HK6", mySchedule.escalation_policies[0].id);
            Assert.AreEqual("Escalation Policy - 24x7", mySchedule.escalation_policies[0].name);
        }
        public void Submit_PerformsCorrectRequest()
        {
            //setup
            var request = new SavedSearchCreateRequestStub("DevKey", "api.careerbuilder.com", "", "", 12345);
            var dummyApp = new SavedSearchCreate();
            dummyApp = SetUpApp(dummyApp);

            //Mock
            var response = new RestResponse<SavedSearchCreateResponse> { Data = new SavedSearchCreateResponse(), ResponseStatus = ResponseStatus.Completed };
            var restReq = new Mock<IRestRequest>();
            restReq.Setup(x => x.AddBody(dummyApp));

            

            var restClient = new Mock<IRestClient>();
            restClient.SetupSet(x => x.BaseUrl = "https://api.careerbuilder.com/v2/SavedSearch/Create");
            restClient.Setup(x => x.Execute<SavedSearchCreateResponse>(It.IsAny<IRestRequest>())).Returns(response);

            request.Request = restReq.Object;
            request.Client = restClient.Object;

            //Assertions
            SavedSearchCreateResponse rest = request.Submit(dummyApp);
            restReq.VerifyAll();
            restClient.VerifyAll();
        }
Exemplo n.º 9
0
        public void JSONDeserializationTest() {
            var path = Path.Combine(Environment.CurrentDirectory, "Incident.json");
            var ds = new JsonDeserializer();
            var response = new RestResponse() { ContentType = "application/json", ResponseStatus = ResponseStatus.Completed, StatusCode = System.Net.HttpStatusCode.OK };

            // Read the file as one string.
            StreamReader myFile = new StreamReader(path);
            string json = myFile.ReadToEnd();
            myFile.Close();
            
            response.Content = json;

            var myAlert = ds.Deserialize<Incident>(response);

            Assert.IsNotNull(myAlert);
            Assert.IsNotNull(myAlert.service);
            Assert.IsNotNull(myAlert.last_status_change_by);
            
            Assert.AreEqual("1", myAlert.incident_number);
            Assert.AreEqual(new DateTime(634830005610000000), myAlert.created_on);
            Assert.AreEqual("resolved", myAlert.status);
            Assert.AreEqual("https://acme.pagerduty.com/incidents/P2A6J96", myAlert.html_url);
            Assert.AreEqual(null, myAlert.incident_key);
            Assert.AreEqual(null, myAlert.assigned_to_user);
            Assert.AreEqual("https://acme.pagerduty.com/incidents/P2A6J96/log_entries/P2NQP6P", myAlert.trigger_details_html_url);
            Assert.AreEqual(new DateTime(634830006590000000), myAlert.last_status_change_on);
        }
        public void Retrieve_AddsProperHeaders()
        {
            //Setup
            var site = new TargetSiteMock("10.0.0.1") { SetHost = "api.koolkid.com", SetSecure = true };
            site.SetHeaders.Add("ILikeHeaders", "true");

            var request = new BlankAppStub("JXXXXXXXXXXXXXXXXXX", "DevKey", "api.careerbuilder.com", "",site);

            //Mock crap
            var response = new RestResponse<BlankApplication> {Data = new BlankApplication()};

            var restReq = new Mock<IRestRequest>();
            restReq.Setup(x => x.AddHeader("Host", "api.koolkid.com"));
            restReq.Setup(x => x.AddHeader("ILikeHeaders", "true"));
            restReq.Setup(x => x.AddParameter("DeveloperKey", "DevKey"));
            restReq.Setup(x => x.AddParameter("JobDID", "JXXXXXXXXXXXXXXXXXX"));
            restReq.SetupSet(x => x.RootElement = "BlankApplication");

            var restClient = new Mock<IRestClient>();
            restClient.SetupSet(x => x.BaseUrl = "https://10.0.0.1/v1/application/blank");
            restClient.Setup(x => x.Execute<BlankApplication>(It.IsAny<IRestRequest>())).Returns(response);

            request.Request = restReq.Object;
            request.Client = restClient.Object;

            //Assert
            BlankApplication resp = request.Retrieve();
            restReq.VerifyAll();
            restClient.VerifyAll();
        }
        public void Submit_PerformsCorrectRequest()
        {
            //setup
            var request = new SavedSearchRetrieveRequestStub("DevKey", "api.careerbuilder.com", "", "", 12345);
            var dummyApp = new SavedSearchRetrieveRequestModel();

            //Mock
            var response = new RestResponse<SavedSearchRetrieveResponseModel> { Data = new SavedSearchRetrieveResponseModel(), ResponseStatus = ResponseStatus.Completed };
            var restReq = new Mock<IRestRequest>();

            restReq.Setup(x => x.AddParameter("DeveloperKey", dummyApp.DeveloperKey));
            restReq.Setup(x => x.AddParameter("ExternalUserID", dummyApp.ExternalUserID));
            restReq.Setup(x => x.AddParameter("ExternalID", dummyApp.ExternalID));



            var restClient = new Mock<IRestClient>();
            restClient.SetupSet(x => x.BaseUrl = "https://api.careerbuilder.com/v1/SavedSearch/retrieve");
            restClient.Setup(x => x.Execute<SavedSearchRetrieveResponseModel>(It.IsAny<IRestRequest>())).Returns(response);

            request.Request = restReq.Object;
            request.Client = restClient.Object;

            //Assertions
            SavedSearchRetrieveResponseModel rest = request.Submit(dummyApp);
            restReq.VerifyAll();
            restClient.VerifyAll();
        }
        public object Deserialize(RestResponse response)
        {
            var root = XDocument.Parse(response.Content).Root;
            var cities = root.Descendants("cities");

            var result = new CitySearchResult()
            {
                Cities = new SearchResultsList<City>()
                {
                    Total = int.Parse(root.Attribute("total").Value),
                    Page = int.Parse(root.Attribute("page").Value),
                    ItemsPerPage = int.Parse(root.Attribute("itemsPerPage").Value)
                }
            };

            result.Cities.AddRange(cities.Select(city => new City()
            {
                State = city.Attribute("state").Value,
                StateCode = city.Attribute("stateCode").Value,
                Name = city.Attribute("name").Value,
                Id = city.Attribute("id").Value,
                Coords = new Coordinates()
                {
                    Lat = double.Parse(city.Element("coords").Attribute("lat").Value),
                    Long = double.Parse(city.Element("coords").Attribute("long").Value)
                },
                Country = new Country()
                {
                    Code = city.Element("country").Attribute("code").Value,
                    Name = city.Element("country").Attribute("name").Value
                }
            }));

            return result;
        }
		public MercadolibreItemsClientTest()
		{
			this.restClientMock = new Mock<MercadolibreRestClient> { CallBase = true };
			var response = new RestResponse<MeliSearchingData<Item>> { Data = new MeliSearchingData<Item>() };
			this.restClientMock.Setup(x => x.Execute<MeliSearchingData<Item>>(It.IsAny<IRestRequest>())).Returns(response);
			this.mercadolibreItemsClient = new MercadolibreItemsClient(this.restClientMock.Object);
		}
Exemplo n.º 14
0
        public void JSONDeserializationTest() {
            var path = Path.Combine(Environment.CurrentDirectory, "User.json");
            var ds = new JsonDeserializer();
            var response = new RestResponse() { ContentType = "application/json", ResponseStatus = ResponseStatus.Completed, StatusCode = System.Net.HttpStatusCode.OK };

            // Read the file as one string.
            StreamReader myFile = new StreamReader(path);
            string json = myFile.ReadToEnd();
            myFile.Close();

            response.Content = json;

            var myUser = ds.Deserialize<User>(response);

            Assert.IsNotNull(myUser);


            Assert.AreEqual("PT23IWX", myUser.id);
            Assert.AreEqual("Tim Wright", myUser.name);
            Assert.AreEqual("*****@*****.**", myUser.email);
            Assert.AreEqual("Eastern Time (US & Canada)", myUser.time_zone);
            Assert.AreEqual("purple", myUser.color);
            Assert.AreEqual("owner", myUser.role);
            Assert.AreEqual("https://secure.gravatar.com/avatar/923a2b907dc04244e9bb5576a42e70a7.png?d=mm&r=PG", myUser.avatar_url);
            Assert.AreEqual("/users/PT23IWX", myUser.user_url);
            Assert.AreEqual(false, myUser.invitation_sent);
            Assert.AreEqual(false, myUser.marketing_opt_out);
        }
Exemplo n.º 15
0
        /// <summary>
        /// Override the method which does the actually call against the Tictail API using REST client
        /// These are both 3-party and should be working just fine
        /// </summary>
        /// <param name="request">RestRequst, is not needed for this</param>
        /// <returns>A RestResonse object</returns>
        protected override IRestResponse RestRequest(IRestRequest request)
        {
            IRestResponse response = new RestResponse();
            response.StatusCode = StatusCode;
            response.ResponseStatus = ResponseStatus;
            response.Content = Content;

            if (ResponseHeaders == null)
            {
                return response;
            }

            foreach (var header in ResponseHeaders)
            {
                response.Headers.Add(new Parameter()
                {
                    Name = header.Key,
                    Value = header.Value,
                    Type = ParameterType.HttpHeader
                });

            }

            return response;
        }
        public void Retrieve_PerformsCorrectRequest()
        {
            //Setup
            var request = new BlankAppStub("JXXXXXXXXXXXXXXXXXX", "DevKey", "api.careerbuilder.com", "", "");

            //Mock crap
            var response = new RestResponse<BlankApplication> {Data = new BlankApplication()};

            var restReq = new Mock<IRestRequest>();
            restReq.Setup(x => x.AddParameter("DeveloperKey", "DevKey"));
            restReq.Setup(x => x.AddParameter("JobDID", "JXXXXXXXXXXXXXXXXXX"));
            restReq.SetupSet(x => x.RootElement = "BlankApplication");

            var restClient = new Mock<IRestClient>();
            restClient.SetupSet(x => x.BaseUrl = "https://api.careerbuilder.com/v1/application/blank");
            restClient.Setup(x => x.Execute<BlankApplication>(It.IsAny<IRestRequest>())).Returns(response);

            request.Request = restReq.Object;
            request.Client = restClient.Object;

            //Assert
            BlankApplication resp = request.Retrieve();
            restReq.VerifyAll();
            restClient.VerifyAll();
        }
Exemplo n.º 17
0
        public void CallApiAsync_ShouldCallOnError_IfRestRequestDoesNotCompleteSuccessfully()
        {
            var mockFactory = new Mock<IRestClientFactory>(MockBehavior.Strict);
            var mockRestClient = new Mock<IRestClient>(MockBehavior.Strict);
            var mockProcessor = new Mock<IResponseProcessor>(MockBehavior.Strict);
            var response = new RestResponse<object>();
            var exception = new GitHubException(new GitHubResponse(response), ErrorType.NoNetwork);
            mockFactory.Setup<IRestClient>(f => f.CreateRestClient(It.IsAny<string>())).Returns(mockRestClient.Object);
            mockRestClient
                .Setup(c => c.ExecuteAsync<object>(It.IsAny<IRestRequest>(),
                                                   It.IsAny<Action<RestResponse<object>, RestRequestAsyncHandle>>()))
                .Returns(_testHandle)
                .Callback<IRestRequest,
                          Action<RestResponse<object>,
                          RestRequestAsyncHandle>>((r, c) => c(response, _testHandle));
            mockRestClient.SetupSet(c => c.Authenticator = It.IsAny<IAuthenticator>());
            mockProcessor.Setup(p => p.TryProcessResponseErrors(It.IsAny<IGitHubResponse>(),
                                                                out exception))
                         .Returns(true);
            var client = CreateClient(mockFactory.Object, mockProcessor.Object);

            var onErrorInvoked = false;
            client.CallApiAsync<object>(new GitHubRequest("foo", API.v3, NGitHub.Web.Method.GET),
                                        o => { },
                                        e => onErrorInvoked = true);

            Assert.IsTrue(onErrorInvoked);
        }
        public void GetRecommendations_PerformsCorrectRequest()
        {
            //Setup
            UserReqStub request = new UserReqStub("ExternalID", "DevKey", "api.careerbuilder.com", "", "");

            //Mock crap
            RestResponse<List<RecommendJobResult>> response = new RestResponse<List<RecommendJobResult>>();
            response.Data = new List<RecommendJobResult>();
            
            var restReq = new Mock<IRestRequest>();
            restReq.Setup(x => x.AddParameter("DeveloperKey", "DevKey"));
            restReq.Setup(x => x.AddParameter("ExternalID", "ExternalID"));
            restReq.SetupSet(x => x.RootElement = "RecommendJobResults");

            var restClient = new Mock<IRestClient>();
            restClient.SetupSet(x => x.BaseUrl = "https://api.careerbuilder.com/v1/recommendations/foruser");
            restClient.Setup(x => x.Execute<List<RecommendJobResult>>(It.IsAny<IRestRequest>())).Returns(response);

            request.Request = restReq.Object;
            request.Client = restClient.Object;

            //Assert//
            List<RecommendJobResult> resp = request.GetRecommendations();
            restReq.VerifyAll();
            restClient.VerifyAll();
        }
Exemplo n.º 19
0
        public void RunSubmitAdRequest_Returns_Empty_List_If_No_Ads()
        {
            var mockery = new MockRepository();
              var restClient = mockery.StrictMock<IRestClient>();
              var restRequestFactory = mockery.StrictMock<IRestRequestFactory>();
              var restRequest = mockery.StrictMock<IRestRequest>();
              var serializer = mockery.Stub<ISerializer>();

              var str = "some data";

              var adRequest = new AdRequest { NetworkId = Guid.NewGuid().ToString() };

              var advertisementResponse = new AdvertisementResponseMessage { advertisement = null };
              var restResponse = new RestResponse<AdvertisementResponseMessage>();
              restResponse.Data = advertisementResponse;

              using (mockery.Record()) {
            Expect.Call(restRequestFactory.Create(null, Method.POST))
              .Constraints(Is.Anything(), Is.Equal(Method.POST))
              .Return(restRequest);
            restRequest.RequestFormat = DataFormat.Json;
            Expect.Call(restRequest.JsonSerializer).Return(serializer);
            Expect.Call(serializer.Serialize(null)).Constraints(
              Rhino.Mocks.Constraints.Property.Value("network_id", adRequest.NetworkId) &&
              Is.TypeOf<AdRequestMessage>()
            ).Return(str);
            Expect.Call(restRequest.AddParameter("text/json", str, ParameterType.RequestBody)).Return(new RestRequest());
            Expect.Call(restClient.Execute<AdvertisementResponseMessage>(restRequest)).Return(restResponse);
              }

              using (mockery.Playback()) {
            var results = new AdRequestor(restClient, restRequestFactory).RunSubmitAdRequest(adRequest);
            Assert.IsEmpty(results);
              }
        }
Exemplo n.º 20
0
		public RestResponse ExecuteDELETEWithAuthorization(string query, string signature) {
			RestClient client = new RestClient(this.Server.ServerAddress);
			RestRequest request = CreateRequest(query, Method.DELETE, signature);

			RestResponse response = (RestResponse)client.Execute(request);
			this.LastResponse = response;
			return response;
		}
Exemplo n.º 21
0
		private void GivenFitBitResponseIs(HttpStatusCode httpStatusCode, string content)
		{
			var restResponse = new RestResponse();
			restResponse.StatusCode = httpStatusCode;
			restResponse.Content =
				content;
			_client.Setup(x => x.Execute(It.IsAny<IRestRequest>())).Returns(restResponse);
		}
        public void ValidateUserInformation()
        {
            //Given
            var mockRestClient = new Mock <RestSharp.RestClient>();
            var response       = new RestSharp.RestResponse();
            var username       = "******";

            dynamic fakeUserInformation = new
            {
                login            = username,
                name             = "name",
                company          = "company",
                blog             = "blog",
                twitter_username = username,
                html_url         = "html_url",
                public_repos     = "public_repos",
                created_at       = "created_at",
                updated_at       = "updated_at",
            };

            var expectedUser = new UserInformation {
                Login          = fakeUserInformation.login,
                FullName       = fakeUserInformation.name,
                Company        = fakeUserInformation.company,
                Blog           = fakeUserInformation.blog,
                TwitterAccount = fakeUserInformation.twitter_username,
                GitHubPage     = fakeUserInformation.html_url,
                PublicRepos    = fakeUserInformation.public_repos,
                CreationDate   = fakeUserInformation.created_at,
                LastUpdate     = fakeUserInformation.updated_at,
            };

            response.Content = JsonConvert.SerializeObject(fakeUserInformation);

            mockRestClient.Setup(m =>
                                 m.Execute(It.IsAny <RestRequest>()))
            .Returns(response);

            var connector = new GitHubConnector(mockRestClient.Object);

            //When
            var result = connector.GetUserInformation(username);

            //Then
            Assert.Equal(expectedUser.Login, result.Login);
            Assert.Equal(expectedUser.FullName, result.FullName);
            Assert.Equal(expectedUser.Company, result.Company);
            Assert.Equal(expectedUser.Blog, result.Blog);
            Assert.Equal(expectedUser.TwitterAccount, result.TwitterAccount);
            Assert.Equal(expectedUser.GitHubPage, result.GitHubPage);
            Assert.Equal(expectedUser.PublicRepos, result.PublicRepos);
            Assert.Equal(expectedUser.CreationDate, result.CreationDate);
            Assert.Equal(expectedUser.LastUpdate, result.LastUpdate);
            Assert.NotEmpty(expectedUser.ToString());

            mockRestClient.Verify(m =>
                                  m.Execute(It.IsAny <RestRequest>()), Times.Exactly(1));
        }
Exemplo n.º 23
0
            public Constructor()
            {
                var response = new RestResponse();
                response.Headers.Add(new Parameter { Name = "X-RateLimit-Limit", Value = "60", Type = ParameterType.HttpHeader });
                response.Headers.Add(new Parameter { Name = "X-RateLimit-Remaining", Value = "54", Type = ParameterType.HttpHeader });
                response.Headers.Add(new Parameter { Name = "X-RateLimit-Reset", Value = "1372700873", Type = ParameterType.HttpHeader });

                this._subject = new API.RateLimitHeader(response);
            }
Exemplo n.º 24
0
        public void TestGetPerson()
        {
            var personResponse = new RestResponse<Person> {Data = new Person {Name = "name_1"}};
            restClient.Execute<Person>(Arg.Is<IRestRequest>(request =>
                request.Method == Method.GET && request.Resource == "people/{id}" && request.Parameters[0].Name == "id" && request.Parameters[0].Value.Equals("2")
                )).Returns(personResponse);

            var people = client.GetPerson(2);
            people.Data.Should().Be(personResponse.Data);
        }
Exemplo n.º 25
0
        public void TestGetPeople()
        {
            var persons = new RestResponse<List<Person>> { Data = new List<Person>() { new Person { Name = "name_1" }, new Person { Name = "name_2" } } };
            restClient.Execute<List<Person>>(Arg.Is<IRestRequest>(request =>
                request.Method == Method.GET && request.Resource == "people"
                )).Returns(persons);

            RestResponse<List<Person>> people = client.GetPeople();
            people.Data.Should().Equal(persons.Data);
        }
Exemplo n.º 26
0
            public void SmokeTest()
            {
                var jsonResponse = new RestResponse
                {
                    Content = "{\"t\":\"2012-01-01T00:00:01.000+00:00\",\"v\":12.34}"
                };

                var result = JsonDeserializationTests.deserializer.Deserialize<DataPoint>(jsonResponse);
                Assert.AreEqual(new DataPoint(new DateTime(2012, 1, 1, 0, 0, 1).ToLocalTime(), 12.34), result);
            }
Exemplo n.º 27
0
        public void Get_Should_Return_Null_If_IRestClient_Method_Get_Response_HttpStatusCode_Its_Not_Ok(HttpStatusCode code)
        {
            IRestResponse moqReturn = new RestResponse();
            moqReturn.StatusCode = code;

            _mockIRestClient.Setup(x => x.Execute(It.IsAny<IRestRequest>())).Returns(moqReturn);

            var actual = _service.Get("SE16");

            Assert.IsNull(actual);
        }
Exemplo n.º 28
0
        public void AddressNotFoundShouldThrowException()
        {
            var restResponse = new RestResponse
            {
                Content = "{\"code\":\"IP_ADDRESS_NOT_FOUND\", \"error\":\"The value 1.2.3.16 is not in the database.\"}",
                ResponseUri = new Uri("http://foo.com/omni/1.2.3.4"),
                StatusCode = (HttpStatusCode)404
            };

            RunClientGivenResponse(restResponse);
        }
Exemplo n.º 29
0
        /// <summary>
        /// A method that will throw an exception which looks like {"error":"invalid_request","error_description":"The authorization code was not found or was already used"}
        /// This error is thrown when trying to authorize an OAuth code that has already been used.
        /// </summary>
        public void ThrowOAuthCodeUsedException()
        {
            var response = new RestResponse()
            {
                RawBytes = Encoding.UTF8.GetBytes("{\"error\":\"invalid_request\",\"error_description\":\"The authorization code was not found or was already used\"}"),
                StatusCode = HttpStatusCode.NotAcceptable,
                StatusDescription = "Not Acceptable"
            };

            RequestEngine.CheckResponseExceptions(response);
        }
Exemplo n.º 30
0
        public void Can_Deserialize_artistGetPastEvents()
        {
            var xmlpath = Environment.CurrentDirectory + @"\..\..\..\Lastfm.Tests\Responses\Artist\artistGetPastEvents.xml";
            var doc = XDocument.Load(xmlpath);
            var response = new RestResponse { Content = doc.ToString() };

            var d = new XmlAttributeDeserializer();
            var output = d.Deserialize<LastfmResponse<EventsList>>(response);

            Assert.AreEqual("Blur", output.Value.Events[2].Headliner);
        }
Exemplo n.º 31
0
        public InsightsResponse RunClientGivenResponse(RestResponse response)
        {
            response.ContentLength = response.Content.Length;

            var restClient = MockRepository.GenerateStub<IRestClient>();

            restClient.Stub(r => r.Execute(Arg<IRestRequest>.Is.Anything)).Return(response);

            var wsc = new WebServiceClient(0, "abcdef", new List<string> { "en" });
            return wsc.Insights("1.2.3.4", restClient);
        }
        public JsonResultTasks GetTasks(string projectId)
        {
            try {
                RestSharp.RestResponse response = DoRequest("projects/" + projectId + "/tasks?status=all", "task");
                ProjectsReply = response.Content.ToString();
                return(Newtonsoft.Json.JsonConvert.DeserializeObject <JsonResultTasks>(ProjectsReply));
            }
            catch (Exception e)
            {
                SlackClient client = new SlackClient("");
                client.PostMessage("PWF API Tool Error: " + e.ToString(), "PWF API Admin", "C9X3YGW5B");

                return(null);
            }
        }
        public JsonResultTimes GetTime(string timeFrom, string timeTo)
        {
            try
            {
                RestSharp.RestResponse response = DoRequest("time?trackedfrom=" + timeFrom + "&trackedto=" + timeTo, "time");
                ProjectsReply = response.Content.ToString();
                return(Newtonsoft.Json.JsonConvert.DeserializeObject <JsonResultTimes>(ProjectsReply));
            }
            catch (Exception e)
            {
                SlackClient client = new SlackClient("");
                client.PostMessage("PWF API Tool Error: " + e.ToString(), "PWF API Admin", "C9X3YGW5B");

                return(null);
            }
        }
Exemplo n.º 34
0
        public List <DiscordMessage> GetMessages()
        {
            var client  = new RestClient("https://discordapp.com/api/v6");
            var request = new RestRequest("/channels/348697779436126209/messages");

            client.Authenticator = new HttpBasicAuthenticator("349610917966905345", "Ho_POj-p6Ex-cCLZW-f3NxDg9bDqKZvJ");
            var response = new RestSharp.RestResponse();

            Task.Run(async() =>
            {
                response = await GetResponseContentAsync(client, request) as RestSharp.RestResponse;
            }).Wait();

            JObject jsonResponse = JsonConvert.DeserializeObject <JObject>(response.Content);
            var     messageList  = JsonConvert.DeserializeObject <List <DiscordMessage> >(jsonResponse["messages"].ToString());

            return(messageList);
        }
Exemplo n.º 35
0
        private static async Task <string> GetDataAsync(string url)
        {
            String decoded = null;

            RestSharp.RestResponse p = default(RestSharp.RestResponse);
            byte[] b          = new byte[0];
            var    client     = new RestClient("http://localhost/WCFREST/SytechService.svc");
            var    request    = new RestRequest("/GetPeople", Method.GET);
            var    restClient = new RestClient(url);
            var    obj        = await client.ExecuteTaskAsync(request);

            try
            {
                b       = obj.RawBytes;
                decoded = Encoding.UTF8.GetString(b);
            }
            catch (Exception ex)
            {
            }
            return(decoded);
        }
Exemplo n.º 36
0
        private static async Task PutDataAsync()
        {
            String decoded = null;

            RestSharp.RestResponse p = default(RestSharp.RestResponse);
            byte[] b = new byte[0];

            var         client  = new RestClient("http://localhost/WCFREST/SytechService.svc/SaveIdea");
            RestRequest request = new RestRequest(Method.POST);

            request.RequestFormat = DataFormat.Json;
            request.AddHeader("Accept", "application/json");


            IdeaText idea = new IdeaText {
                Idea = "What a great one!"
            };

            /*
             * MemoryStream ms = new MemoryStream();
             * DataContractJsonSerializer serializerToUpload = new DataContractJsonSerializer(typeof(Idea));
             * serializerToUpload.WriteObject(ms, idea);
             */

            request.AddJsonBody(idea);

            var obj = await client.ExecuteTaskAsync(request);

            try
            {
                b       = obj.RawBytes;
                decoded = Encoding.UTF8.GetString(b);
            }
            catch (Exception ex)
            {
            }
        }
Exemplo n.º 37
0
        private async Task <RestResponse <T> > ConvertToRestResponse <T>(IRestRequest request, HttpResponseMessage httpResponse)
        {
            if (httpResponse == null)
            {
                throw new ArgumentNullException("HttpResponseMessage value was Null in ConvertToRestResponse function");
            }

            var restResponse = new RestResponse <T>();

            restResponse.Content = await httpResponse.Content.ReadAsStringAsync();

            restResponse.ContentLength = restResponse.Content.Length;
            if (!string.IsNullOrEmpty(restResponse.Content))
            {
                restResponse.RawBytes = Encoding.UTF8.GetBytes(restResponse.Content);
            }

            if (httpResponse.IsSuccessStatusCode)
            {
                restResponse.ResponseStatus = ResponseStatus.Completed;   //   Always Completed if get this far.  Will set error in Try/Catch
            }
            else
            {
                restResponse.ResponseStatus = ResponseStatus.Error;
            }



            restResponse.StatusCode        = (System.Net.HttpStatusCode)httpResponse.StatusCode;
            restResponse.StatusDescription = httpResponse.ReasonPhrase;
            restResponse.Request           = request;

            if (httpResponse.Content.Headers.ContentType != null)
            {
                restResponse.ContentType = httpResponse.Content.Headers.ContentType.MediaType;
            }

            //  Cookies will be returned via the headers here.
            foreach (var header in httpResponse.Headers)
            {
                switch (header.Key)
                {
                case "Set-Cookie":      //  Could parse this out to the cookie collection but not right now.
                default:
                    restResponse.Headers.Add(new Parameter {
                        Name = header.Key, Value = header.Value, Type = ParameterType.HttpHeader
                    });
                    break;
                }
            }

            //   Try and Deserialize here
            IDeserializer deserializer = GetHandler(restResponse.ContentType);

            if (deserializer != null)
            {
                restResponse.Data = deserializer.Deserialize <T>(restResponse);
            }



            return(restResponse);
        }
Exemplo n.º 38
0
        public Task <BaseRestSharp.RestResponse> InvokeCall(HttpServiceRequest httpRequest, bool throwException = true,
                                                            bool isElasticLog = false, bool invokeAsync = false)
        {
            ServicePointManager.DefaultConnectionLimit = 200;
            // Base URL
            BaseRestSharp.RestClient    client   = new BaseRestSharp.RestClient(httpRequest.Url);
            BaseRestSharp.IRestResponse response = null;
            Stopwatch watch = new Stopwatch();


            // Method to be triggered
            BaseRestSharp.RestRequest request = new BaseRestSharp.RestRequest(httpRequest.Action, (BaseRestSharp.Method)httpRequest.MethodType)
            {
                Timeout = httpRequest.Timeout
            };

            if (httpRequest.CookieJar != null)
            {
                foreach (Cookie cookie in httpRequest.CookieJar)
                {
                    request.AddCookie(cookie.Name, cookie.Value);
                }
            }

            if (httpRequest.Body != null)
            {
                request.RequestFormat = BaseRestSharp.DataFormat.Json;
                request.AddJsonBody(httpRequest.Body);
            }

            if (httpRequest.Headers != null)
            {
                foreach (KeyValuePair <string, string> header in httpRequest.Headers.ToList())
                {
                    request.AddHeader(header.Key, header.Value);
                }
            }


            if (httpRequest.QueryStringParameters != null)
            {
                foreach (KeyValuePair <string, string> param in httpRequest.QueryStringParameters.ToList())
                {
                    request.AddQueryParameter(param.Key, param.Value);
                }
            }

            watch.Start();

            BaseRestSharp.RestResponse customRestResponse = null;
            TaskCompletionSource <BaseRestSharp.RestResponse> taskCompletionSource = new TaskCompletionSource <BaseRestSharp.RestResponse>();


            response = client.Execute(request);
            watch.Stop();

            taskCompletionSource.SetResult(customRestResponse);

            ResponseVerifications(response, throwException, httpRequest.Url, httpRequest.MethodType);


            return(taskCompletionSource.Task);
        }
Exemplo n.º 39
0
        public async Task <int> UpdateFilesBatch(ObservableFileSystem fileSystem, int sensorId, int start, int rows, CancellationToken cancelToken = default(CancellationToken))
        {
            ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); };
            var client = new RestClient();

            client.BaseUrl = new System.Uri(iCrt_01.Properties.Resources.CBMasServer);
            var filereq = new RestRequest();

            filereq.AddHeader("X-Auth-Token", iCrt_01.Properties.Resources.CBApiKey);
            filereq.Resource = "/v1/process?start={start}&rows={rows}&q=sensor_id:{sensorID} and filemod_count:[1 TO *]&sort=start asc";
            filereq.AddParameter("start", start, ParameterType.UrlSegment);
            filereq.AddParameter("rows", rows, ParameterType.UrlSegment);
            filereq.AddParameter("sensorID", sensorId, ParameterType.UrlSegment);

            var queryForPidsResponse = client.Execute <CBResult>(filereq);

            if (cancelToken.IsCancellationRequested)
            {
                return(-1);
            }
            if (queryForPidsResponse.StatusCode != System.Net.HttpStatusCode.OK)
            {
                throw new ApplicationException(String.Format("Could not get process batch for sensor id:{0}, start:{1}, rows:{2} - HTTP Code {3}",
                                                             sensorId, start, rows, queryForPidsResponse.StatusCode));
            }
            else
            {
                int resultCount = 0;
                foreach (var item in queryForPidsResponse.Data.results)
                {
                    RestSharp.RestResponse response = new RestSharp.RestResponse();
                    response.Content = item;
                    RestSharp.Deserializers.JsonDeserializer deserial = new JsonDeserializer();
                    var result = deserial.Deserialize <CBProcess>(response);

                    var processId = result.id;
                    var segmentId = result.segment_id;
                    var eventreq  = new RestRequest();
                    eventreq.AddHeader("X-Auth-Token", iCrt_01.Properties.Resources.CBApiKey);
                    eventreq.Resource = (String.Format("/v1/process/{0}/{1}/event", processId, segmentId));
                    var queryForEventsResponse = await client.ExecuteTaskAsync <CBResultProc>(eventreq, cancelToken);

                    if (queryForEventsResponse.StatusCode != System.Net.HttpStatusCode.OK)
                    {
                        // do something
                    }
                    else
                    {
                        foreach (var filemod in queryForEventsResponse.Data.process)
                        {
                            if (filemod.filemod_complete == null)
                            {
                                continue;
                            }
                            else
                            {
                                try
                                {
                                    foreach (string evt in filemod.filemod_complete)
                                    {
                                        var evtParts = evt.Split('|');
                                        int type     = Convert.ToInt32(evtParts[0]);
                                        fileSystem.AddFileSystemItem(evtParts[2], evtParts[1], type);
                                    }
                                }
                                catch
                                {
                                    continue;
                                }
                            }
                        }
                    }
                    resultCount++;

                    if (cancelToken.IsCancellationRequested)
                    {
                        return(resultCount);
                    }
                }

                return(resultCount);
            }
        }
        private IRestResponse<T, E, C> Deserialize<T, E, C>(IRestRequest request, IRestResponse raw)
        {
            request.OnBeforeDeserialization(raw);

            IRestResponse<T, E, C> response = new RestResponse<T, E, C>();
            try
            {
                response = raw.toAsyncResponse<T, E, C>();
                response.Request = request;

                // Only attempt to deserialize if the request has not errored due
                // to a transport or framework exception.  HTTP errors should attempt to 
                // be deserialized 

                if (response.ErrorException == null)
                {
                    IDeserializer handler = GetHandler(raw.ContentType);
                    handler.RootElement = request.RootElement;
                    handler.DateFormat = request.DateFormat;
                    handler.Namespace = request.XmlNamespace;

                    response.Data = handler.Deserialize<T>(raw);
                }
            }
            catch (InvalidOperationException ex)
            {
                if (response.ErrorException == null)
                {
                    try
                    {
                        IDeserializer handler = GetHandler(raw.ContentType);
                        handler.RootElement = request.RootElement;
                        handler.DateFormat = request.DateFormat;
                        handler.Namespace = request.XmlNamespace;

                        response.Error = handler.Deserialize<E>(raw);
                    }
                    catch (InvalidOperationException ex1)
                    {
                        if (response.ErrorException == null)
                        {
                            IDeserializer handler = GetHandler(raw.ContentType);
                            handler.RootElement = request.RootElement;
                            handler.DateFormat = request.DateFormat;
                            handler.Namespace = request.XmlNamespace;

                            response.ExtraData = handler.Deserialize<C>(raw);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                response.ResponseStatus = ResponseStatus.Error;
                response.ErrorMessage = ex.Message;
                response.ErrorException = ex;
            }
            finally
            {
                response.ErrorException = response.ErrorException != null ? response.ErrorException : raw.ErrorException;
                response.ResponseStatus = response.ResponseStatus != null ? response.ResponseStatus : raw.ResponseStatus;
            }

            return response;
        }
Exemplo n.º 41
0
 public T Deserialize <T>(RestSharp.RestResponse response) where T : new()
 {
     return(Deserialize <T>(response.Content));
 }
Exemplo n.º 42
0
        private void ProcessResponse(IRestRequest request, HttpResponse httpResponse, RestRequestAsyncHandle asyncHandle, Action <IRestResponse, RestRequestAsyncHandle> callback)
        {
            RestResponse arg = ConvertToRestResponse(request, httpResponse);

            callback(arg, asyncHandle);
        }
        public void Search_PerformsCorrectRequest()
        {
            //Setup
            JobSearchStub request = new JobSearchStub("DevKey", "api.careerbuilder.com","","");
            
            //Mock crap
            RestResponse<ResponseJobSearch> response = new RestResponse<ResponseJobSearch>();
            response.Data = new ResponseJobSearch();
                        
            var restReq = new Mock<IRestRequest>();
            restReq.Setup(x => x.AddParameter("DeveloperKey", "DevKey"));
            restReq.Setup(x => x.AddParameter("CountryCode", "NL"));
            restReq.SetupSet(x => x.RootElement = "ResponseJobSearch");

            var restClient = new Mock<IRestClient>();
            restClient.SetupSet(x => x.BaseUrl = "https://api.careerbuilder.com/v1/jobsearch");
            restClient.Setup(x => x.Execute<ResponseJobSearch>(It.IsAny<IRestRequest>())).Returns(response);

            request.Request = restReq.Object;
            request.Client = restClient.Object;
            
            //Assert
            ResponseJobSearch resp = request.WhereCountryCode(CountryCode.NL).Search();
            restReq.Verify();
            restClient.VerifyAll();
        }