Browse Source

Merge branch 'master' into 0.7.0

Ben Hsieh 8 years ago
parent
commit
fa3ddd8e66
9 changed files with 126 additions and 203 deletions
  1. 4
    3
      README.md
  2. 1
    1
      package.json
  3. 4
    3
      src/README.md
  4. 3
    3
      src/ios/RNFetchBlobNetwork.h
  5. 90
    87
      src/ios/RNFetchBlobNetwork.m
  6. 1
    1
      src/package.json
  7. 22
    16
      test/test-0.1.x-0.4.x.js
  8. 0
    87
      test/test-0.5.3.js
  9. 1
    2
      test/test-init.js

+ 4
- 3
README.md View File

@@ -1,4 +1,4 @@
1
-# react-native-fetch-blob [![npm](https://img.shields.io/npm/v/react-native-fetch-blob.svg?style=flat-square)]() ![](https://img.shields.io/badge/PR-Welcome-brightgreen.svg?style=flat-square) [![npm](https://img.shields.io/npm/l/express.svg?maxAge=2592000&style=flat-square)]()
1
+# react-native-fetch-blob [![npm](https://img.shields.io/npm/v/react-native-fetch-blob.svg?style=flat-square)](https://www.npmjs.com/package/react-native-fetch-blob) ![](https://img.shields.io/badge/PR-Welcome-brightgreen.svg?style=flat-square) [![npm](https://img.shields.io/npm/l/express.svg?maxAge=2592000&style=flat-square)]() [![npm](https://img.shields.io/badge/inProgress-0.7.0-yellow.svg?style=flat-square)]()
2 2
 
3 3
 A module provides upload, download, and files access API. Supports file stream read/write for process large files.
4 4
 
@@ -6,13 +6,13 @@ A module provides upload, download, and files access API. Supports file stream r
6 6
 
7 7
 React Native does not support `Blob` object at this moment, which means if you're going to send/receive binary data via `fetch` API, that might not work as you expect. See [[fetch] Does fetch with blob() marshal data across the bridge?](https://github.com/facebook/react-native/issues/854).
8 8
 
