GithubHelp home page GithubHelp logo

kleinlieu / hklsocketstubserver Goto Github PK

View Code? Open in Web Editor NEW

This project forked from ebricks/hklsocketstubserver

0.0 2.0 0.0 43 KB

A fake TCP server for iOS testing, similar to NLTHTTPStubServer

License: Other

Ruby 1.88% Objective-C 98.12%

hklsocketstubserver's Introduction

HKLSocketStubServer License MIT

HKLSocketStubServer is a fake TCP server for iOS testing.

Can register fake response by expect or stub.

// e.g.) Respond a string if incoming data start with the string
[[[server expect] forDataString:@"incoming data(left-hand match)"] respondsString:@"response data"];
// e.g.) Response a data when 3-way handshake is finished
NSData *data = [@"did connect.\0" dataUsingEncoding:NSUTF8StringEncoding];
[[[server expect] respondsWhenAccepted:data];

This is strongly inspired by awesome NLTHTTPStubServer which is written by yaakaito.

Features

  • Fake TCP server runs on iOS device/simulator
  • Responds a specified data for specified incoming data via TCP
  • Uses a prefix search

System requirements

  • iOS 6.0 or higher (older version may be also available, but not tested yet)

Installation

If you install HKLSocketStubServer manually, then just add HKLSocketStubServer subdirectory to your project.

I'm preparing CocoaPods spec now...

Usage

Write the following code at the top of your TestCase.

#import "HKLSocketStubServer.h"

The most simply test example using GCDAsyncSocket is as follows.

  • Get the shared server. the default URL is localhost:54321.
  • register the response data for specified data
  • Send a data to HKLSocketStubServer via TCP. Receive the response.
  • Verify the all expects are invoked

Saying it simply, you change the server URL from real to fake.

static dispatch_semaphore_t _sem_testResponse;
static NSString *_str_response;

- (void)testResponse
{
    HKLSocketStubServer *stubServer = [HKLSocketStubServer sharedServer];

    // Register fake response for incoming "foo" string
    [[[[stubServer expect] forDataString:@"foo"] respondsString:@"bar"];

    // GCDAsyncSocket: Setup async socket.
    GCDAsyncSocket *sock = [[GCDAsyncSocket alloc]
                            initWithDelegate:self
                            delegateQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)];
    [sock connectToHost:@"localhost" onPort:kHKLDefaultListenPort+5 error:nil];

    // Wait a response from HKLSocketStubServer
    _sem_testResponse = dispatch_semaphore_create(0);
    long result = dispatch_semaphore_wait(_sem_testResponse,
                                          dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)));

    // Check the response
    XCTAssertEqual(result, 0, @"should get result immediately.");
    XCTAssertEqualObjects(@"bar", _str_response,
                          @"Received data should be [bar].");

    // Verify all responses have been sent.
    XCTAssertNoThrow([server verify], @"all fake responses have been sent.");

    _str_testRespondsResourceOfType = nil;
}

// GCDAsyncSocketDelegate
- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port
{
    // Send "foo" data to server.
    NSData *data = [@"foo" dataUsingEncoding:NSUTF8StringEncoding];
    [sock readDataWithTimeout:-1 tag:0]; // Start reading without timeout
    [sock writeData:data withTimeout:-1 tag:0];
}

- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
    // Store the received string(should be "bar") and signal to the main thread.
    _str_response = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    dispatch_semaphore_signal(_sem_testResponse);
}
@end

Basics

Get a server instance and clear

Get shared instance.

HKLSocketStubServer *server =[HKLSocketStubServer sharedServer];

Remove all fake responses.

[server clear];

Expecations and verifycation

[[server expect] forData:[@"something binary data" dataUsingEncoding:NSUTF8StringEncoding]];

Register fake response. Server will response this fake if requested /fake. After this setup the functionality under test should be invoked followed by

[server verify];

When expected responses have not been invoked, verify method will raise an exception.

Stubs

[[server stub] forDataString:@"bar"]

stub is similar to expect, But stub remains server response queue after invoked it. Therefore, verify ignores response that registered by stub.

Complicated response

Simulate waiting

// e.g.) Send response after 10 sec.
[[[server stub] forDataString:@"heavy command"] andProcessingTime:10.0f];

Check incoming data in blocks

// e.g.) Log the data from client.
[[[stubServer expect] forData:data] andCheckData:^(NSData *data) {
        NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"Received %@", str);
    }];

NLTHTTPStubServer architecture is also available for your understanding.

License

HKLSocketStubServer is available under the MIT license. See the LICENSE file for more info.

hklsocketstubserver's People

Contributors

hirohitokato avatar

Watchers

Klein Lieu avatar James Cloos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.