2014年7月23日 星期三

iOS 開發筆記 - 使用 GCDAsyncSocket / AsyncSocket 之處理 Partial Data 的用法

原本想寫寫 BSD Socket 的,再搭配 dispatch_async 其實也能運作的很好,但讓我想起去年底面試一間新創時,被問到有沒有用過 GCDAsyncSocket 的心得,看來用用已經常見的 framework / library 已是一種流行的或組織文化吧?至少接手的人可以有一樣的思維而不用再去認識另一個 coding style 吧!

把玩 GCDAsyncSocket 時,一開始試用了 readDataToData 函數,但發現這東西不是我想要的,也就是 server 沒有吐出預設字元(newline)時,程式端無法處理已接收的資料,但可以得知已經接收多少 Partial Data (可用在回報下載、上傳進度)。爾後用一些關鍵字(partial data)找找,發現也有人有這種需求:Is there a way to get partial data read and clear the buffer?

原來會有這種困惑只是不懂 GCDAsyncSocket 設計架構,搞懂後就一切安好啦。

There are 3 methods of reading data using GCDAsyncSocket / AsyncSocket:
  • readDataWithTimeout : reads chunks of data as they arrive
  • readDataToLength : read a specific length of data before returning result
  • readDataToData : read until finding a specific terminator

對於不能確定 Server 回傳的資料長度或特徵的行為,就適合採用 readDataWithTimeout 方式 :)

- (GCDAsyncSocket*)asyncSocket {
if(!_asyncSocket)
_asyncSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_queue_create("socket", NULL)];
return _asyncSocket;
}

- (NSMutableData *)buffer {
if (!_buffer) {
_buffer = [[NSMutableData alloc] init];
}
return _buffer;
}

- (void)viewDidLoad {
[super viewDidLoad];

if (![self.asyncSocket connectToHost:@"ServerIP" onPort:80 error:&error]) {
NSLog(@"ERROR: %@", error);
}
}

- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port {
NSLog(@"didConnectToHost");
[sock readDataWithTimeout:-1 buffer:self.buffer bufferOffset:[self.buffer length] tag:1];
}

- (void)socket:(GCDAsyncSocket *)sock didReadPartialDataOfLength:(NSUInteger)partialLength tag:(long)tag {
NSLog(@"didReadPartialDataOfLength");
}

- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {
NSLog(@"didReadData(%lu): %@", tag, @([data length]));
[self.buffer setLength:0];
[sock readDataWithTimeout:-1 buffer:self.buffer bufferOffset:[self.buffer length] tag:tag];
}

- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err {
NSLog(@"socketDidDisconnect: %@", err);
}

- (void)socketDidSecure:(GCDAsyncSocket *)sock {
NSLog(@"socketDidSecure");
}

- (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag {
NSLog(@"didWriteDataWithTag");
}

iOS 開發筆記 - 使用 UITapGestureRecognizer / UISwipeGestureRecognizer 偵測 UIView Click/Tap/Swipe Event (手指點擊、滑動事件)

沒把玩過,趁颱風天筆記一下 :P

One Click (Single Tap):

- (void)viewDidLoad {
[super viewDidLoad];
UITapGestureRecognizer *tapGestureRecognizer;
tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTap:)];
tapGestureRecognizer.numberOfTapsRequired = 1;
[self.view addGestureRecognizer:tapGestureRecognizer];
}

- (void)singleTap:(UIGestureRecognizer *)recognizer {
NSLog(@"singleTap: %@", NSStringFromCGPoint([recognizer locationInView:[recognizer.view superview]]));
}


Double Click (Double Tap):

- (void)viewDidLoad {
[super viewDidLoad];
UITapGestureRecognizer *tapGestureRecognizer;
tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleTap:)];
tapGestureRecognizer.numberOfTapsRequired = 2;
[self.view addGestureRecognizer:tapGestureRecognizer];
}

- (void)doubleTap:(UIGestureRecognizer *)recognizer {
NSLog(@"doubleTap: %@", NSStringFromCGPoint([recognizer locationInView:[recognizer.view superview]]));
}


Swipe Up:

