OCMock: Setting expectations on properties - objective-c

How do I set an expectation on a property of an instance?
Let's say I have the following code:
id request = OCMClassMock([NSMutableURLRequest class]);
And I want to make sure that, in my implementation, the HTTPMethod property is set to #"Get", how would my test verify this?

Try something like this:
- (void)testNSURLConnection
{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://www.stackoverflow.com"]];
[request setHTTPMethod:#"POST"];
id connectionMock = OCMClassMock([NSURLConnection class]);
OCMStub([connectionMock connectionWithRequest:[OCMArg checkWithBlock:^BOOL(NSMutableURLRequest *request) {
XCTAssertTrue([request.HTTPMethod isEqualToString:#"GET"]);
return YES;
}] delegate:OCMOCK_ANY]);
[NSURLConnection connectionWithRequest:request delegate:nil];
}
This test will fail until your change #"POST" to #"GET" which is, I believe, what you want.

Related

How do i set multiple http header using sessionManager (AFNetworking)

I have searched through various stackoverflow questions and I got answer but using NSMutableURLRequest as there is one method - (void)addValue:(NSString *)value forHTTPHeaderField:(NSString *)field; which can be called over requestObject only.
How do I add value using _sessionManager.requestSerializer ?Or any work around. Here is the code which I am using for session configuration.
- (void)configureSesionManager {
_sessionManager = [AFHTTPSessionManager manager];
_sessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
_sessionManager.requestSerializer = [AFJSONRequestSerializer serializer];
_sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"application/json"];
_sessionManager.requestSerializer.timeoutInterval = 360;
if ([GSCommonUtil isUserLoggedIn]) {
authenticationHeader = [NSString stringWithFormat:#"Bearer %#",[GSCommonUtil retriveValueFromUserDefaults:kNSUserAuthenticationToken]];
[_sessionManager.requestSerializer setValue:authenticationHeader forHTTPHeaderField:#"Authorization"];
}
[_sessionManager.requestSerializer setValue:#"text/plain" forHTTPHeaderField:#"Content-Type"];
[_sessionManager.requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Accept"];
// I have to add one more HTTPHeader for #"Accept". How could I achieve it.
NSLog(#"Done with Session Manager Configuration!");
}
The Accept header takes a comma separated list, so something like this should work:
[_sessionManager.requestSerializer setValue:#"application/json, application/xml" forHTTPHeaderField:#"Accept"];
Obviously replace application/xml with whatever you need.

HTTPRequest for forum login - Objective C

I am trying to implement this code in Objective C:
Public Shared Function Login(ByVal Username As String, ByVal Password As String) As Boolean
Dim str As String = Func.ConvertToHex(Username)
Http.GetResponse("http://www.website.com/forum/login.php?do=login", String.Concat(New String() { "vb_login_username=", str, "&vb_login_password=", Password, "&cookieuser=1&s=&securitytoken=guest&do=login&vb_login_md5password=&vb_login_md5password_utf=" }))
If Http.ResponseValue.Contains(("Thank you for logging in, " & Username)) Then
Http.GetResponse("http://www.website.com/forum/usercp.php")
Return True
End If
Return False
End Function
This is what I've already done:
- (IBAction)loginButton:(id)sender {
NSURL *loginURL = [NSURL URLWithString:#"http://www.website.com/forum/login.php?do=login"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:loginURL];
[request setRequestMethod:#"POST"];
[request setUseKeychainPersistence:YES];
[request addPostValue:[self.usernameField stringValue] forKey:#"vb_login_username="];
[request addPostValue:[self.passwordField stringValue] forKey:#"&vb_login_password="];
[request setDelegate:self];
[request setTimeOutSeconds:60];
[request startSynchronous];
[request setUseSessionPersistence:YES];
}
- (void)requestFailed:(ASIHTTPRequest *)request {
NSLog(#"Request failed: %#",[request error]);
}
- (void)requestFinished:(ASIHTTPRequest *)request
{
NSLog(#"Submitted form successfully");
NSLog(#"Response was:");
NSLog(#"%#",[request responseString]);
}
But it does not work..
I get a reply back but not as a member.
P.S. It's about a vBulletin Forum
Sorry for my bad english..
Thanks in advance!
Hard to try to reproduce with no server to test. However two things:
lib which you use is depreciated, consider moving for other (for example AFNetworking)
in second parameter you have "&vb_login_password=" I believe there should be no '&' character. Also try to remove '=' at end.
If there is no HTTPS you can use wireshark to check packets from program which work, and from your version. Then compare both request and seek for differences.
It now works. I've added some more entries.
[request addPostValue:#"1" forKey:#"cookieuser"];
[request addPostValue:#"login" forKey:#"do"];
[request addPostValue:#"" forKey:#"s"];
[request addPostValue:#"guest" forKey:#"securitytoken"];
[request addPostValue:#"" forKey:#"vb_login_md5password"];
[request addPostValue:#"" forKey:#"vb_login_md5password_utf"];
[request addPostValue:[self.passwordField stringValue] forKey:#"vb_login_password"];
[request addPostValue:[self.usernameField stringValue] forKey:#"vb_login_username"];
I now get the HTML code from the forum back to a point where it says "Thank you for logging in, Username".

argument-passing from iOS to WCF service

I need to pass information from the application to the server, specifically a and b in text format. Here is the code the WCF service:
public class iOSService
{
// To use HTTP GET, add [WebGet] attribute. (Default ResponseFormat is WebMessageFormat.Json)
// To create an operation that returns XML,
// add [WebGet(ResponseFormat=WebMessageFo rmat.Xml)],
// and include the following line in the operation body:
// WebOperationContext.Current.Outgoin gResponse.ContentType = "text/xml";
[OperationContract]
public void DoWork()
{
// Add your operation implementation here
return;
}
// Add more operations here and mark them with [OperationContract]
[OperationContract]
public string iOSTest2(string a, string b)
{
string res = "";
try
{
res=(int.Parse(a) + int.Parse(b)).ToString();
}
catch (Exception exp)
{
res = "Not a number";
}
return res;
}
}
After receiving a and b, the server adds them, and sends back their sum.
And here is my code to send parameters to the server of an iOS application:
- (IBAction)test:(id)sender {
NSArray *propertyNames = [NSArray arrayWithObjects:#"23", #"342", nil];
NSArray *propertyValues = [NSArray arrayWithObjects:#"a", #"b", nil];
NSDictionary *properties = [NSDictionary dictionaryWithObjects:propertyNames forKeys:propertyValues];
NSMutableArray * arr;
arr=[[NSMutableArray alloc]initWithObjects:properties, nil];
NSLog(#"%#",arr);
NSError * error;
NSData *jsonData2 = [NSJSONSerialization dataWithJSONObject:arr options:NSJSONWritingPrettyPrinted error:&error];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://www.mathforyou.net/iOSservice.svc/iOSTest2"]];
NSString *jsonString = [[NSString alloc] initWithData:jsonData2 encoding:NSUTF8StringEncoding];
[request setValue:#"appliction/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:jsonData2];
NSLog(#"JSON String: %#",jsonString);
NSError *errorReturned = nil;
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&errorReturned];
if (errorReturned) {
//...handle the error
NSLog(#"error");
}
else {
NSString *retVal = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"%#",retVal);
}
}
But the server answers me the following message:
"ExceptionDetail":null,"ExceptionType":null,"Message":"The server was unable to process the request due to an internal error. For more information about the error, either turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the <serviceDebug> configuration behavior) on the server in order to send the exception information back to the client, or turn on tracing as per the Microsoft .NET Framework SDK documentation and inspect the server trace logs.","StackTrace":null
And here is the logs from Xcode:
2013-03-01 17:38:28.657 2231233122[3442:c07] (
{
a = 23;
b = 342;
}
)
2013-03-01 17:38:28.659 2231233122[3442:c07] JSON String: [
{
"a" : "23",
"b" : "342"
}
]
2013-03-01 17:38:29.054 2231233122[3442:c07] {"ExceptionDetail":null,"ExceptionType":null,"Message":"The server was unable to process the request due to an internal error. For more information about the error, either turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the <serviceDebug> configuration behavior) on the server in order to send the exception information back to the client, or turn on tracing as per the Microsoft .NET Framework SDK documentation and inspect the server trace logs.","StackTrace":null}
P.S. I asked a friend to help me, but since he does not know objective-c wrote a program just for C++ and the code works, so the problem is not in the server. Here is the code:
string data = "{\"a\":\"560\",\"b\":\"90\"}";
byte[] bd = Encoding.UTF8.GetBytes(data);
HttpWebRequest wr = (HttpWebRequest)HttpWebRequest.Create("http://www.mathforyou.net/IOSService.svc/iOSTest2");
wr.ContentType = "application/json";
wr.Method = "POST";
wr.ContentLength = bd.Length;
Stream sw = wr.GetRequestStream();
sw.Write(bd, 0, bd.Length);
sw.Close();
HttpWebResponse resp = (HttpWebResponse)wr.GetResponse();
Stream s = resp.GetResponseStream();
byte[] bres = new byte[resp.ContentLength];
s.Read(bres, 0, bres.Length);
string ans = Encoding.UTF8.GetString(bres);
Console.WriteLine(ans);
Please help, I'm worn out.
If you copied and pasted the code, it looks like you might have misspelled your Content-Type value. It should be application/json, you have it as appliction/json.
Also, I'm not sure if this matters, but you're also not setting the content length explicitly. I am not sure if setHTTPBody: does that for you.
I'm not sure if you still need this, but try the following:
[request addValue:#"application/json; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setValue:jsonString forHTTPHeaderField:#"json"]; //<-- I added this line
[request setHTTPMethod:#"POST"];
[request setHTTPBody:jsonData2];

JSON Payload doesnt seem to be sending

My problem I'm pretty positive is simple, I must just be missing something.. just not sure what.
I can send GET and POST for granular elements (this=that kind of stuff), but a web service call I need to send data too, takes a raw JSON block, with no "key"
Heres the method I wrote:
-(NSData *)execute {
// Smart Chooser ?
if(PostData.count >0 || Payload != nil)
[self setMethod:UPLINK_METHOD_POST];
else
[self setMethod:UPLINK_METHOD_GET];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:self.connectionUrl
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
timeoutInterval:10];
if([UPLINK_METHOD_GET isEqualToString:self.connectionMethod])
[request setHTTPMethod:#"GET"];
else
[request setHTTPMethod:#"POST"];
NSString *gData = [self compileGetData];
NSString *pData = [self compilePostData];
// if we have get data, set it into the URL string
if(GetData.count > 0) {
[self setURLWithString:[[self.connectionUrl absoluteString] stringByAppendingString:[#"?" stringByAppendingString:gData]]];
[request setURL:self.connectionUrl];
}
// if we have post data, set it in the body
if(PostData.count > 0) {
const char *bytes = [[NSString stringWithString:pData] UTF8String];
[request setHTTPBody:[NSData dataWithBytes:bytes length:strlen(bytes)]];
}
// Override any post data if a payload is already defined.
if(Payload != nil) {
[request setHTTPBody:[Payload dataUsingEncoding:NSUTF8StringEncoding]];
}
NSLog(#"URL : %#", request.URL);
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
if(err != nil)
NSLog(#"here was an error: %#", err);
return responseData;
}
-(NSDictionary *)executeAsJSON
{
NSData *responseData = [self execute];
NSError *e;
return [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&e];
}
Ok SO, the way this thing works, is that it automatically sets whether the request is POST or GET depending on the data provided in the GetData, PostData, and Payload vars.
The request is GET by default, but turns into POST if PostData or Payload have anything in them.
The compileGetData and compilePostData mostly just bring back formatted strings with arrays of information combined, nothing special there.
But thats not where the problem is.
See, "Payload" overrides anything "PostData" had in it. If you had provided PostData elements into the class, it would just be overridden by a provided Payload if that does exist.
I needed to provide this to demonstrate the "workarea" as it exists right now, its not linearly provided information.
This is the area of interest:
// Override any post data if a payload is already defined.
if(Payload != nil) {
//const char *plbytes = [[NSString stringWithString:Payload] UTF8String]; // this didn't work
[request setHTTPBody:[Payload dataUsingEncoding:NSUTF8StringEncoding]]; // inline, doesn't work either
}
When I say "doesnt work", what I mean is, im getting back an error JSON array from the webservice that basically means "hey, wheres the payload?". If the request is not POST it comes back as a general error, so thats all working, the URL is then obviously correct.
I've used RESTConsole for Chrome to test the webservice to make sure its working properly, and it does.
I've also checked through the debugger the exact payload im sending, i copy+pasted that into RESTConsole, and it works there.
I'm.. honestly at a loss here...
Try using a web proxy like Charles or Wireshark (I personally preferr Charles due to it's ease of use, it's a 30-day trial though) and monitor the request you make from RESTConsole and the one you make from your app and see if they look the same.
Check any headers, line returns and anything else that looks different.
That's the best I can think of to start with

ASIFormDataRequest - iOS Application. How do I RETRIEVE a post variable

So I have this url that leads to a .php
So far I managed to retrieve every single thing except the actual XML that I want. the XML is stored in a variable called _xml.
if($this->outMethod=="" || $this->outMethod=="POST") //Default to POST
{
$_POST["_xml"] = $_xml;
}
So I've already set the outMethod to POST but I don't understand how to retrieve the value within _xml.
- (void)grabURLInBackground
{
NSLog(#"grab url in background");
NSURL *url = [NSURL URLWithString:#"xxxxxxxxxxx"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:#"POST" forKey:#"outMethod"];
[request setPostValue:#"1" forKey:#"Entity_ID"];
[request setDelegate:self];
[request startAsynchronous];
NSLog(#"end of grabUrlInBackgroun");
}
don't worry the URL is right I just don't want to post it.
- (void)requestFinished:(ASIHTTPRequest *)request
{
NSLog(#"A");
// Use when fetching text data
NSString *responseString = [request responseString];
// Use when fetching binary data
NSData *responseData = [request responseData];
if(responseString)
{
NSLog(#"responseData is not null");
}
NSLog(#"response string: %#", responseString);
//NSLog(#"%#", responseString);
}
What I get back is that the request is good, but there is no response in responseString. This is because my php does not want to print out any of the XML on screen in HTML but it stores the result in the variable _xml sent via post "$_POST["_xml"] = $_xml
My question is, how do I get back that xml variable? Isn't there a method available within the ASIHTTPRequest library? I am using ASIFormDataRequest class not ASIHTTPRequest.
You have to print you variable in the php-file:
if($this->outMethod=="" || $this->outMethod=="POST") //Default to POST
{
echo $_xml;
}
A HTTPRequest (and the ASIFormDataRequest as well) isn't interested in any variables you declare in your *.php file. It only returns the string you actually print.