Skip to content

Commit 97ee70c

Browse files
authored
HTTP mocking: support filename option (#332)
1 parent ddda951 commit 97ee70c

2 files changed

Lines changed: 29 additions & 0 deletions

File tree

features/http-mocking.feature

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,3 +119,20 @@ Feature: HTTP request mocking
119119
Then STDOUT should be a table containing rows:
120120
| version | update_type | package_url |
121121
| 999.9.9 | major | https://downloads.wordpress.org/release/wordpress-999.9.9.zip |
122+
123+
Scenario: Mock HTTP request with filename option writes to disk
124+
Given an empty directory
125+
And that HTTP requests to https://example.com/mocked-file.txt will respond with:
126+
"""
127+
HTTP/1.1 200 OK
128+
Content-Type: text/plain
129+
130+
Mocked file contents on disk!
131+
"""
132+
133+
When I try `wp eval 'WP_CLI\Utils\http_request("GET", "https://example.com/mocked-file.txt", null, [], ["filename" => "downloaded.txt"]);' --skip-wordpress`
134+
Then the return code should be 0
135+
And the downloaded.txt file should contain:
136+
"""
137+
Mocked file contents on disk!
138+
"""

src/Context/GivenStepDefinitions.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -228,6 +228,14 @@ public function request( \$url, \$headers = array(), \$data = array(), \$options
228228
if ( false !== \$pos ) {
229229
\$response = substr( \$response, 0, \$pos ) . "\\r\\n\\r\\n" . substr( \$response, \$pos + 2 );
230230
}
231+
if ( ! empty( \$options['filename'] ) ) {
232+
\$body = '';
233+
\$body_pos = strpos( \$response, "\\r\\n\\r\\n" );
234+
if ( false !== \$body_pos ) {
235+
\$body = substr( \$response, \$body_pos + 4 );
236+
}
237+
file_put_contents( \$options['filename'], \$body );
238+
}
231239
return \$response;
232240
}
233241
}
@@ -313,6 +321,10 @@ static function( \$pre, \$parsed_args, \$url ) {
313321
);
314322
}
315323
324+
if ( ! empty( \$parsed_args['filename'] ) ) {
325+
file_put_contents( \$parsed_args['filename'], \$response->body );
326+
}
327+
316328
return array(
317329
'headers' => \$response->headers->getAll(),
318330
'body' => \$response->body,

0 commit comments

Comments
 (0)