- (void)viewDidLoad {
[super viewDidLoad];
UISwipeGestureRecognizer *swipeGestureRecognizer;
swipeGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeUp:)];
swipeGestureRecognizer.direction = UISwipeGestureRecognizerDirectionUp;
[self.view addGestureRecognizer:swipeGestureRecognizer];
}

- (void)swipeUp:(UIGestureRecognizer *)recognizer {
NSLog(@"swipeUp: %@", NSStringFromCGPoint([recognizer locationInView:[recognizer.view superview]]));
}


Swipe Down:

- (void)viewDidLoad {
[super viewDidLoad];
UISwipeGestureRecognizer *swipeGestureRecognizer;
swipeGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeDown:)];
swipeGestureRecognizer.direction = UISwipeGestureRecognizerDirectionDown;
[self.view addGestureRecognizer:swipeGestureRecognizer];
}

- (void)swipeDown:(UIGestureRecognizer *)recognizer {
NSLog(@"swipeDown: %@", NSStringFromCGPoint([recognizer locationInView:[recognizer.view superview]]));
}


Swipe Left:

- (void)viewDidLoad {
[super viewDidLoad];
UISwipeGestureRecognizer *swipeGestureRecognizer;
swipeGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeLeft:)];
swipeGestureRecognizer.direction = UISwipeGestureRecognizerDirectionLeft;
[self.view addGestureRecognizer:swipeGestureRecognizer];
}

- (void)swipeLeft:(UIGestureRecognizer *)recognizer {
NSLog(@"swipeLeft: %@", NSStringFromCGPoint([recognizer locationInView:[recognizer.view superview]]));
}


Swipe Right:

- (void)viewDidLoad {
[super viewDidLoad];
UISwipeGestureRecognizer *swipeGestureRecognizer;
swipeGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeRight:)];
swipeGestureRecognizer.direction = UISwipeGestureRecognizerDirectionRight;
[self.view addGestureRecognizer:swipeGestureRecognizer];
}

- (void)swipeRight:(UIGestureRecognizer *)recognizer {
NSLog(@"swipeRight: %@", NSStringFromCGPoint([recognizer locationInView:[recognizer.view superview]]));
}


其他部分,大概是注意 UIView 跟 UIViewController 內定已經有把 events 接收處理的事項,例如 UIScrollView 就有捲動事件,假設 UIScrollView 只有提供左右捲動的功能,那就偵測不到 SwipeLeft 跟 SwipeRight ,但 SwipeUp 跟 SwipeDown 仍可以。而 Single Tap 跟 Double Tap 之間,基本上兩者存在時,點擊兩下的過程中,Single Tap Action 跟 Double Tap Action 都會被執行,並且 Single Tap Action 會先被執行。

2014年7月22日 星期二

[CPP] Incremental Test Case for C++ Usage via Google Test @ Ubuntu 14.04

既然做了 Unit Test 了,就希望 Test Case 可以不斷地累積下來。昨晚跟總監級的高手閒聊工作瑣事,以 Python 跟 MongoDB 的互動為例,其實 PyMono 很多操作都還是撰寫 Javascript ,只是從 Python 發動罷了,這時候最佳的設計是讓 Javascript 獨立出來,如此一來可以切割工作出來,讓把玩 Javascript 就專心把玩,而不要每次要改 Javascript 時,還得去動 Python code。

這樣的情境跟 Test Case 有點類似,有沒有辦法讓 Test case 增加時,不必動到測試的邏輯程式?解法就是把 Test Case 用目錄管理,每次做 Unit Test 時,是去掃目錄的檔案出來即可。

片段程式碼:

#include <dirent.h>
bool getFiles(std::string dir, std::vector<std::string> &files) {
        DIR *dp;
        struct dirent *dirp;
        if((dp  = opendir(dir.c_str())) == NULL)
                return false;
        while ((dirp = readdir(dp)) != NULL)
                if(dirp->d_name && dirp->d_name[0] != '.')
                        files.push_back(dir+"/"+std::string(dirp->d_name));
        closedir(dp);
        return true;
}