9
-For some uses cases, you might get into trouble. For example, displaying an image that requires a specific field in headers (ex. "Authorization : Bearer ...") or body, so you can't just pass the image uri to `Image` component because that will probably returns a 401 response. Or you're going to upload binary data which generated from JS, the server will get an empry body due to [this issue](https://github.com/facebook/react-native/issues/854). With help of this APIs provides by this module, you can send HTTP request with any headers, and decide how to handle the response/reqeust data without worry about if it is not supported by `fetch` API. The response data can be just simply converted into BASE64 string, or store to a file directly so that you can read it by file access APIs such as readFile, readStream.
9
+For some use cases, you might get into trouble. For example, displaying an image that requires a specific field in headers (ex. "Authorization : Bearer ...") or body, so you can't just pass the image uri to `Image` component because that will probably returns a 401 response. Or you're going to upload binary data which generated from JS, the server will get an empry body due to [this issue](https://github.com/facebook/react-native/issues/854). With help of APIs provided by this module, you can send HTTP request with any headers, and decide how to handle the response/reqeust data without worry about if it is not supported by `fetch` API. The response data can be just simply converted into BASE64 string, or stored to a file directly so that you can read it by using file access APIs such as readFile, readStream.
10 10
 
11 11
 This module was designed to be a substitution of `Blob`, there's a set of APIs including basic file system CRUD method, and file stream reader/writer. Also it has a special `fetch` implementation that supports binary request/response body.
12 12
 
13 13
 **Pre v0.5.0 Users**
14 14
 
15
-This update is `backward-compatible` generally you don't have to change existing code unless you're going to use new APIs. In latest version (v0.5.0), new APIs can either `upload` or `download` files simply using a file path. It's much more memory efficent in some use case. We've also introduced `fs` APIs for access files, and `file stream` API that helps you read/write files (especially for **large ones**), see [Examples](#user-content-usage) bellow. This module implements native methods, supports both Android (uses awesome native library  [AsyncHttpClient](https://github.com/AsyncHttpClient/async-http-client])) and IOS.
15
+All updates are `backward-compatible` generally you don't have to change existing code unless you're going to use new APIs. In latest version (v0.5.0), new APIs can either `upload` or `download` files simply using a file path. It's much more memory efficent in some use case. We've also introduced `fs` APIs for access files, and `file stream` API that helps you read/write files (especially for **large ones**), see [Examples](#user-content-usage) bellow. This module implements native methods, supports both Android (uses awesome native library  [AsyncHttpClient](https://github.com/AsyncHttpClient/async-http-client])) and IOS.
16 16
 
17 17
 ## TOC
18 18
 
@@ -539,6 +539,7 @@ RNFetchBlob.config({
539 539
 
540 540
 | Version | |
541 541
 |---|---|
542
+| 0.6.1 | Fix #37 progress report API issue on IOS |
542 543
 | 0.6.0 | Add readFile and writeFile API for easier file access, also added Android download manager support. |
543 544
 | 0.5.8 | Fix #33 PUT request will always be sent as POST on Android |
544 545
 | 0.5.7 | Fix #31 #30 Xcode pre 7.3 build error |

+ 1
- 1
package.json View File

@@ -1,6 +1,6 @@
1 1
 {
2 2
   "name": "fetchblob",
3
-  "version": "0.6.0",
3
+  "version": "0.6.1",
4 4
   "private": true,
5 5
   "scripts": {
6 6
     "start": "node node_modules/react-native/local-cli/cli.js start",

+ 4
- 3
src/README.md View File

@@ -1,4 +1,4 @@
1
-# react-native-fetch-blob [![npm](https://img.shields.io/npm/v/react-native-fetch-blob.svg?style=flat-square)]() ![](https://img.shields.io/badge/PR-Welcome-brightgreen.svg?style=flat-square) [![npm](https://img.shields.io/npm/l/express.svg?maxAge=2592000&style=flat-square)]()
1
+# react-native-fetch-blob [![npm](https://img.shields.io/npm/v/react-native-fetch-blob.svg?style=flat-square)](https://www.npmjs.com/package/react-native-fetch-blob) ![](https://img.shields.io/badge/PR-Welcome-brightgreen.svg?style=flat-square) [![npm](https://img.shields.io/npm/l/express.svg?maxAge=2592000&style=flat-square)]()
2 2
 
3 3
 A module provides upload, download, and files access API. Supports file stream read/write for process large files.
4 4
 
@@ -6,13 +6,13 @@ A module provides upload, download, and files access API. Supports file stream r
6 6
 
7 7
 React Native does not support `Blob` object at this moment, which means if you're going to send/receive binary data via `fetch` API, that might not work as you expect. See [[fetch] Does fetch with blob() marshal data across the bridge?](https://github.com/facebook/react-native/issues/854).
8 8
 
9
-For some uses cases, you might get into trouble. For example, displaying an image that requires a specific field in headers (ex. "Authorization : Bearer ...") or body, so you can't just pass the image uri to `Image` component because that will probably returns a 401 response. Or you're going to upload binary data which generated from JS, the server will get an empry body due to [this issue](https://github.com/facebook/react-native/issues/854). With help of this APIs provides by this module, you can send HTTP request with any headers, and decide how to handle the response/reqeust data without worry about if it is not supported by `fetch` API. The response data can be just simply converted into BASE64 string, or store to a file directly so that you can read it by file access APIs such as readFile, readStream.
9
+For some use cases, you might get into trouble. For example, displaying an image that requires a specific field in headers (ex. "Authorization : Bearer ...") or body, so you can't just pass the image uri to `Image` component because that will probably returns a 401 response. Or you're going to upload binary data which generated from JS, the server will get an empry body due to [this issue](https://github.com/facebook/react-native/issues/854). With help of APIs provided by this module, you can send HTTP request with any headers, and decide how to handle the response/reqeust data without worry about if it is not supported by `fetch` API. The response data can be just simply converted into BASE64 string, or stored to a file directly so that you can read it by using file access APIs such as readFile, readStream.
10 10
 
11 11
 This module was designed to be a substitution of `Blob`, there's a set of APIs including basic file system CRUD method, and file stream reader/writer. Also it has a special `fetch` implementation that supports binary request/response body.
12 12
 
13 13
 **Pre v0.5.0 Users**
14 14
 
15
-This update is `backward-compatible` generally you don't have to change existing code unless you're going to use new APIs. In latest version (v0.5.0), new APIs can either `upload` or `download` files simply using a file path. It's much more memory efficent in some use case. We've also introduced `fs` APIs for access files, and `file stream` API that helps you read/write files (especially for **large ones**), see [Examples](#user-content-usage) bellow. This module implements native methods, supports both Android (uses awesome native library  [AsyncHttpClient](https://github.com/AsyncHttpClient/async-http-client])) and IOS.
15
+All updates are `backward-compatible` generally you don't have to change existing code unless you're going to use new APIs. In latest version (v0.5.0), new APIs can either `upload` or `download` files simply using a file path. It's much more memory efficent in some use case. We've also introduced `fs` APIs for access files, and `file stream` API that helps you read/write files (especially for **large ones**), see [Examples](#user-content-usage) bellow. This module implements native methods, supports both Android (uses awesome native library  [AsyncHttpClient](https://github.com/AsyncHttpClient/async-http-client])) and IOS.
16 16
 
17 17
 ## TOC
18 18
 
@@ -539,6 +539,7 @@ RNFetchBlob.config({
539 539
 
540 540
 | Version | |
541 541
 |---|---|
542
+| 0.6.1 | Fix #37 progress report API issue on IOS |
542 543
 | 0.6.0 | Add readFile and writeFile API for easier file access, also added Android download manager support. |
543 544
 | 0.5.8 | Fix #33 PUT request will always be sent as POST on Android |
544 545
 | 0.5.7 | Fix #31 #30 Xcode pre 7.3 build error |

+ 3
- 3
src/ios/RNFetchBlobNetwork.h View File

@@ -15,7 +15,7 @@
15 15
 typedef void(^CompletionHander)(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error);
16 16
 typedef void(^DataTaskCompletionHander) (NSData * _Nullable resp, NSURLResponse * _Nullable response, NSError * _Nullable error);
17 17
 
18
-@interface RNFetchBlobNetwork : NSObject  <NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, UIApplicationDelegate>
18
+@interface RNFetchBlobNetwork : NSObject  <NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate>
19 19
 
20 20
 @property (nullable, nonatomic) NSString * taskId;
21 21
 @property (nonatomic) int expectedBytes;
@@ -25,8 +25,8 @@ typedef void(^DataTaskCompletionHander) (NSData * _Nullable resp, NSURLResponse
25 25
 @property (nullable, nonatomic) RCTBridge * bridge;
26 26
 @property (nullable, nonatomic) NSDictionary * options;
27 27
 @property (nullable, nonatomic) RNFetchBlobFS * fileStream;
28
-//@property (strong, nonatomic) CompletionHander fileTaskCompletionHandler;
29
-//@property (strong, nonatomic) DataTaskCompletionHander dataTaskCompletionHandler;
28
+@property (strong, nonatomic) CompletionHander fileTaskCompletionHandler;
29
+@property (strong, nonatomic) DataTaskCompletionHander dataTaskCompletionHandler;
30 30
 @property (nullable, nonatomic) NSError * error;
31 31
 
32 32
 

+ 90
- 87
src/ios/RNFetchBlobNetwork.m View File

@@ -21,6 +21,16 @@
21 21
 //
22 22
 ////////////////////////////////////////
23 23
 
24
+@interface RNFetchBlobNetwork ()
25
+{
26
+    BOOL * respFile;
27
+    NSString * destPath;
28
+    NSOutputStream * writeStream;
29
+    long bodyLength;
30
+}
31
+
32
+@end
33
+
24 34
 @implementation RNFetchBlobNetwork
25 35
 
26 36
 NSOperationQueue *taskQueue;
@@ -32,8 +42,8 @@ NSOperationQueue *taskQueue;
32 42
 @synthesize callback;
33 43
 @synthesize bridge;
34 44
 @synthesize options;
35
-//@synthesize fileTaskCompletionHandler;
36
-//@synthesize dataTaskCompletionHandler;
45
+@synthesize fileTaskCompletionHandler;
46
+@synthesize dataTaskCompletionHandler;
37 47
 @synthesize error;
38 48
 
39 49
 
@@ -73,83 +83,28 @@ NSOperationQueue *taskQueue;
73 83
     NSString * ext = [self.options valueForKey:CONFIG_FILE_EXT];
74 84
     NSURLSession * session;
75 85
     
86
+    bodyLength = [[req HTTPBody] length];
87
+    
76 88
     // the session trust any SSL certification
77
-    if([options valueForKey:CONFIG_TRUSTY] != nil)
89
+
90
+    NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:taskId];
91
+    session = [NSURLSession sessionWithConfiguration:defaultConfigObject delegate:self delegateQueue:[NSOperationQueue mainQueue]];
92
+    
93
+    if(path != nil || [self.options valueForKey:CONFIG_USE_TEMP]!= nil)
78 94
     {
79
-        NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
80
-        session = [NSURLSession sessionWithConfiguration:defaultConfigObject delegate:self delegateQueue:[NSOperationQueue mainQueue]];
95
+        respFile = YES;
96
+        if(path != nil)
97
+            destPath = path;
98
+        else
99
+            destPath = [RNFetchBlobFS getTempPath:taskId withExtension:[self.options valueForKey:CONFIG_FILE_EXT]];
81 100
     }
82
-    // the session validates SSL certification, self-signed certification will be aborted
83 101
     else
84 102
     {
85
-        session = [NSURLSession sharedSession];
86
-    }
87
-    
88
-    // file will be stored at a specific path
89
-    if( path != nil) {
90
-        
91
-//        self.fileTaskCompletionHandler = ;
92
-        NSURLSessionDownloadTask * task = [session downloadTaskWithRequest:req completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
93
-            if(error != nil) {
94
-                callback(@[[error localizedDescription]]);
95
-                return;
96
-            }
97
-            NSError * taskErr;
98
-            NSFileManager * fm = [NSFileManager defaultManager];
99
-            // move temp file to desination
100
-            [fm moveItemAtURL:location toURL:[NSURL fileURLWithPath:path] error:&taskErr];
101
-            if(taskErr != nil) {
102
-                callback(@[[taskErr localizedDescription]]);
103
-                return;
104
-            }
105
-            callback(@[[NSNull null], path]);
106
-            // prevent memory leaks
107
-            self.respData = nil;
108
-            [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
109
-        }];
110
-        [task resume];
111
-    }
112
-    // file will be stored at tmp path
113
-    else if ( [self.options valueForKey:CONFIG_USE_TEMP]!= nil ) {
114
-        
115
-//        self.fileTaskCompletionHandler;
116
-        NSURLSessionDownloadTask * task = [session downloadTaskWithRequest:req completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
117
-            if(error != nil) {
118
-                callback(@[[error localizedDescription]]);
119
-                return;
120
-            }
121
-            NSError * taskErr;
122
-            NSFileManager * fm = [NSFileManager defaultManager];
123
-            NSString * tmpPath = [RNFetchBlobFS getTempPath:self.taskId withExtension:[self.options valueForKey:CONFIG_FILE_EXT]];
124
-            // move temp file to desination
125
-            [fm moveItemAtURL:location toURL:[NSURL fileURLWithPath:tmpPath] error:&taskErr];
126
-            if(taskErr != nil) {
127
-                callback(@[[taskErr localizedDescription]]);
128
-                return;
129
-            }
130
-            callback(@[[NSNull null], tmpPath]);
131
-            [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
132
-            // prevent memory leaks
133
-            self.respData = nil;
134
-        }];
135
-        [task resume];
136
-    }
137
-    // base64 response
138
-    else {
139
-//        self.dataTaskCompletionHandler = ;
140
-        NSURLSessionDataTask * task = [session dataTaskWithRequest:req completionHandler:^(NSData * _Nullable resp, NSURLResponse * _Nullable response, NSError * _Nullable error) {
141
-            if(error != nil) {
142
-                callback(@[[error localizedDescription]]);
143
-                return;
144
-            }
145
-            else {
146
-                callback(@[[NSNull null], [resp base64EncodedStringWithOptions:0]]);
147
-            }
148
-            self.respData = nil;
149
-            [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
150
-        }];
151
-        [task resume];
103
+        respData = [[NSMutableData alloc] init];
104
+        respFile = NO;
152 105
     }
106
+    NSURLSessionDataTask * task = [session dataTaskWithRequest:req];
107
+    [task resume];
153 108
     
154 109
     // network status indicator
155 110
     if([[options objectForKey:CONFIG_INDICATOR] boolValue] == YES)
@@ -169,19 +124,34 @@ NSOperationQueue *taskQueue;
169 124
 - (void) URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
170 125
 {
171 126
     expectedBytes = [response expectedContentLength];
127
+    
128
+    if(respFile == YES)
129
+    {
130
+        NSFileManager * fm = [NSFileManager defaultManager];
131
+        NSString * folder = [destPath stringByDeletingLastPathComponent];
132
+        if(![fm fileExistsAtPath:folder]) {
133
+            [fm createDirectoryAtPath:folder withIntermediateDirectories:YES attributes:NULL error:nil];
134
+        }
135
+        [fm createFileAtPath:destPath contents:[[NSData alloc] init] attributes:nil];
136
+        writeStream = [[NSOutputStream alloc] initToFileAtPath:destPath append:YES];
137
+        [writeStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
138
+        [writeStream open];
139
+    }
140
+    completionHandler(NSURLSessionResponseAllow);
172 141
 }
173 142
 
174 143
 // download progress handler
175 144
 - (void) URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
176 145
 {
177 146
     receivedBytes += [data length];
178
-    
179
-    Boolean fileCache = [self.options valueForKey:CONFIG_USE_TEMP];
180
-    NSString * path = [self.options valueForKey:CONFIG_FILE_PATH];
181
-    // cache data in memory
182
-    if(path == nil && fileCache == nil) {
147
+    if(respFile == NO)
148
+    {
183 149
         [respData appendData:data];
184 150
     }
151
+    else
152
+    {
153
+        [writeStream write:[data bytes] maxLength:[data length]];
154
+    }
185 155
     
186 156
     [self.bridge.eventDispatcher
187 157
      sendDeviceEventWithName:@"RNFetchBlobProgress"
@@ -191,6 +161,20 @@ NSOperationQueue *taskQueue;
191 161
             @"total": [NSString stringWithFormat:@"%d", expectedBytes]
192 162
             }
193 163
      ];
164
+    
165
+    if(receivedBytes >= expectedBytes)
166
+    {
167
+        if(respFile == YES)
168
+        {
169
+            [writeStream close];
170
+            callback(@[[NSNull null], destPath]);
171
+        }
172
+        // base64 response
173
+        else {
174
+            callback(@[[NSNull null], [respData base64EncodedStringWithOptions:0]]);
175
+        }
176
+        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
177
+    }
194 178
 }
195 179
 
196 180
 - (void) URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
@@ -202,14 +186,12 @@ NSOperationQueue *taskQueue;
202 186
 // upload progress handler
203 187
 - (void) URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesWritten totalBytesExpectedToSend:(int64_t)totalBytesExpectedToWrite
204 188
 {
205
-    expectedBytes = totalBytesExpectedToWrite;
206
-    receivedBytes += totalBytesWritten;
207 189
     [self.bridge.eventDispatcher
208 190
      sendDeviceEventWithName:@"RNFetchBlobProgress"
209 191
      body:@{
210 192
             @"taskId": taskId,
211
-            @"written": [NSString stringWithFormat:@"%d", receivedBytes],
212
-            @"total": [NSString stringWithFormat:@"%d", expectedBytes]
193
+            @"written": [NSString stringWithFormat:@"%d", totalBytesWritten],
194
+            @"total": [NSString stringWithFormat:@"%d", totalBytesExpectedToWrite]
213 195
             }
214 196
      ];
215 197
 }
@@ -230,13 +212,34 @@ NSOperationQueue *taskQueue;
230 212
 //    }
231 213
 //}
232 214
 
233
-- (void) URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler
215
+- (void) URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable credantial))completionHandler
234 216
 {
235 217
     if([options valueForKey:CONFIG_TRUSTY] != nil)
236
-        completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
237
-    else {
238
-        RCTLogWarn(@"counld not create connection with an unstrusted SSL certification, if you're going to create connection anyway, add `trusty:true` to RNFetchBlob.config");
239
-        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
218
+    {
219
+        completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
220
+    }
221
+    else
222
+    {
223
+        NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling;
224
+        __block NSURLCredential *credential = nil;
225
+        if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust])
226
+        {
227
+            credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
228
+            if (credential) {
229
+                disposition = NSURLSessionAuthChallengeUseCredential;
230
+            } else {
231
+                disposition = NSURLSessionAuthChallengePerformDefaultHandling;
232
+            }
233
+        }
234
+        else
235
+        {
236
+            disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge;
237
+            RCTLogWarn(@"counld not create connection with an unstrusted SSL certification, if you're going to create connection anyway, add `trusty:true` to RNFetchBlob.config");
238
+            [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
239
+        }
240
+        if (completionHandler) {
241
+            completionHandler(disposition, credential);
242
+        }
240 243
     }
241 244
 }
242 245
 

+ 1
- 1
src/package.json View File

@@ -1,6 +1,6 @@
1 1
 {
2 2
   "name": "react-native-fetch-blob",
3
-  "version": "0.6.0",
3
+  "version": "0.6.1",
4 4
   "description": "A module provides upload, download, and files access API. Supports file stream read/write for process large files.",
5 5
   "main": "index.js",
6 6
   "scripts": {

+ 22
- 16
test/test-0.1.x-0.4.x.js View File

@@ -97,19 +97,20 @@ describe('Compare uploaded multipart image', (report, done) => {
97 97
 // added after 0.4.2
98 98
 
99 99
 describe('Progress report test', (report, done) => {
100
-  let received = 0
100
+  let actual = 0, expect = -1
101 101
   RNFetchBlob
102 102
     .fetch('GET', `${TEST_SERVER_URL}/public/1mb-dummy`, {
103 103
       Authorization : 'Bearer abde123eqweje'
104 104
     })
105
-    .progress((written, total) => {
106
-      // report(<Info key={`progress = ${written} bytes / ${total} bytes`}/>)
107
-      if(written === total)
108
-        report(<Assert key="progress goes to 100%" expect={written} actual={total}/>)
105
+    .progress((received, total) => {
106
+      actual = received
107
+      expect = total
109 108
     })
110 109
     .then((resp) => {
111
-      report(<Assert key="response data should be correct event with progress listener"
112
-        expect={resp.text().substr(0,10)} actual={"1234567890"}/>)
110
+      report(
111
+        <Assert key="download progress correct" expect={expect} actual={actual}/>,
112
+        <Assert key="response data should be correct event with progress listener"
113
+          expect={resp.text().substr(0,10)} actual={"1234567890"}/>)
113 114
       done()
114 115
     })
115 116
 
@@ -117,7 +118,7 @@ describe('Progress report test', (report, done) => {
117 118
 
118 119
 
119 120
 describe('PUT request test', (report, done) => {
120
-
121
+  let actual = 0, expect = -1
121 122
   RNFetchBlob.fetch('PUT', `${TEST_SERVER_URL}/upload-form`, {
122 123
       Authorization : "Bearer fsXcpmKPrHgAAAAAAAAAEGxFXwhejXM_E8fznZoXPhHbhbNhA-Lytbe6etp1Jznz",
123 124
       'Content-Type' : 'multipart/form-data',
@@ -127,14 +128,19 @@ describe('PUT request test', (report, done) => {
127 128
       { name : 'field1', data : 'hello !!'},
128 129
       { name : 'field2', data : 'hello2 !!'}
129 130
     ])
130
-  .then((resp) => {
131
-    resp = resp.json()
132
-    report(
133
-      <Assert key="check put form data #1" expect="hello !!" actual={resp.fields.field1}/>,
134
-      <Assert key="check put form data #2" expect="hello2 !!" actual={resp.fields.field2}/>,
135
-    )
136
-    done()
137
-  })
131
+    .progress((written, total) => {
132
+      actual = written
133
+      expect = total
134
+    })
135
+    .then((resp) => {
136
+      resp = resp.json()
137
+      report(
138
+        <Assert key="upload progress correct" expect={expect} actual={actual}/>,
139
+        <Assert key="check put form data #1" expect="hello !!" actual={resp.fields.field1}/>,
140
+        <Assert key="check put form data #2" expect="hello2 !!" actual={resp.fields.field2}/>,
141
+      )
142
+      done()
143
+    })
138 144
 })
139 145
 
140 146
 describe('DELETE request test', (report, done) => {

+ 0
- 87
test/test-0.5.3.js View File

@@ -1,87 +0,0 @@
1
-import RNTest from './react-native-testkit/'
2
-import React from 'react'
3
-import RNFetchBlob from 'react-native-fetch-blob'
4
-
5
-import {
6
-  StyleSheet,
7
-  Text,
8
-  View,
9
-  ScrollView,
10
-  Platform,
11
-  Dimensions,
12
-  Image,
13
-} from 'react-native';
14
-
15
-const fs = RNFetchBlob.fs
16
-const { Assert, Comparer, Info, prop } = RNTest
17
-const describe = RNTest.config({
18
-  group : '0.5.3',
19
-  run : true,
20
-  expand : false,
21
-})
22
-const { TEST_SERVER_URL_SSL, FILENAME, DROPBOX_TOKEN, styles } = prop()
23
-
24
-let prefix = ((Platform.OS === 'android') ? 'file://' : '')
25
-
26
-
27
-describe('GET request with params', (report, done) => {
28
-  let time = Date.now()
29
-  RNFetchBlob
30
-  .config({ fileCache : true, trusty : true })
31
-    .fetch('GET', `${TEST_SERVER_URL_SSL}/params?time=${time}&name=RNFetchBlobParams&lang=中文`)
32
-    .then((resp) => {
33
-      let file = resp.path()
34
-      return RNFetchBlob.fs.readStream(resp.path(), 'utf8')
35
-    })
36
-    .then((stream) => {
37
-      let result = ''
38
-      stream.open()
39
-      stream.onData((chunk) => {
40
-        result += chunk
41
-      })
42
-      stream.onEnd(() => {
43
-        result = JSON.parse(result)
44
-        report(<Assert key="param#1 should correct"
45
-          expect={parseInt(time)}
46
-          actual={parseInt(result.time)}/>,
47
-        <Assert key="param#2 should correct"
48
-          expect={'RNFetchBlobParams'}
49
-          actual={result.name}/>,
50
-        <Assert key="param contains unicode data should correct"
51
-          expect={'中文'}
52
-          actual={result.lang}/>)
53
-          done()
54
-      })
55
-    })
56
-})
57
-
58
-
59
-describe('POST request with params', (report, done) => {
60
-  let time = Date.now()
61
-  RNFetchBlob.config({ fileCache : true, trusty : true })
62
-    .fetch('POST', `${TEST_SERVER_URL_SSL}/params?time=${time}&name=RNFetchBlobParams&lang=中文`)
63
-    .then((resp) => {
64
-      let file = resp.path()
65
-      return RNFetchBlob.fs.readStream(resp.path(), 'utf8')
66
-    })
67
-    .then((stream) => {
68
-      let result = ''
69
-      stream.open()
70
-      stream.onData((chunk) => {
71
-        result += chunk
72
-      })
73
-      stream.onEnd(() => {
74
-        result = JSON.parse(result)
75
-        report(<Assert key="param#1 should correct"
76
-          expect={parseInt(time)}
77
-          actual={parseInt(result.time)}/>,
78
-        <Assert key="param#2 should correct"
79
-          expect={'RNFetchBlobParams'}
80
-          actual={result.name}/>,
81
-        <Assert key="param contains unicode data should correct"
82
-          expect={'中文'}
83
-          actual={result.lang}/>)
84
-          done()
85
-      })
86
-    })
87
-})

+ 1
- 2
test/test-init.js View File

@@ -17,7 +17,7 @@ const { Assert, Comparer, Info, describe, prop } = RNTest
17 17
 
18 18
 // test environment variables
19 19
 
20
-prop('FILENAME', `${Platform.OS}-0.6.0-${Date.now()}.png`)
20
+prop('FILENAME', `${Platform.OS}-0.7.0-${Date.now()}.png`)
21 21
 prop('TEST_SERVER_URL', 'http://192.168.16.70:8123')
22 22
 prop('TEST_SERVER_URL_SSL', 'https://192.168.16.70:8124')
23 23
 prop('DROPBOX_TOKEN', 'fsXcpmKPrHgAAAAAAAAAoXZhcXYWdgLpQMan6Tb_bzJ237DXhgQSev12hA-gUXt4')
@@ -54,7 +54,6 @@ describe('GET image from server', (report, done) => {
54 54
 require('./test-0.1.x-0.4.x')
55 55
 require('./test-0.5.1')
56 56
 require('./test-0.5.2')
57
-require('./test-0.5.3')
58 57
 require('./test-0.6.0')
59 58
 require('./test-fs')
60 59
 require('./test-android')