const std::string testcase_dir_Func1 = "testcase_dir";
TEST(MyJob, testFunc1) {
        std::vector<std::string> testcase;
        std::string dirTarget = testcase_dir_Func1;
        ASSERT_EQ(getFiles(dirTarget,testcase), true);
        ASSERT_EQ(testcase.size() > 0, true);
        for(int i=0 ; i<testcase.size() ; ++i) {
                std::fstream input(testcase[i], std::fstream::binary|std::fstream::in);
                std::stringstream buffer;
                buffer << input.rdbuf();
                ASSERT_EQ(buffer.str().length() > 10, true);

// ...
        }
}

2014年7月21日 星期一

[CPP] Unit Test for C++ Usage via Google Test @ Ubuntu 14.04

跟友人閒聊把玩 CPP 的心得,就被推坑到 Google test 啦:Google C++ Testing Framework

看一下簡介就...準備跳槽了 XD

Who Is Using Google Test?

In addition to many internal projects at Google, Google Test is also used by the following notable projects:
  • The Chromium projects (behind the Chrome browser and Chrome OS)
  • The LLVM compiler
  • Protocol Buffers (Google's data interchange format)
安裝:

$ sudo apt-get install cmake libgtest-dev
$ mkdir gtest && cd gtest
$ cmake /usr/src/gtest/
-- The CXX compiler identification is GNU 4.8.2
-- The C compiler identification is GNU 4.8.2
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Found PythonInterp: /usr/bin/python (found version "2.7.6")
-- Looking for include file pthread.h
-- Looking for include file pthread.h - found
-- Looking for pthread_create
-- Looking for pthread_create - not found
-- Looking for pthread_create in pthreads
-- Looking for pthread_create in pthreads - not found
-- Looking for pthread_create in pthread
-- Looking for pthread_create in pthread - found
-- Found Threads: TRUE
-- Configuring done
-- Generating done
-- Build files have been written to: /path/gtest

$ make
Scanning dependencies of target gtest
[ 50%] Building CXX object CMakeFiles/gtest.dir/src/gtest-all.cc.o
Linking CXX static library libgtest.a
[ 50%] Built target gtest
Scanning dependencies of target gtest_main
[100%] Building CXX object CMakeFiles/gtest_main.dir/src/gtest_main.cc.o
Linking CXX static library libgtest_main.a
[100%] Built target gtest_main

$ sudo cp *.a /usr/lib


試用:

$ vim gtest.cpp
#include <gtest/gtest.h>

int main(int argc, char** argv) {
        testing::InitGoogleTest(&argc, argv);
        return RUN_ALL_TESTS();
}
$ g++ gtest.cpp -lgtest -lpthread
$ ./a.out
[==========] Running 0 tests from 0 test cases.
[==========] 0 tests from 0 test cases ran. (0 ms total)
[  PASSED  ] 0 tests.


測試失敗範例:

$ vim gtest.cpp
#include <gtest/gtest.h>

TEST(MyJob, Action1) {
    ASSERT_EQ(0, 1);
}

int main(int argc, char** argv) {
        testing::InitGoogleTest(&argc, argv);
        return RUN_ALL_TESTS();
}


$ g++ gtest.cpp -lgtest -lpthread
$ ./a.out

[==========] Running 1 test from 1 test case.
[----------] Global test environment set-up.
[----------] 1 test from MyJob
[ RUN      ] MyJob.Action1
gtest.cpp:4: Failure
Value of: 1
Expected: 0
[  FAILED  ] MyJob.Action1 (1 ms)
[----------] 1 test from MyJob (1 ms total)

[----------] Global test environment tear-down
[==========] 1 test from 1 test case ran. (1 ms total)
[  PASSED  ] 0 tests.
[  FAILED  ] 1 test, listed below:
[  FAILED  ] MyJob.Action1

 1 FAILED TEST


測試成功的範例:

$ vim gtest.cpp
#include <gtest/gtest.h>

TEST(MyJob, Action1) {
    ASSERT_EQ(0, 0);
}

int main(int argc, char** argv) {
        testing::InitGoogleTest(&argc, argv);
        return RUN_ALL_TESTS();
}


$ g++ gtest.cpp -lgtest -lpthread
$ ./a.out

[==========] Running 1 test from 1 test case.
[----------] Global test environment set-up.
[----------] 1 test from MyJob
[ RUN      ] MyJob.Action1
[       OK ] MyJob.Action1 (0 ms)
[----------] 1 test from MyJob (0 ms total)

[----------] Global test environment tear-down
[==========] 1 test from 1 test case ran. (1 ms total)
[  PASSED  ] 1 test.

2014年7月19日 星期六

[CPP] Unit Test for C++ Usage via CppUnit @ Ubuntu 14.04

隨著時間越來越少後,不知不覺更在意"成果"是否能夠年年累積。想了一會兒後,最佳的方式就是引進軟工管理,除了最基本的版本控制外,幫自己把玩的小玩意 open source 及增加 reuse 的機會也很重要,維護方面則是從簡易人眼的測試改成更制式的 unit test 架構,最好能夠定時批次測試等。只不過採用制式的 unit test 不見得適合 startup 環境,畢竟時間寶貴,有些 prototype 生命週期很短。

在此以 CppUnit 為例,筆記一下怎樣快速使用,更多簡介請參考 CppUnit 文件。

安裝:

$ sudo apt-get install libcppunit-dev

$ vim t.cpp
#include <cppunit/ui/text/TestRunner.h>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/TestResult.h>
#include <cppunit/CompilerOutputter.h>
#include <cppunit/TestResultCollector.h>
#include <cppunit/BriefTestProgressListener.h>

class SampleTest : public CppUnit::TestFixture {
private:
int a;
public:
void setUp() {
a = 0;
}
void tearDown() {
a = 0;
}
static CppUnit::Test *suite() {
CppUnit::TestSuite *suiteOfTests = new CppUnit::TestSuite( "SampleTest" );
suiteOfTests->addTest( new CppUnit::TestCaller<SampleTest>(
"testSample",
&SampleTest::testSample
));
return suiteOfTests;
}
void testSample() {
CPPUNIT_ASSERT( a == 10 );
}
};

int main() {
std::cout << "\n\n=== Style 1 ===\n\n";
{
CppUnit::TestCaller<SampleTest> test ( "testSample", &SampleTest::testSample );

CppUnit::BriefTestProgressListener progress;
CppUnit::TestResultCollector collectedresults;
CppUnit::TestResult result;
result.addListener(&progress);
test.run( &result );

CppUnit::CompilerOutputter outputter( &collectedresults, std::cerr );
}

std::cout << "\n\n=== Style 2 ===\n\n";
{
CppUnit::TestSuite suite;
suite.addTest( new CppUnit::TestCaller<SampleTest>(
"testSample",
&SampleTest::testSample
));

CppUnit::BriefTestProgressListener progress;
CppUnit::TestResultCollector collectedresults;
CppUnit::TestResult result;
result.addListener(&progress);
suite.run( &result );

CppUnit::CompilerOutputter outputter( &collectedresults, std::cerr );
}

std::cout << "\n\n=== Style 3 ===\n\n";
{
CppUnit::TextUi::TestRunner runner;
runner.addTest( SampleTest::suite() );
runner.run();
}
return 0;
}


測試成功:

=== Style 1 ===

testSample : OK


=== Style 2 ===

testSample : OK


=== Style 3 ===

.


OK (1 tests)


測試失敗:

=== Style 1 ===

testSample : assertion


=== Style 2 ===

testSample : assertion


=== Style 3 ===

.F


!!!FAILURES!!!
Test Results:
Run:  1   Failures: 1   Errors: 0


1) test: testSample (F) line: 27 t.cpp
assertion failed
- Expression: a == 10


目前大概打算對自定的 class 編寫一些偏邏輯層面的 unit test,例如 bool testFunc1(); 的方式,成功就回傳 true,但不套用任何 unit test framework,如此一來純邏輯的驗證更可以適用在不同平台,而要再加上特定的 unit test framework (如 CppUnit) 時,只需簡易套用,可以直接 reusable 而不必重頭寫。