> Human-friendly and powerful HTTP request library for Node.js
[](https://npmjs.com/got)
[](https://packagephobia.com/result?p=got)
[See how Got compares to other HTTP libraries](#comparison)
---
**You probably want [Ky](https://github.com/sindresorhus/ky) instead, by the same people. It's smaller, works in the browser too, and is more stable since it's built on [`Fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API). Or [fetch-extras](https://github.com/sindresorhus/fetch-extras) for simple needs.**
---
**Support questions should be asked [here](https://github.com/sindresorhus/got/discussions).**
## Install
```sh
npm install got
```
**Warning:** This package is native [ESM](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules) and no longer provides a CommonJS export. If your project uses CommonJS, you will have to [convert to ESM](https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c). Please don't open issues for questions regarding CommonJS / ESM.
**Got v11 is no longer maintained and we will not accept any backport requests.**
## Take a peek
**A [quick start](documentation/quick-start.md) guide is available.**
### JSON mode
Got has a dedicated option for handling JSON payload.\
Furthermore, the promise exposes a `.json()` function that returns `Promise`.
```js
import got from 'got';
const {data} = await got.post('https://httpbin.org/anything', {
json: {
hello: 'world'
}
}).json();
console.log(data);
//=> {"hello": "world"}
```
For advanced JSON usage, check out the [`parseJson`](documentation/2-options.md#parsejson) and [`stringifyJson`](documentation/2-options.md#stringifyjson) options.
**For more useful tips like this, visit the [Tips](documentation/tips.md) page.**
## Highlights
- [Used by 10K+ packages and 5M+ repos](https://github.com/sindresorhus/got/network/dependents)
- [Actively maintained](https://github.com/sindresorhus/got/graphs/contributors)
- [Trusted by many companies](#widely-used)
## Documentation
By default, Got will retry on failure. To disable this option, set [`options.retry.limit`](documentation/7-retry.md#retry) to 0.
#### Main API
- [x] [Promise API](documentation/1-promise.md)
- [x] [Options](documentation/2-options.md)
- [x] [Stream API](documentation/3-streams.md)
- [x] [Pagination API](documentation/4-pagination.md)
- [x] [Advanced HTTPS API](documentation/5-https.md)
- [x] [HTTP/2 support](documentation/2-options.md#http2)
- [x] [`Response` class](documentation/3-streams.md#response-2)
#### Timeouts and retries
- [x] [Advanced timeout handling](documentation/6-timeout.md)
- [x] [Retries on failure](documentation/7-retry.md)
- [x] [Errors with metadata](documentation/8-errors.md)
#### Advanced creation
- [x] [Hooks](documentation/9-hooks.md)
- [x] [Instances](documentation/10-instances.md)
- [x] [Progress events & other events](documentation/3-streams.md#events)
- [x] [Plugins](documentation/lets-make-a-plugin.md)
- [x] [Compose](documentation/examples/advanced-creation.js)
#### Cache, Proxy and UNIX sockets
- [x] [RFC 7234 compliant caching](documentation/cache.md)
- [x] [Proxy support](documentation/tips.md#proxying)
- [x] [Unix Domain Sockets](documentation/2-options.md#enableunixsockets)
#### Integration
- [x] [Diagnostics Channel](documentation/diagnostics-channel.md)
- [x] [TypeScript support](documentation/typescript.md)
- [x] [AWS](documentation/tips.md#aws)
- [x] [Testing](documentation/tips.md#testing)
---
### Migration guides
- [Request migration guide](documentation/migration-guides/request.md)
- [*(Note that Request is unmaintained)*](https://github.com/request/request/issues/3142)
- [Axios](documentation/migration-guides/axios.md)
- [Node.js](documentation/migration-guides/nodejs.md)
## Got plugins
- [`got4aws`](https://github.com/SamVerschueren/got4aws) - Got convenience wrapper to interact with AWS v4 signed APIs
- [`gh-got`](https://github.com/sindresorhus/gh-got) - Got convenience wrapper to interact with the GitHub API
- [`gl-got`](https://github.com/singapore/gl-got) - Got convenience wrapper to interact with the GitLab API
- [`gotql`](https://github.com/khaosdoctor/gotql) - Got convenience wrapper to interact with GraphQL using JSON-parsed queries instead of strings
- [`got-fetch`](https://github.com/alexghr/got-fetch) - Got with a [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) interface
- [`got-scraping`](https://github.com/apify/got-scraping) - Got wrapper specifically designed for web scraping purposes
- [`got-ssrf`](https://github.com/JaneJeon/got-ssrf) - Got wrapper to protect server-side requests against SSRF attacks
## Comparison
| | `got` | [`node-fetch`][n0] | [`ky`][k0] | [`axios`][a0] | [`superagent`][s0] |
|-----------------------|:-------------------:|:--------------------:|:------------------------:|:------------------:|:----------------------:|
| HTTP/2 support | :heavy_check_mark: | :x: | :heavy_check_mark: | :x: | :heavy_check_mark:\*\* |
| Browser support | :x: | :heavy_check_mark:\* | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: |
| Promise API | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: |
| Stream API | :heavy_check_mark: | Node.js only | :x: | :x: | :heavy_check_mark: |
| Pagination API | :heavy_check_mark: | :x: | :x: | :x: | :x: |
| Request aborting | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: |
| RFC 7234 caching | :heavy_check_mark: | :x: | :x: | :x: | :x: |
| Cookies (out-of-the-box) | :heavy_check_mark: | :x: | :x: | :x: | :x: |
| Follows redirects | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: |
| Retries on failure | :heavy_check_mark: | :x: | :heavy_check_mark: | :x: | :heavy_check_mark: |
| Progress events | :heavy_check_mark: | :x: | :heavy_check_mark: | Browser only | :heavy_check_mark: |
| Handles gzip/deflate | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: |
| Advanced timeouts | :heavy_check_mark: | :x: | :x: | :x: | :x: |
| Timings | :heavy_check_mark: | :x: | :x: | :x: | :x: |
| Errors with metadata | :heavy_check_mark: | :x: | :heavy_check_mark: | :heavy_check_mark: | :x: |
| JSON mode | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: |
| Custom defaults | :heavy_check_mark: | :x: | :heavy_check_mark: | :heavy_check_mark: | :x: |
| Composable | :heavy_check_mark: | :x: | :x: | :x: | :heavy_check_mark: |
| Hooks | :heavy_check_mark: | :x: | :heavy_check_mark: | :heavy_check_mark: | :x: |
| Issues open | [![][gio]][g1] | [![][nio]][n1] | [![][kio]][k1] | [![][aio]][a1] | [![][sio]][s1] |
| Issues closed | [![][gic]][g2] | [![][nic]][n2] | [![][kic]][k2] | [![][aic]][a2] | [![][sic]][s2] |
| Downloads | [![][gd]][g3] | [![][nd]][n3] | [![][kd]][k3] | [![][ad]][a3] | [![][sd]][s3] |
| Coverage | TBD | [![][nc]][n4] | [![][kc]][k4] | [![][ac]][a4] | [![][sc]][s4] |
| Build | [![][gb]][g5] | [![][nb]][n5] | [![][kb]][k5] | [![][ab]][a5] | [![][sb]][s5] |
| Bugs | [![][gbg]][g6] | [![][nbg]][n6] | [![][kbg]][k6] | [![][abg]][a6] | [![][sbg]][s6] |
| Dependents | [![][gdp]][g7] | [![][ndp]][n7] | [![][kdp]][k7] | [![][adp]][a7] | [![][sdp]][s7] |
| Install size | [![][gis]][g8] | [![][nis]][n8] | [![][kis]][k8] | [![][ais]][a8] | [![][sis]][s8] |
| GitHub stars | [![][gs]][g9] | [![][ns]][n9] | [![][ks]][k9] | [![][as]][a9] | [![][ss]][s9] |
| TypeScript support | [![][gts]][g10] | [![][nts]][n10] | [![][kts]][k10] | [![][ats]][a10] | [![][sts]][s11] |
| Last commit | [![][glc]][g11] | [![][nlc]][n11] | [![][klc]][k11] | [![][alc]][a11] | [![][slc]][s11] |
\* It's almost API compatible with the browser `fetch` API.\
\*\* Need to switch the protocol manually. Doesn't accept PUSH streams and doesn't reuse HTTP/2 sessions.\
:sparkle: Almost-stable feature, but the API may change. Don't hesitate to try it out!\
:grey_question: Feature in early stage of development. Very experimental.
[k0]: https://github.com/sindresorhus/ky
[n0]: https://github.com/node-fetch/node-fetch
[a0]: https://github.com/axios/axios
[s0]: https://github.com/visionmedia/superagent
[gio]: https://img.shields.io/github/issues-raw/sindresorhus/got?color=gray&label
[kio]: https://img.shields.io/github/issues-raw/sindresorhus/ky?color=gray&label
[nio]: https://img.shields.io/github/issues-raw/bitinn/node-fetch?color=gray&label
[aio]: https://img.shields.io/github/issues-raw/axios/axios?color=gray&label
[sio]: https://img.shields.io/github/issues-raw/visionmedia/superagent?color=gray&label
[g1]: https://github.com/sindresorhus/got/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc
[k1]: https://github.com/sindresorhus/ky/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc
[n1]: https://github.com/bitinn/node-fetch/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc
[a1]: https://github.com/axios/axios/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc
[s1]: https://github.com/visionmedia/superagent/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc
[gic]: https://img.shields.io/github/issues-closed-raw/sindresorhus/got?color=blue&label
[kic]: https://img.shields.io/github/issues-closed-raw/sindresorhus/ky?color=blue&label
[nic]: https://img.shields.io/github/issues-closed-raw/bitinn/node-fetch?color=blue&label
[aic]: https://img.shields.io/github/issues-closed-raw/axios/axios?color=blue&label
[sic]: https://img.shields.io/github/issues-closed-raw/visionmedia/superagent?color=blue&label
[g2]: https://github.com/sindresorhus/got/issues?q=is%3Aissue+is%3Aclosed+sort%3Aupdated-desc
[k2]: https://github.com/sindresorhus/ky/issues?q=is%3Aissue+is%3Aclosed+sort%3Aupdated-desc
[n2]: https://github.com/bitinn/node-fetch/issues?q=is%3Aissue+is%3Aclosed+sort%3Aupdated-desc
[a2]: https://github.com/axios/axios/issues?q=is%3Aissue+is%3Aclosed+sort%3Aupdated-desc
[s2]: https://github.com/visionmedia/superagent/issues?q=is%3Aissue+is%3Aclosed+sort%3Aupdated-desc
[gd]: https://img.shields.io/npm/dm/got?color=darkgreen&label
[kd]: https://img.shields.io/npm/dm/ky?color=darkgreen&label
[nd]: https://img.shields.io/npm/dm/node-fetch?color=darkgreen&label
[ad]: https://img.shields.io/npm/dm/axios?color=darkgreen&label
[sd]: https://img.shields.io/npm/dm/superagent?color=darkgreen&label
[g3]: https://www.npmjs.com/package/got
[k3]: https://www.npmjs.com/package/ky
[n3]: https://www.npmjs.com/package/node-fetch
[a3]: https://www.npmjs.com/package/axios
[s3]: https://www.npmjs.com/package/superagent
[kc]: https://img.shields.io/codecov/c/github/sindresorhus/ky?color=0b9062&label
[nc]: https://img.shields.io/coveralls/github/bitinn/node-fetch?color=0b9062&label
[ac]: https://img.shields.io/coveralls/github/mzabriskie/axios?color=0b9062&label
[sc]: https://img.shields.io/codecov/c/github/visionmedia/superagent?color=0b9062&label
[k4]: https://codecov.io/gh/sindresorhus/ky
[n4]: https://coveralls.io/github/bitinn/node-fetch
[a4]: https://coveralls.io/github/mzabriskie/axios
[s4]: https://codecov.io/gh/visionmedia/superagent
[gb]: https://github.com/sindresorhus/got/actions/workflows/main.yml/badge.svg
[kb]: https://github.com/sindresorhus/ky/actions/workflows/main.yml/badge.svg
[nb]: https://img.shields.io/travis/bitinn/node-fetch?label
[ab]: https://img.shields.io/travis/axios/axios?label
[sb]: https://img.shields.io/travis/visionmedia/superagent?label
[g5]: https://github.com/sindresorhus/got/actions/workflows/main.yml
[k5]: https://github.com/sindresorhus/ky/actions/workflows/main.yml
[n5]: https://travis-ci.org/github/bitinn/node-fetch
[a5]: https://travis-ci.org/github/axios/axios
[s5]: https://travis-ci.org/github/visionmedia/superagent
[gbg]: https://img.shields.io/github/issues-raw/sindresorhus/got/bug?color=darkred&label
[kbg]: https://img.shields.io/github/issues-raw/sindresorhus/ky/bug?color=darkred&label
[nbg]: https://img.shields.io/github/issues-raw/bitinn/node-fetch/bug?color=darkred&label
[abg]: https://img.shields.io/github/issues-raw/axios/axios/bug-fix?color=darkred&label
[sbg]: https://img.shields.io/github/issues-raw/visionmedia/superagent/Bug?color=darkred&label
[g6]: https://github.com/sindresorhus/got/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3Abug
[k6]: https://github.com/sindresorhus/ky/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3Abug
[n6]: https://github.com/bitinn/node-fetch/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3Abug
[a6]: https://github.com/axios/axios/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3A%22bug-fix%22
[s6]: https://github.com/visionmedia/superagent/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3ABug
[gdp]: https://badgen.net/npm/dependents/got?color=orange&label
[kdp]: https://badgen.net/npm/dependents/ky?color=orange&label
[ndp]: https://badgen.net/npm/dependents/node-fetch?color=orange&label
[adp]: https://badgen.net/npm/dependents/axios?color=orange&label
[sdp]: https://badgen.net/npm/dependents/superagent?color=orange&label
[g7]: https://www.npmjs.com/package/got?activeTab=dependents
[k7]: https://www.npmjs.com/package/ky?activeTab=dependents
[n7]: https://www.npmjs.com/package/node-fetch?activeTab=dependents
[a7]: https://www.npmjs.com/package/axios?activeTab=dependents
[s7]: https://www.npmjs.com/package/visionmedia?activeTab=dependents
[gis]: https://packagephobia.com/badge?p=got
[kis]: https://packagephobia.com/badge?p=ky
[nis]: https://packagephobia.com/badge?p=node-fetch
[ais]: https://packagephobia.com/badge?p=axios
[sis]: https://packagephobia.com/badge?p=superagent
[g8]: https://packagephobia.com/result?p=got
[k8]: https://packagephobia.com/result?p=ky
[n8]: https://packagephobia.com/result?p=node-fetch
[a8]: https://packagephobia.com/result?p=axios
[s8]: https://packagephobia.com/result?p=superagent
[gs]: https://img.shields.io/github/stars/sindresorhus/got?color=white&label
[ks]: https://img.shields.io/github/stars/sindresorhus/ky?color=white&label
[ns]: https://img.shields.io/github/stars/bitinn/node-fetch?color=white&label
[as]: https://img.shields.io/github/stars/axios/axios?color=white&label
[ss]: https://img.shields.io/github/stars/visionmedia/superagent?color=white&label
[g9]: https://github.com/sindresorhus/got
[k9]: https://github.com/sindresorhus/ky
[n9]: https://github.com/node-fetch/node-fetch
[a9]: https://github.com/axios/axios
[s9]: https://github.com/visionmedia/superagent
[gts]: https://badgen.net/npm/types/got?label
[kts]: https://badgen.net/npm/types/ky?label
[nts]: https://badgen.net/npm/types/node-fetch?label
[ats]: https://badgen.net/npm/types/axios?label
[sts]: https://badgen.net/npm/types/superagent?label
[g10]: https://github.com/sindresorhus/got
[k10]: https://github.com/sindresorhus/ky
[n10]: https://github.com/node-fetch/node-fetch
[a10]: https://github.com/axios/axios
[glc]: https://img.shields.io/github/last-commit/sindresorhus/got?color=gray&label
[klc]: https://img.shields.io/github/last-commit/sindresorhus/ky?color=gray&label
[nlc]: https://img.shields.io/github/last-commit/bitinn/node-fetch?color=gray&label
[alc]: https://img.shields.io/github/last-commit/axios/axios?color=gray&label
[slc]: https://img.shields.io/github/last-commit/visionmedia/superagent?color=gray&label
[g11]: https://github.com/sindresorhus/got/commits
[k11]: https://github.com/sindresorhus/ky/commits
[n11]: https://github.com/node-fetch/node-fetch/commits
[a11]: https://github.com/axios/axios/commits
[s11]: https://github.com/visionmedia/superagent/commits
[Click here][InstallSizeOfTheDependencies] to see the install size of the Got dependencies.
[InstallSizeOfTheDependencies]: https://packagephobia.com/result?p=@sindresorhus/is@8.0.0,byte-counter@0.1.0,cacheable-request@13.0.18,chunk-data@0.1.0,decompress-response@10.0.0,keyv@5.6.0,lowercase-keys@4.0.1,responselike@4.0.2,type-fest@5.6.0,uint8array-extras@1.5.0
## Maintainers
[](https://sindresorhus.com) | [](https://github.com/szmarczak)
---|---
[Sindre Sorhus](https://sindresorhus.com) | [Szymon Marczak](https://github.com/szmarczak)
## These amazing companies are using Got
> Segment is a happy user of Got! Got powers the main backend API that our app talks to. It's used by our in-house RPC client that we use to communicate with all microservices.
>
> — Vadim Demedes
> Antora, a static site generator for creating documentation sites, uses Got to download the UI bundle. In Antora, the UI bundle (aka theme) is maintained as a separate project. That project exports the UI as a zip file we call the UI bundle. The main site generator downloads that UI from a URL using Got and streams it to vinyl-zip to extract the files. Those files go on to be used to create the HTML pages and supporting assets.
>
> — Dan Allen
> GetVoIP is happily using Got in production. One of the unique capabilities of Got is the ability to handle Unix sockets which enables us to build a full control interfaces for our docker stack.
>
> — Daniel Kalen
> We're using Got inside of Exoframe to handle all the communication between CLI and server. Exoframe is a self-hosted tool that allows simple one-command deployments using Docker.
>
> — Tim Ermilov
> Karaoke Mugen uses Got to fetch content updates from its online server.
>
> — Axel Terizaki
> Renovate uses Got, gh-got and gl-got to send millions of queries per day to GitHub, GitLab, npmjs, PyPi, Packagist, Docker Hub, Terraform, CircleCI, and more.
>
> — Rhys Arkins
> Resistbot uses Got to communicate from the API frontend where all correspondence ingresses to the officials lookup database in back.
>
> — Chris Erickson
> Natural Cycles is using Got to communicate with all kinds of 3rd-party REST APIs (over 9000!).
>
> — Kirill Groshkov
> Microlink is a cloud browser as an API service that uses Got widely as the main HTTP client, serving ~22M requests a month, every time a network call needs to be performed.
>
> — Kiko Beats
> We’re using Got at Radity. Thanks for such an amazing work!
>
> — Mirzayev Farid
[> Back to homepage](../readme.md#documentation)
## Let's make a plugin!
> Another example on how to use Got like a boss :electric_plug:
Okay, so you already have learned some basics. That's great!
When it comes to advanced usage, custom instances are really helpful.
For example, take a look at [`gh-got`](https://github.com/sindresorhus/gh-got).
It looks pretty complicated, but... it's simple and extremely useful.
Before we start, we need to find the [GitHub API docs](https://developer.github.com/v3/).
Let's write down the most important information:
1. The root endpoint is `https://api.github.com/`.
2. We will use version 3 of the API.\
The `Accept` header needs to be set to `application/vnd.github.v3+json`.
3. The body is in a JSON format.
4. We will use OAuth2 for authorization.
5. We may receive `400 Bad Request` or `422 Unprocessable Entity`.\
The body contains detailed information about the error.
6. *Pagination?* Yeah! Supported natively by Got.
7. Rate limiting. These headers are interesting:
- `X-RateLimit-Limit`
- `X-RateLimit-Remaining`
- `X-RateLimit-Reset`
Also `X-GitHub-Request-Id` may be useful for debugging.
8. The `User-Agent` header is required.
When we have all the necessary info, we can start mixing :cake:
### The root endpoint
Not much to do here. Just extend an instance and provide the `prefixUrl` option:
```js
import got from 'got';
const instance = got.extend({
prefixUrl: 'https://api.github.com'
});
export default instance;
```
### v3 API
GitHub needs to know which API version we are using. We'll use the `Accept` header for that:
```js
import got from 'got';
const instance = got.extend({
prefixUrl: 'https://api.github.com',
headers: {
accept: 'application/vnd.github.v3+json'
}
});
export default instance;
```
### JSON body
We'll use [`options.responseType`](2-options.md#responsetype):
```js
import got from 'got';
const instance = got.extend({
prefixUrl: 'https://api.github.com',
headers: {
accept: 'application/vnd.github.v3+json'
},
responseType: 'json'
});
export default instance;
```
### Authorization
It's common to set some environment variables, for example, `GITHUB_TOKEN`. You can modify the tokens in all your apps easily, right? Cool. What about... we want to provide a unique token for each app. Then we will need to create a new option - it will default to the environment variable, but you can easily override it.
Got performs option validation and doesn't know that `token` is a wanted option so it will throw. We can handle it inside an `init` hook and save it in `options.context`.
```js
import got from 'got';
const instance = got.extend({
prefixUrl: 'https://api.github.com',
headers: {
accept: 'application/vnd.github.v3+json'
},
responseType: 'json',
context: {
token: process.env.GITHUB_TOKEN,
},
hooks: {
init: [
(raw, options) => {
if ('token' in raw) {
options.context.token = raw.token;
delete raw.token;
}
}
]
}
});
export default instance;
```
For the rest we will use a handler. We could use hooks, but this way it will be more readable. Having `beforeRequest`, `beforeError` and `afterResponse` hooks for just a few lines of code would complicate things unnecessarily.
**Tip:**
> - It's a good practice to use hooks when your plugin gets complicated.
> - Try not to overload the handler function, but don't abuse hooks either.
```js
import got from 'got';
const instance = got.extend({
prefixUrl: 'https://api.github.com',
headers: {
accept: 'application/vnd.github.v3+json'
},
responseType: 'json',
context: {
token: process.env.GITHUB_TOKEN,
},
hooks: {
init: [
(raw, options) => {
if ('token' in raw) {
options.context.token = raw.token;
delete raw.token;
}
}
]
},
handlers: [
(options, next) => {
// Authorization
const {token} = options.context;
if (token && !options.headers.authorization) {
options.headers.authorization = `token ${token}`;
}
return next(options);
}
]
});
export default instance;
```
### Errors
We should name our errors, just to know if the error is from the API response. Superb errors, here we come!
```js
...
handlers: [
(options, next) => {
// Authorization
const {token} = options.context;
if (token && !options.headers.authorization) {
options.headers.authorization = `token ${token}`;
}
// Don't touch streams
if (options.isStream) {
return next(options);
}
// Magic begins
return (async () => {
try {
const response = await next(options);
return response;
} catch (error) {
const {response} = error;
// Nicer errors
if (response && response.body) {
error.name = 'GitHubError';
error.message = `${response.body.message} (${response.statusCode} status code)`;
}
throw error;
}
})();
}
]
...
```
Note that by providing our own errors in handlers, we don't alter the ones in `beforeError` hooks.\
The conversion is the last thing here.
### Rate limiting
Umm... `response.headers['x-ratelimit-remaining']` doesn't look good. What about `response.rateLimit.limit` instead?\
Yeah, definitely. Since `response.headers` is an object, we can easily parse these:
```js
const getRateLimit = (headers) => ({
limit: Number.parseInt(headers['x-ratelimit-limit'], 10),
remaining: Number.parseInt(headers['x-ratelimit-remaining'], 10),
reset: new Date(Number.parseInt(headers['x-ratelimit-reset'], 10) * 1000)
});
getRateLimit({
'x-ratelimit-limit': '60',
'x-ratelimit-remaining': '55',
'x-ratelimit-reset': '1562852139'
});
// => {
// limit: 60,
// remaining: 55,
// reset: 2019-07-11T13:35:39.000Z
// }
```
Let's integrate it:
```js
const getRateLimit = (headers) => ({
limit: Number.parseInt(headers['x-ratelimit-limit'], 10),
remaining: Number.parseInt(headers['x-ratelimit-remaining'], 10),
reset: new Date(Number.parseInt(headers['x-ratelimit-reset'], 10) * 1000)
});
...
handlers: [
(options, next) => {
// Authorization
const {token} = options.context;
if (token && !options.headers.authorization) {
options.headers.authorization = `token ${token}`;
}
// Don't touch streams
if (options.isStream) {
return next(options);
}
// Magic begins
return (async () => {
try {
const response = await next(options);
// Rate limit for the Response object
response.rateLimit = getRateLimit(response.headers);
return response;
} catch (error) {
const {response} = error;
// Nicer errors
if (response && response.body) {
error.name = 'GitHubError';
error.message = `${response.body.message} (${response.statusCode} status code)`;
}
// Rate limit for errors
if (response) {
error.rateLimit = getRateLimit(response.headers);
}
throw error;
}
})();
}
]
...
```
### The frosting on the cake: `User-Agent` header.
```js
const packageJson = {
name: 'gh-got',
version: '12.0.0'
};
const instance = got.extend({
...
headers: {
accept: 'application/vnd.github.v3+json',
'user-agent': `${packageJson.name}/${packageJson.version}`
},
...
});
```
## Woah. Is that it?
Yup. View the full source code [here](examples/gh-got.js). Here's an example of how to use it:
```js
import ghGot from 'gh-got';
const response = await ghGot('users/sindresorhus');
const creationDate = new Date(response.created_at);
console.log(`Sindre's GitHub profile was created on ${creationDate.toGMTString()}`);
// => Sindre's GitHub profile was created on Sun, 20 Dec 2009 22:57:02 GMT
```
### Pagination
```js
import ghGot from 'gh-got';
const countLimit = 50;
const pagination = ghGot.paginate(
'repos/sindresorhus/got/commits',
{
pagination: {countLimit}
}
);
console.log(`Printing latest ${countLimit} Got commits (newest to oldest):`);
for await (const commitData of pagination) {
console.log(commitData.commit.message);
}
```
That's... astonishing! We don't have to implement pagination on our own. Got handles it all.
### At the end
Did you know you can mix many instances into a bigger, more powerful one? Check out the [Advanced Creation](examples/advanced-creation.js) guide.
'use strict';
const _ = require('lodash');
const async = require('async');
const path = require('path');
const file = require('../common/file');
const util = require('../common/util');
const basePath = path.join(__dirname, '..', '..');
const distPath = path.join(basePath, 'dist');
const filePairs = [
[path.join(distPath, 'lodash.core.js'), 'core.js'],
[path.join(distPath, 'lodash.core.min.js'), 'core.min.js'],
[path.join(distPath, 'lodash.min.js'), 'lodash.min.js']
];
/*----------------------------------------------------------------------------*/
/**
* Creates supplementary Lodash modules at the `target` path.
*
* @private
* @param {string} target The output directory path.
*/
function build(target) {
const actions = _.map(filePairs, pair =>
file.copy(pair[0], path.join(target, pair[1])));
async.series(actions, util.pitch);
}
build(_.last(process.argv));
{
"version": 2,
"metadata": {
"name": "benchmark-template",
"catch2-version": "3.15.2"
},
"listings": {
"tests": [
{
"name": "Comparing function pointers",
"tags": [
"function pointer",
"Tricky"
]
},
{
"name": "Testing checked-if 4",
"tags": [
"!shouldfail",
"checked-if"
]
},
{
"name": "count_equidistant_floats - double",
"tags": [
"approvals",
"distance",
"floating-point"
]
},
{
"name": "Usage of AllTrue range matcher",
"tags": [
"matchers",
"quantifiers",
"templated"
]
},
{
"name": "Exception matchers that succeed",
"tags": [
"!throws",
"exceptions",
"matchers"
]
},
{
"name": "A TEMPLATE_TEST_CASE_METHOD based test run that succeeds - float",
"class-name": "Template_Fixture",
"tags": [
"class",
"template"
]
},
{
"name": "Approximate PI",
"tags": [
"Approx",
"PI"
]
},
{
"name": "TextFlow::Column respects width setting",
"tags": [
"approvals",
"column",
"TextFlow"
]
},
{
"name": "Generators internals",
"tags": [
"generators",
"internals"
]
},
{
"name": "Mayfail test case with nested sections",
"tags": [
"!mayfail"
]
}
]
}
}
name: Publish
on:
push:
tags: ['*']
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
- uses: astral-sh/setup-uv@f0ec1fc3b38f5e7cd731bb6ce540c5af426746bb # v6.1.0
with:
enable-cache: true
prune-cache: false
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
with:
python-version-file: pyproject.toml
- run: echo "SOURCE_DATE_EPOCH=$(git log -1 --pretty=%ct)" >> $GITHUB_ENV
- run: uv build
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
with:
path: ./dist
create-release:
needs: [build]
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
- name: create release
run: >
gh release create --draft --repo ${{ github.repository }}
${{ github.ref_name }} artifact/*
env:
GH_TOKEN: ${{ github.token }}
publish-pypi:
needs: [build]
environment:
name: publish
url: https://pypi.org/project/Jinja2/${{ github.ref_name }}
runs-on: ubuntu-latest
permissions:
id-token: write
steps:
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
- uses: pypa/gh-action-pypi-publish@76f52bc884231f62b9a034ebfe128415bbaabdfc # v1.12.4
with:
packages-dir: artifact/
[> Back to homepage](../readme.md#documentation)
## Errors
Source code:
- [`source/core/errors.ts`](../source/core/errors.ts)
- [`source/as-promise/types.ts`](../source/as-promise/types.ts)
- [`source/core/response.ts`](../source/core/response.ts)
All Got errors contain various metadata, such as:
- `code` - A string like `ERR_NON_2XX_3XX_RESPONSE`,
- `options` - An instance of [`Options`](2-options.md),
- `request` - An instance of Got Stream,
- `response` (optional) - An instance of Got Response,
- `timings` (optional) - Points to `response.timings`.
#### Capturing async stack traces
Read the article [here](async-stack-traces.md).
> [!NOTE]
> - The error codes may differ when the root error has a `code` property set.
> - The root error will be propagated as is via the [`cause`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/cause) property.
### `RequestError`
**Code: `ERR_GOT_REQUEST_ERROR`**
When a request fails. Contains a `code` property with error class code, like `ECONNREFUSED`. All the errors below inherit this one.
### `CacheError`
**Code: `ERR_CACHE_ACCESS`**
When a cache method fails, for example, if the database goes down or there's a filesystem error.
### `ReadError`
**Code: `ERR_READING_RESPONSE_STREAM` or `ERR_HTTP_CONTENT_LENGTH_MISMATCH`**
When reading from response stream fails.
The error code will be `ERR_HTTP_CONTENT_LENGTH_MISMATCH` when the `strictContentLength` option is enabled and the server specifies a `content-length` header but the actual number of bytes received doesn't match.
### `ParseError`
**Code: `ERR_BODY_PARSE_FAILURE`**
When server response code is 2xx, and parsing body fails. Includes a `response` property.
### `UploadError`
**Code: `ERR_UPLOAD`**
When the request body is a stream and an error occurs while reading from that stream.
### `HTTPError`
**Code: `ERR_NON_2XX_3XX_RESPONSE`**
When the request is unsuccessful.
A request is successful when the status code of the final request is `2xx` or `3xx`.
When [following redirects](2-options.md#followredirect), a request is successful **only** when the status code of the final request is `2xx`.
> [!NOTE]
> `304` responses are always considered successful.
### `MaxRedirectsError`
**Code: `ERR_TOO_MANY_REDIRECTS`**
When the server redirects you more than ten times. Includes a `response` property.
### `UnsupportedProtocolError`
> [!NOTE]
> This error is not public.
**Code: `ERR_UNSUPPORTED_PROTOCOL`**
When given an unsupported protocol.
### `TimeoutError`
**Code: `ETIMEDOUT`**
When the request is aborted due to a [timeout](6-timeout.md). Includes an `event` (a string) property along with `timings`.
### `RetryError`
**Code: `ERR_RETRYING`**
Always triggers a new retry when thrown.
### `AbortError`
**Code: `ERR_ABORTED`**
When the request is aborted with [AbortController.abort()](https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort).
'use strict'
var users = require('./db');
exports.html = function(req, res){
res.send('
' + users.map(function(user){
return '
' + user.name + '
';
}).join('') + '
');
};
exports.text = function(req, res){
res.send(users.map(function(user){
return ' - ' + user.name + '\n';
}).join(''));
};
exports.json = function(req, res){
res.json(users);
};
from typing_extensions import assert_type
import click
@click.command()
@click.help_option("-h", "--help")
def hello() -> None:
"""Simple program that greets NAME for a total of COUNT times."""
click.echo("Hello!")
assert_type(hello, click.Command)
# Frequently Asked Questions
```{contents}
:depth: 2
:local: true
```
## General
### Shell Variable Expansion On Windows
I have a simple Click app :
```
import click
@click.command()
@click.argument('message')
def main(message: str):
click.echo(message)
if __name__ == '__main__':
main()
```
When you pass an environment variable in the argument, it expands it:
```{code-block} powershell
> Desktop python foo.py '$M0/.viola/2025-01-25-17-20-23-307878'
> M:/home/ramrachum/.viola/2025-01-25-17-20-23-307878
>
```
Note that I used single quotes above, so my shell is not expanding the environment variable, Click does. How do I get Click to not expand it?
#### Answer
If you don't want Click to emulate (as best it can) unix expansion on Windows, pass windows_expand_args=False when calling the CLI.
Windows command line doesn't do any *, ~, or $ENV expansion. It also doesn't distinguish between double quotes and single quotes (where the later means "don't expand here"). Click emulates the expansion so that the app behaves similarly on both platforms, but doesn't receive information about what quotes were used.
# List of examples
## Already available
- Test Case: [Single-file](../examples/010-TestCase.cpp)
- Test Case: [Multiple-file 1](../examples/020-TestCase-1.cpp), [2](../examples/020-TestCase-2.cpp)
- Assertion: [REQUIRE, CHECK](../examples/030-Asn-Require-Check.cpp)
- Fixture: [Sections](../examples/100-Fix-Section.cpp)
- Fixture: [Class-based fixtures](../examples/110-Fix-ClassFixture.cpp)
- Fixture: [Persistent fixtures](../examples/111-Fix-PersistentFixture.cpp)
- BDD: [SCENARIO, GIVEN, WHEN, THEN](../examples/120-Bdd-ScenarioGivenWhenThen.cpp)
- Listener: [Listeners](../examples/210-Evt-EventListeners.cpp)
- Configuration: [Provide your own output streams](../examples/231-Cfg-OutputStreams.cpp)
- Generators: [Create your own generator](../examples/300-Gen-OwnGenerator.cpp)
- Generators: [Use map to convert types in GENERATE expression](../examples/301-Gen-MapTypeConversion.cpp)
- Generators: [Run test with a table of input values](../examples/302-Gen-Table.cpp)
- Generators: [Use variables in generator expressions](../examples/310-Gen-VariablesInGenerators.cpp)
- Generators: [Use custom variable capture in generator expressions](../examples/311-Gen-CustomCapture.cpp)
## Planned
- Assertion: [REQUIRE_THAT and Matchers](../examples/040-Asn-RequireThat.cpp)
- Assertion: [REQUIRE_NO_THROW](../examples/050-Asn-RequireNoThrow.cpp)
- Assertion: [REQUIRE_THROWS](../examples/050-Asn-RequireThrows.cpp)
- Assertion: [REQUIRE_THROWS_AS](../examples/070-Asn-RequireThrowsAs.cpp)
- Assertion: [REQUIRE_THROWS_WITH](../examples/080-Asn-RequireThrowsWith.cpp)
- Assertion: [REQUIRE_THROWS_MATCHES](../examples/090-Asn-RequireThrowsMatches.cpp)
- Floating point: [Approx - Comparisons](../examples/130-Fpt-Approx.cpp)
- Logging: [CAPTURE - Capture expression](../examples/140-Log-Capture.cpp)
- Logging: [INFO - Provide information with failure](../examples/150-Log-Info.cpp)
- Logging: [WARN - Issue warning](../examples/160-Log-Warn.cpp)
- Logging: [FAIL, FAIL_CHECK - Issue message and force failure/continue](../examples/170-Log-Fail.cpp)
- Logging: [SUCCEED - Issue message and continue](../examples/180-Log-Succeed.cpp)
- Report: [User-defined type](../examples/190-Rpt-ReportUserDefinedType.cpp)
- Report: [User-defined reporter](../examples/202-Rpt-UserDefinedReporter.cpp)
- Report: [Automake reporter](../examples/205-Rpt-AutomakeReporter.cpp)
- Report: [TAP reporter](../examples/206-Rpt-TapReporter.cpp)
- Report: [Multiple reporter](../examples/208-Rpt-MultipleReporters.cpp)
- Configuration: [Provide your own main()](../examples/220-Cfg-OwnMain.cpp)
- Configuration: [Compile-time configuration](../examples/230-Cfg-CompileTimeConfiguration.cpp)
- Configuration: [Run-time configuration](../examples/240-Cfg-RunTimeConfiguration.cpp)
---
[Home](Readme.md#top)
import importlib.metadata
import pytest
import click
import click.core
import click.parser
import click.shell_completion
import click.utils
@pytest.mark.parametrize(
("module", "name", "target"),
[
# Stream helpers, re-exported from both `click` and `click.utils`.
(click, "get_binary_stream", click.utils._get_binary_stream),
(click, "get_text_stream", click.utils._get_text_stream),
(click.utils, "get_binary_stream", click.utils._get_binary_stream),
(click.utils, "get_text_stream", click.utils._get_text_stream),
# Command-class aliases, re-exported from `click` and `click.core`.
(click, "BaseCommand", click.core._BaseCommand),
(click, "MultiCommand", click.core._MultiCommand),
(click.core, "BaseCommand", click.core._BaseCommand),
(click.core, "MultiCommand", click.core._MultiCommand),
# Old parser API (moved to `optparse`); `OptionParser` is also
# re-exported from the top-level `click` namespace.
(click, "OptionParser", click.parser._OptionParser),
(click.parser, "OptionParser", click.parser._OptionParser),
(click.parser, "Argument", click.parser._Argument),
(click.parser, "Option", click.parser._Option),
(click.parser, "split_opt", click.parser._split_opt),
(click.parser, "normalize_opt", click.parser._normalize_opt),
(click.parser, "ParsingState", click.parser._ParsingState),
(click.parser, "split_arg_string", click.shell_completion.split_arg_string),
# Deprecated `click.utils` utilities.
(click.utils, "LazyFile", click.utils._LazyFile),
(click.utils, "KeepOpenFile", click.utils._KeepOpenFile),
(click.utils, "make_default_short_help", click.utils._make_default_short_help),
(click.utils, "PacifyFlushWrapper", click.utils._PacifyFlushWrapper),
(click.utils, "safecall", click.utils._safecall),
# Version metadata attribute.
(click, "__version__", importlib.metadata.version("click")),
],
ids=lambda v: getattr(v, "__name__", v),
)
def test_attr_deprecated(module, name, target):
with pytest.warns(DeprecationWarning, match=name):
value = getattr(module, name)
assert value == target
@pytest.mark.parametrize(
"module",
[click, click.core, click.parser, click.utils],
ids=lambda m: m.__name__,
)
def test_unknown_attribute_raises(module):
with pytest.raises(AttributeError, match="no_such_attribute"):
_ = module.no_such_attribute
def test_context_protected_args_deprecated():
ctx = click.Context(click.Command("cli"))
with pytest.warns(DeprecationWarning, match="protected_args"):
assert ctx.protected_args == []
def test_isolated_filesystem_deprecated(runner):
with pytest.warns(DeprecationWarning, match="isolated_filesystem"):
with runner.isolated_filesystem():
pass
'use strict'
var express = require('../')
, request = require('supertest');
describe('app', function(){
describe('.param(names, fn)', function(){
it('should map the array', function(done){
var app = express();
app.param(['id', 'uid'], function(req, res, next, id){
id = Number(id);
if (isNaN(id)) return next('route');
req.params.id = id;
next();
});
app.get('/post/:id', function(req, res){
var id = req.params.id;
res.send((typeof id) + ':' + id)
});
app.get('/user/:uid', function(req, res){
var id = req.params.id;
res.send((typeof id) + ':' + id)
});
request(app)
.get('/user/123')
.expect(200, 'number:123', function (err) {
if (err) return done(err)
request(app)
.get('/post/123')
.expect('number:123', done)
})
})
})
describe('.param(name, fn)', function(){
it('should map logic for a single param', function(done){
var app = express();
app.param('id', function(req, res, next, id){
id = Number(id);
if (isNaN(id)) return next('route');
req.params.id = id;
next();
});
app.get('/user/:id', function(req, res){
var id = req.params.id;
res.send((typeof id) + ':' + id)
});
request(app)
.get('/user/123')
.expect(200, 'number:123', done)
})
it('should only call once per request', function(done) {
var app = express();
var called = 0;
var count = 0;
app.param('user', function(req, res, next, user) {
called++;
req.user = user;
next();
});
app.get('/foo/:user', function(req, res, next) {
count++;
next();
});
app.get('/foo/:user', function(req, res, next) {
count++;
next();
});
app.use(function(req, res) {
res.end([count, called, req.user].join(' '));
});
request(app)
.get('/foo/bob')
.expect('2 1 bob', done);
})
it('should call when values differ', function(done) {
var app = express();
var called = 0;
var count = 0;
app.param('user', function(req, res, next, user) {
called++;
req.users = (req.users || []).concat(user);
next();
});
app.get('/:user/bob', function(req, res, next) {
count++;
next();
});
app.get('/foo/:user', function(req, res, next) {
count++;
next();
});
app.use(function(req, res) {
res.end([count, called, req.users.join(',')].join(' '));
});
request(app)
.get('/foo/bob')
.expect('2 2 foo,bob', done);
})
it('should support altering req.params across routes', function(done) {
var app = express();
app.param('user', function(req, res, next, user) {
req.params.user = 'loki';
next();
});
app.get('/:user', function(req, res, next) {
next('route');
});
app.get('/:user', function (req, res) {
res.send(req.params.user);
});
request(app)
.get('/bob')
.expect('loki', done);
})
it('should not invoke without route handler', function(done) {
var app = express();
app.param('thing', function(req, res, next, thing) {
req.thing = thing;
next();
});
app.param('user', function(req, res, next, user) {
next(new Error('invalid invocation'))
});
app.post('/:user', function (req, res) {
res.send(req.params.user);
});
app.get('/:thing', function (req, res) {
res.send(req.thing);
});
request(app)
.get('/bob')
.expect(200, 'bob', done);
})
it('should work with encoded values', function(done){
var app = express();
app.param('name', function(req, res, next, name){
req.params.name = name;
next();
});
app.get('/user/:name', function(req, res){
var name = req.params.name;
res.send('' + name);
});
request(app)
.get('/user/foo%25bar')
.expect('foo%bar', done);
})
it('should catch thrown error', function(done){
var app = express();
app.param('id', function(req, res, next, id){
throw new Error('err!');
});
app.get('/user/:id', function(req, res){
var id = req.params.id;
res.send('' + id);
});
request(app)
.get('/user/123')
.expect(500, done);
})
it('should catch thrown secondary error', function(done){
var app = express();
app.param('id', function(req, res, next, val){
process.nextTick(next);
});
app.param('id', function(req, res, next, id){
throw new Error('err!');
});
app.get('/user/:id', function(req, res){
var id = req.params.id;
res.send('' + id);
});
request(app)
.get('/user/123')
.expect(500, done);
})
it('should defer to next route', function(done){
var app = express();
app.param('id', function(req, res, next, id){
next('route');
});
app.get('/user/:id', function(req, res){
var id = req.params.id;
res.send('' + id);
});
app.get('/:name/123', function(req, res){
res.send('name');
});
request(app)
.get('/user/123')
.expect('name', done);
})
it('should defer all the param routes', function(done){
var app = express();
app.param('id', function(req, res, next, val){
if (val === 'new') return next('route');
return next();
});
app.all('/user/:id', function(req, res){
res.send('all.id');
});
app.get('/user/:id', function(req, res){
res.send('get.id');
});
app.get('/user/new', function(req, res){
res.send('get.new');
});
request(app)
.get('/user/new')
.expect('get.new', done);
})
it('should not call when values differ on error', function(done) {
var app = express();
var called = 0;
var count = 0;
app.param('user', function(req, res, next, user) {
called++;
if (user === 'foo') throw new Error('err!');
req.user = user;
next();
});
app.get('/:user/bob', function(req, res, next) {
count++;
next();
});
app.get('/foo/:user', function(req, res, next) {
count++;
next();
});
app.use(function(err, req, res, next) {
res.status(500);
res.send([count, called, err.message].join(' '));
});
request(app)
.get('/foo/bob')
.expect(500, '0 1 err!', done)
});
it('should call when values differ when using "next"', function(done) {
var app = express();
var called = 0;
var count = 0;
app.param('user', function(req, res, next, user) {
called++;
if (user === 'foo') return next('route');
req.user = user;
next();
});
app.get('/:user/bob', function(req, res, next) {
count++;
next();
});
app.get('/foo/:user', function(req, res, next) {
count++;
next();
});
app.use(function(req, res) {
res.end([count, called, req.user].join(' '));
});
request(app)
.get('/foo/bob')
.expect('1 2 bob', done);
})
})
})
[project]
name = "click-example-termui"
version = "1.0.0"
description = "Click termui example"
requires-python = ">=3.10"
dependencies = [
"click>=8.1",
]
[project.scripts]
termui = "termui:cli"
[build-system]
requires = ["flit_core<4"]
build-backend = "flit_core.buildapi"
[tool.flit.module]
name = "termui"
'use strict';
const _ = require('lodash');
/*----------------------------------------------------------------------------*/
/**
* Creates a hash object. If a `properties` object is provided, its own
* enumerable properties are assigned to the created hash.
*
* @memberOf util
* @param {Object} [properties] The properties to assign to the hash.
* @returns {Object} Returns the new hash object.
*/
function Hash(properties) {
return _.transform(properties, (result, value, key) => {
result[key] = (_.isPlainObject(value) && !(value instanceof Hash))
? new Hash(value)
: value;
}, this);
}
Hash.prototype = Object.create(null);
/**
* This method throws any error it receives.
*
* @memberOf util
* @param {Object} [error] The error object.
*/
function pitch(error) {
if (error != null) {
throw error;
}
}
module.exports = {
Hash,
pitch
};
'use strict'
var express = require('../../..');
var apiv2 = express.Router();
apiv2.get('/', function(req, res) {
res.send('Hello from APIv2 root route.');
});
apiv2.get('/users', function(req, res) {
res.send('List of APIv2 users.');
});
module.exports = apiv2;
/*!
* express
* Copyright(c) 2009-2013 TJ Holowaychuk
* Copyright(c) 2013 Roman Shtylman
* Copyright(c) 2014-2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict';
/**
* Module dependencies.
* @private
*/
var finalhandler = require('finalhandler');
var debug = require('debug')('express:application');
var View = require('./view');
var http = require('node:http');
var methods = require('./utils').methods;
var compileETag = require('./utils').compileETag;
var compileQueryParser = require('./utils').compileQueryParser;
var compileTrust = require('./utils').compileTrust;
var resolve = require('node:path').resolve;
var once = require('once')
var Router = require('router');
/**
* Module variables.
* @private
*/
var slice = Array.prototype.slice;
var flatten = Array.prototype.flat;
/**
* Application prototype.
*/
var app = exports = module.exports = {};
/**
* Variable for trust proxy inheritance back-compat
* @private
*/
var trustProxyDefaultSymbol = '@@symbol:trust_proxy_default';
/**
* Initialize the server.
*
* - setup default configuration
* - setup default middleware
* - setup route reflection methods
*
* @private
*/
app.init = function init() {
var router = null;
this.cache = Object.create(null);
this.engines = Object.create(null);
this.settings = Object.create(null);
this.defaultConfiguration();
// Setup getting to lazily add base router
Object.defineProperty(this, 'router', {
configurable: true,
enumerable: true,
get: function getrouter() {
if (router === null) {
router = new Router({
caseSensitive: this.enabled('case sensitive routing'),
strict: this.enabled('strict routing')
});
}
return router;
}
});
};
/**
* Initialize application configuration.
* @private
*/
app.defaultConfiguration = function defaultConfiguration() {
var env = process.env.NODE_ENV || 'development';
// default settings
this.enable('x-powered-by');
this.set('etag', 'weak');
this.set('env', env);
this.set('query parser', 'simple')
this.set('subdomain offset', 2);
this.set('trust proxy', false);
// trust proxy inherit back-compat
Object.defineProperty(this.settings, trustProxyDefaultSymbol, {
configurable: true,
value: true
});
debug('booting in %s mode', env);
this.on('mount', function onmount(parent) {
// inherit trust proxy
if (this.settings[trustProxyDefaultSymbol] === true
&& typeof parent.settings['trust proxy fn'] === 'function') {
delete this.settings['trust proxy'];
delete this.settings['trust proxy fn'];
}
// inherit protos
Object.setPrototypeOf(this.request, parent.request)
Object.setPrototypeOf(this.response, parent.response)
Object.setPrototypeOf(this.engines, parent.engines)
Object.setPrototypeOf(this.settings, parent.settings)
});
// setup locals
this.locals = Object.create(null);
// top-most app is mounted at /
this.mountpath = '/';
// default locals
this.locals.settings = this.settings;
// default configuration
this.set('view', View);
this.set('views', resolve('views'));
this.set('jsonp callback name', 'callback');
if (env === 'production') {
this.enable('view cache');
}
};
/**
* Dispatch a req, res pair into the application. Starts pipeline processing.
*
* If no callback is provided, then default error handlers will respond
* in the event of an error bubbling through the stack.
*
* @private
*/
app.handle = function handle(req, res, callback) {
// final handler
var done = callback || finalhandler(req, res, {
env: this.get('env'),
onerror: logerror.bind(this)
});
// set powered by header
if (this.enabled('x-powered-by')) {
res.setHeader('X-Powered-By', 'Express');
}
// set circular references
req.res = res;
res.req = req;
// alter the prototypes
Object.setPrototypeOf(req, this.request)
Object.setPrototypeOf(res, this.response)
// setup locals
if (!res.locals) {
res.locals = Object.create(null);
}
this.router.handle(req, res, done);
};
/**
* Proxy `Router#use()` to add middleware to the app router.
* See Router#use() documentation for details.
*
* If the _fn_ parameter is an express app, then it will be
* mounted at the _route_ specified.
*
* @public
*/
app.use = function use(fn) {
var offset = 0;
var path = '/';
// default path to '/'
// disambiguate app.use([fn])
if (typeof fn !== 'function') {
var arg = fn;
while (Array.isArray(arg) && arg.length !== 0) {
arg = arg[0];
}
// first arg is the path
if (typeof arg !== 'function') {
offset = 1;
path = fn;
}
}
var fns = flatten.call(slice.call(arguments, offset), Infinity);
if (fns.length === 0) {
throw new TypeError('app.use() requires a middleware function')
}
// get router
var router = this.router;
fns.forEach(function (fn) {
// non-express app
if (!fn || !fn.handle || !fn.set) {
return router.use(path, fn);
}
debug('.use app under %s', path);
fn.mountpath = path;
fn.parent = this;
// restore .app property on req and res
router.use(path, function mounted_app(req, res, next) {
var orig = req.app;
fn.handle(req, res, function (err) {
Object.setPrototypeOf(req, orig.request)
Object.setPrototypeOf(res, orig.response)
next(err);
});
});
// mounted an app
fn.emit('mount', this);
}, this);
return this;
};
/**
* Proxy to the app `Router#route()`
* Returns a new `Route` instance for the _path_.
*
* Routes are isolated middleware stacks for specific paths.
* See the Route api docs for details.
*
* @public
*/
app.route = function route(path) {
return this.router.route(path);
};
/**
* Register the given template engine callback `fn`
* as `ext`.
*
* By default will `require()` the engine based on the
* file extension. For example if you try to render
* a "foo.ejs" file Express will invoke the following internally:
*
* app.engine('ejs', require('ejs').__express);
*
* For engines that do not provide `.__express` out of the box,
* or if you wish to "map" a different extension to the template engine
* you may use this method. For example mapping the EJS template engine to
* ".html" files:
*
* app.engine('html', require('ejs').renderFile);
*
* In this case EJS provides a `.renderFile()` method with
* the same signature that Express expects: `(path, options, callback)`,
* though note that it aliases this method as `ejs.__express` internally
* so if you're using ".ejs" extensions you don't need to do anything.
*
* Some template engines do not follow this convention, the
* [Consolidate.js](https://github.com/tj/consolidate.js)
* library was created to map all of node's popular template
* engines to follow this convention, thus allowing them to
* work seamlessly within Express.
*
* @param {String} ext
* @param {Function} fn
* @return {app} for chaining
* @public
*/
app.engine = function engine(ext, fn) {
if (typeof fn !== 'function') {
throw new Error('callback function required');
}
// get file extension
var extension = ext[0] !== '.'
? '.' + ext
: ext;
// store engine
this.engines[extension] = fn;
return this;
};
/**
* Proxy to `Router#param()` with one added api feature. The _name_ parameter
* can be an array of names.
*
* See the Router#param() docs for more details.
*
* @param {String|Array} name
* @param {Function} fn
* @return {app} for chaining
* @public
*/
app.param = function param(name, fn) {
if (Array.isArray(name)) {
for (var i = 0; i < name.length; i++) {
this.param(name[i], fn);
}
return this;
}
this.router.param(name, fn);
return this;
};
/**
* Assign `setting` to `val`, or return `setting`'s value.
*
* app.set('foo', 'bar');
* app.set('foo');
* // => "bar"
*
* Mounted servers inherit their parent server's settings.
*
* @param {String} setting
* @param {*} [val]
* @return {Server} for chaining
* @public
*/
app.set = function set(setting, val) {
if (arguments.length === 1) {
// app.get(setting)
return this.settings[setting];
}
debug('set "%s" to %o', setting, val);
// set value
this.settings[setting] = val;
// trigger matched settings
switch (setting) {
case 'etag':
this.set('etag fn', compileETag(val));
break;
case 'query parser':
this.set('query parser fn', compileQueryParser(val));
break;
case 'trust proxy':
this.set('trust proxy fn', compileTrust(val));
// trust proxy inherit back-compat
Object.defineProperty(this.settings, trustProxyDefaultSymbol, {
configurable: true,
value: false
});
break;
}
return this;
};
/**
* Return the app's absolute pathname
* based on the parent(s) that have
* mounted it.
*
* For example if the application was
* mounted as "/admin", which itself
* was mounted as "/blog" then the
* return value would be "/blog/admin".
*
* @return {String}
* @private
*/
app.path = function path() {
return this.parent
? this.parent.path() + this.mountpath
: '';
};
/**
* Check if `setting` is enabled (truthy).
*
* app.enabled('foo')
* // => false
*
* app.enable('foo')
* app.enabled('foo')
* // => true
*
* @param {String} setting
* @return {Boolean}
* @public
*/
app.enabled = function enabled(setting) {
return Boolean(this.set(setting));
};
/**
* Check if `setting` is disabled.
*
* app.disabled('foo')
* // => true
*
* app.enable('foo')
* app.disabled('foo')
* // => false
*
* @param {String} setting
* @return {Boolean}
* @public
*/
app.disabled = function disabled(setting) {
return !this.set(setting);
};
/**
* Enable `setting`.
*
* @param {String} setting
* @return {app} for chaining
* @public
*/
app.enable = function enable(setting) {
return this.set(setting, true);
};
/**
* Disable `setting`.
*
* @param {String} setting
* @return {app} for chaining
* @public
*/
app.disable = function disable(setting) {
return this.set(setting, false);
};
/**
* Delegate `.VERB(...)` calls to `router.VERB(...)`.
*/
methods.forEach(function (method) {
app[method] = function (path) {
if (method === 'get' && arguments.length === 1) {
// app.get(setting)
return this.set(path);
}
var route = this.route(path);
route[method].apply(route, slice.call(arguments, 1));
return this;
};
});
/**
* Special-cased "all" method, applying the given route `path`,
* middleware, and callback to _every_ HTTP method.
*
* @param {String} path
* @param {Function} ...
* @return {app} for chaining
* @public
*/
app.all = function all(path) {
var route = this.route(path);
var args = slice.call(arguments, 1);
for (var i = 0; i < methods.length; i++) {
route[methods[i]].apply(route, args);
}
return this;
};
/**
* Render the given view `name` name with `options`
* and a callback accepting an error and the
* rendered template string.
*
* Example:
*
* app.render('email', { name: 'Tobi' }, function(err, html){
* // ...
* })
*
* @param {String} name
* @param {Object|Function} options or fn
* @param {Function} callback
* @public
*/
app.render = function render(name, options, callback) {
var cache = this.cache;
var done = callback;
var engines = this.engines;
var opts = options || {};
var view;
// support callback function as second arg
if (typeof options === 'function') {
done = options;
opts = {};
}
// merge options
var renderOptions = { ...this.locals, ...opts._locals, ...opts };
// set .cache unless explicitly provided
if (renderOptions.cache == null) {
renderOptions.cache = this.enabled('view cache');
}
// primed cache
if (renderOptions.cache) {
view = cache[name];
}
// view
if (!view) {
var View = this.get('view');
view = new View(name, {
defaultEngine: this.get('view engine'),
root: this.get('views'),
engines: engines
});
if (!view.path) {
var dirs = Array.isArray(view.root) && view.root.length > 1
? 'directories "' + view.root.slice(0, -1).join('", "') + '" or "' + view.root[view.root.length - 1] + '"'
: 'directory "' + view.root + '"'
var err = new Error('Failed to lookup view "' + name + '" in views ' + dirs);
err.view = view;
return done(err);
}
// prime the cache
if (renderOptions.cache) {
cache[name] = view;
}
}
// render
tryRender(view, renderOptions, done);
};
/**
* Listen for connections.
*
* A node `http.Server` is returned, with this
* application (which is a `Function`) as its
* callback. If you wish to create both an HTTP
* and HTTPS server you may do so with the "http"
* and "https" modules as shown here:
*
* var http = require('node:http')
* , https = require('node:https')
* , express = require('express')
* , app = express();
*
* http.createServer(app).listen(80);
* https.createServer({ ... }, app).listen(443);
*
* @return {http.Server}
* @public
*/
app.listen = function listen() {
var server = http.createServer(this)
var args = slice.call(arguments)
if (typeof args[args.length - 1] === 'function') {
var done = args[args.length - 1] = once(args[args.length - 1])
server.once('error', done)
}
return server.listen.apply(server, args)
}
/**
* Log error using console.error.
*
* @param {Error} err
* @private
*/
function logerror(err) {
/* istanbul ignore next */
if (this.get('env') !== 'test') console.error(err);
}
/**
* Try rendering a view.
* @private
*/
function tryRender(view, options, callback) {
try {
view.render(options, callback);
} catch (err) {
callback(err);
}
}
version: 2
updates:
- package-ecosystem: github-actions
directory: /
schedule:
interval: monthly
- package-ecosystem: npm
directory: /
schedule:
interval: monthly
time: "23:00"
timezone: Europe/London
open-pull-requests-limit: 10
ignore:
- dependency-name: "*"
update-types: ["version-update:semver-major"]
# Reference
To get the most out of Catch2, start with the [tutorial](tutorial.md#top).
Once you're up and running consider the following reference material.
**Writing tests:**
* [Assertion macros](assertions.md#top)
* [Matchers (asserting complex properties)](matchers.md#top)
* [Comparing floating point numbers](comparing-floating-point-numbers.md#top)
* [Logging macros](logging.md#top)
* [Test cases and sections](test-cases-and-sections.md#top)
* [Test fixtures](test-fixtures.md#top)
* [Explicitly skipping, passing, and failing tests at runtime](skipping-passing-failing.md#top)
* [Reporters (output customization)](reporters.md#top)
* [Event Listeners](event-listeners.md#top)
* [Data Generators (value parameterized tests)](generators.md#top)
* [Other macros](other-macros.md#top)
* [Micro benchmarking](benchmarks.md#top)
**Fine tuning:**
* [Supplying your own main()](own-main.md#top)
* [Compile-time configuration](configuration.md#top)
* [String Conversions](tostring.md#top)
**Running:**
* [Command line reference](command-line.md#top)
* [Running specific section/generator](filtering-execution-path.md#top)
**Odds and ends:**
* [Frequently Asked Questions (FAQ)](faq.md#top)
* [Best practices and other tips](usage-tips.md#top)
* [CMake integration](cmake-integration.md#top)
* [Tooling integration (CI, test runners, other)](ci-and-misc.md#top)
* [Known limitations](limitations.md#top)
* [Thread safety in Catch2](thread-safety.md#top)
**Other:**
* [Why Catch2?](why-catch.md#top)
* [Migrating from v2 to v3](migrate-v2-to-v3.md#top)
* [Open Source Projects using Catch2](opensource-users.md#top)
* [Commercial Projects using Catch2](commercial-users.md#top)
* [Contributing](contributing.md#top)
* [Release Notes](release-notes.md#top)
* [Deprecations and incoming changes](deprecations.md#top)
import type {Writable, Readable} from 'node:stream';
import type {ClientRequest} from 'node:http';
function isClientRequest(clientRequest: Writable | Readable): clientRequest is ClientRequest {
return (clientRequest as Writable).writable && !(clientRequest as Writable).writableEnded;
}
export default isClientRequest;
import pytest
from jinja2 import DictLoader
from jinja2 import Environment
from jinja2 import TemplateRuntimeError
from jinja2 import TemplateSyntaxError
from jinja2 import UndefinedError
@pytest.fixture
def env_trim():
return Environment(trim_blocks=True)
class TestForLoop:
def test_simple(self, env):
tmpl = env.from_string("{% for item in seq %}{{ item }}{% endfor %}")
assert tmpl.render(seq=list(range(10))) == "0123456789"
def test_else(self, env):
tmpl = env.from_string("{% for item in seq %}XXX{% else %}...{% endfor %}")
assert tmpl.render() == "..."
def test_else_scoping_item(self, env):
tmpl = env.from_string("{% for item in [] %}{% else %}{{ item }}{% endfor %}")
assert tmpl.render(item=42) == "42"
def test_empty_blocks(self, env):
tmpl = env.from_string("<{% for item in seq %}{% else %}{% endfor %}>")
assert tmpl.render() == "<>"
def test_context_vars(self, env):
slist = [42, 24]
for seq in [slist, iter(slist), reversed(slist), (_ for _ in slist)]:
tmpl = env.from_string(
"""{% for item in seq -%}
{{ loop.index }}|{{ loop.index0 }}|{{ loop.revindex }}|{{
loop.revindex0 }}|{{ loop.first }}|{{ loop.last }}|{{
loop.length }}###{% endfor %}"""
)
one, two, _ = tmpl.render(seq=seq).split("###")
(
one_index,
one_index0,
one_revindex,
one_revindex0,
one_first,
one_last,
one_length,
) = one.split("|")
(
two_index,
two_index0,
two_revindex,
two_revindex0,
two_first,
two_last,
two_length,
) = two.split("|")
assert int(one_index) == 1 and int(two_index) == 2
assert int(one_index0) == 0 and int(two_index0) == 1
assert int(one_revindex) == 2 and int(two_revindex) == 1
assert int(one_revindex0) == 1 and int(two_revindex0) == 0
assert one_first == "True" and two_first == "False"
assert one_last == "False" and two_last == "True"
assert one_length == two_length == "2"
def test_cycling(self, env):
tmpl = env.from_string(
"""{% for item in seq %}{{
loop.cycle('<1>', '<2>') }}{% endfor %}{%
for item in seq %}{{ loop.cycle(*through) }}{% endfor %}"""
)
output = tmpl.render(seq=list(range(4)), through=("<1>", "<2>"))
assert output == "<1><2>" * 4
def test_lookaround(self, env):
tmpl = env.from_string(
"""{% for item in seq -%}
{{ loop.previtem|default('x') }}-{{ item }}-{{
loop.nextitem|default('x') }}|
{%- endfor %}"""
)
output = tmpl.render(seq=list(range(4)))
assert output == "x-0-1|0-1-2|1-2-3|2-3-x|"
def test_changed(self, env):
tmpl = env.from_string(
"""{% for item in seq -%}
{{ loop.changed(item) }},
{%- endfor %}"""
)
output = tmpl.render(seq=[None, None, 1, 2, 2, 3, 4, 4, 4])
assert output == "True,False,True,True,False,True,True,False,False,"
def test_scope(self, env):
tmpl = env.from_string("{% for item in seq %}{% endfor %}{{ item }}")
output = tmpl.render(seq=list(range(10)))
assert not output
def test_varlen(self, env):
tmpl = env.from_string("{% for item in iter %}{{ item }}{% endfor %}")
output = tmpl.render(iter=range(5))
assert output == "01234"
def test_noniter(self, env):
tmpl = env.from_string("{% for item in none %}...{% endfor %}")
pytest.raises(TypeError, tmpl.render)
def test_recursive(self, env):
tmpl = env.from_string(
"""{% for item in seq recursive -%}
[{{ item.a }}{% if item.b %}<{{ loop(item.b) }}>{% endif %}]
{%- endfor %}"""
)
assert (
tmpl.render(
seq=[
dict(a=1, b=[dict(a=1), dict(a=2)]),
dict(a=2, b=[dict(a=1), dict(a=2)]),
dict(a=3, b=[dict(a="a")]),
]
)
== "[1<[1][2]>][2<[1][2]>][3<[a]>]"
)
def test_recursive_lookaround(self, env):
tmpl = env.from_string(
"""{% for item in seq recursive -%}
[{{ loop.previtem.a if loop.previtem is defined else 'x' }}.{{
item.a }}.{{ loop.nextitem.a if loop.nextitem is defined else 'x'
}}{% if item.b %}<{{ loop(item.b) }}>{% endif %}]
{%- endfor %}"""
)
assert (
tmpl.render(
seq=[
dict(a=1, b=[dict(a=1), dict(a=2)]),
dict(a=2, b=[dict(a=1), dict(a=2)]),
dict(a=3, b=[dict(a="a")]),
]
)
== "[x.1.2<[x.1.2][1.2.x]>][1.2.3<[x.1.2][1.2.x]>][2.3.x<[x.a.x]>]"
)
def test_recursive_depth0(self, env):
tmpl = env.from_string(
"""{% for item in seq recursive -%}
[{{ loop.depth0 }}:{{ item.a }}{% if item.b %}<{{ loop(item.b) }}>{% endif %}]
{%- endfor %}"""
)
assert (
tmpl.render(
seq=[
dict(a=1, b=[dict(a=1), dict(a=2)]),
dict(a=2, b=[dict(a=1), dict(a=2)]),
dict(a=3, b=[dict(a="a")]),
]
)
== "[0:1<[1:1][1:2]>][0:2<[1:1][1:2]>][0:3<[1:a]>]"
)
def test_recursive_depth(self, env):
tmpl = env.from_string(
"""{% for item in seq recursive -%}
[{{ loop.depth }}:{{ item.a }}{% if item.b %}<{{ loop(item.b) }}>{% endif %}]
{%- endfor %}"""
)
assert (
tmpl.render(
seq=[
dict(a=1, b=[dict(a=1), dict(a=2)]),
dict(a=2, b=[dict(a=1), dict(a=2)]),
dict(a=3, b=[dict(a="a")]),
]
)
== "[1:1<[2:1][2:2]>][1:2<[2:1][2:2]>][1:3<[2:a]>]"
)
def test_looploop(self, env):
tmpl = env.from_string(
"""{% for row in table %}
{%- set rowloop = loop -%}
{% for cell in row -%}
[{{ rowloop.index }}|{{ loop.index }}]
{%- endfor %}
{%- endfor %}"""
)
assert tmpl.render(table=["ab", "cd"]) == "[1|1][1|2][2|1][2|2]"
def test_reversed_bug(self, env):
tmpl = env.from_string(
"{% for i in items %}{{ i }}{% if not loop.last %},{% endif %}{% endfor %}"
)
assert tmpl.render(items=reversed([3, 2, 1])) == "1,2,3"
def test_loop_errors(self, env):
tmpl = env.from_string(
"""{% for item in [1] if loop.index
== 0 %}...{% endfor %}"""
)
pytest.raises(UndefinedError, tmpl.render)
tmpl = env.from_string(
"""{% for item in [] %}...{% else
%}{{ loop }}{% endfor %}"""
)
assert tmpl.render() == ""
def test_loop_filter(self, env):
tmpl = env.from_string(
"{% for item in range(10) if item is even %}[{{ item }}]{% endfor %}"
)
assert tmpl.render() == "[0][2][4][6][8]"
tmpl = env.from_string(
"""
{%- for item in range(10) if item is even %}[{{
loop.index }}:{{ item }}]{% endfor %}"""
)
assert tmpl.render() == "[1:0][2:2][3:4][4:6][5:8]"
def test_loop_unassignable(self, env):
pytest.raises(
TemplateSyntaxError, env.from_string, "{% for loop in seq %}...{% endfor %}"
)
def test_scoped_special_var(self, env):
t = env.from_string(
"{% for s in seq %}[{{ loop.first }}{% for c in s %}"
"|{{ loop.first }}{% endfor %}]{% endfor %}"
)
assert t.render(seq=("ab", "cd")) == "[True|True|False][False|True|False]"
def test_scoped_loop_var(self, env):
t = env.from_string(
"{% for x in seq %}{{ loop.first }}"
"{% for y in seq %}{% endfor %}{% endfor %}"
)
assert t.render(seq="ab") == "TrueFalse"
t = env.from_string(
"{% for x in seq %}{% for y in seq %}"
"{{ loop.first }}{% endfor %}{% endfor %}"
)
assert t.render(seq="ab") == "TrueFalseTrueFalse"
def test_recursive_empty_loop_iter(self, env):
t = env.from_string(
"""
{%- for item in foo recursive -%}{%- endfor -%}
"""
)
assert t.render(dict(foo=[])) == ""
def test_call_in_loop(self, env):
t = env.from_string(
"""
{%- macro do_something() -%}
[{{ caller() }}]
{%- endmacro %}
{%- for i in [1, 2, 3] %}
{%- call do_something() -%}
{{ i }}
{%- endcall %}
{%- endfor -%}
"""
)
assert t.render() == "[1][2][3]"
def test_scoping_bug(self, env):
t = env.from_string(
"""
{%- for item in foo %}...{{ item }}...{% endfor %}
{%- macro item(a) %}...{{ a }}...{% endmacro %}
{{- item(2) -}}
"""
)
assert t.render(foo=(1,)) == "...1......2..."
def test_unpacking(self, env):
tmpl = env.from_string(
"{% for a, b, c in [[1, 2, 3]] %}{{ a }}|{{ b }}|{{ c }}{% endfor %}"
)
assert tmpl.render() == "1|2|3"
def test_intended_scoping_with_set(self, env):
tmpl = env.from_string(
"{% for item in seq %}{{ x }}{% set x = item %}{{ x }}{% endfor %}"
)
assert tmpl.render(x=0, seq=[1, 2, 3]) == "010203"
tmpl = env.from_string(
"{% set x = 9 %}{% for item in seq %}{{ x }}"
"{% set x = item %}{{ x }}{% endfor %}"
)
assert tmpl.render(x=0, seq=[1, 2, 3]) == "919293"
class TestIfCondition:
def test_simple(self, env):
tmpl = env.from_string("""{% if true %}...{% endif %}""")
assert tmpl.render() == "..."
def test_elif(self, env):
tmpl = env.from_string(
"""{% if false %}XXX{% elif true
%}...{% else %}XXX{% endif %}"""
)
assert tmpl.render() == "..."
def test_elif_deep(self, env):
elifs = "\n".join(f"{{% elif a == {i} %}}{i}" for i in range(1, 1000))
tmpl = env.from_string(f"{{% if a == 0 %}}0{elifs}{{% else %}}x{{% endif %}}")
for x in (0, 10, 999):
assert tmpl.render(a=x).strip() == str(x)
assert tmpl.render(a=1000).strip() == "x"
def test_else(self, env):
tmpl = env.from_string("{% if false %}XXX{% else %}...{% endif %}")
assert tmpl.render() == "..."
def test_empty(self, env):
tmpl = env.from_string("[{% if true %}{% else %}{% endif %}]")
assert tmpl.render() == "[]"
def test_complete(self, env):
tmpl = env.from_string(
"{% if a %}A{% elif b %}B{% elif c == d %}C{% else %}D{% endif %}"
)
assert tmpl.render(a=0, b=False, c=42, d=42.0) == "C"
def test_no_scope(self, env):
tmpl = env.from_string("{% if a %}{% set foo = 1 %}{% endif %}{{ foo }}")
assert tmpl.render(a=True) == "1"
tmpl = env.from_string("{% if true %}{% set foo = 1 %}{% endif %}{{ foo }}")
assert tmpl.render() == "1"
class TestMacros:
def test_simple(self, env_trim):
tmpl = env_trim.from_string(
"""\
{% macro say_hello(name) %}Hello {{ name }}!{% endmacro %}
{{ say_hello('Peter') }}"""
)
assert tmpl.render() == "Hello Peter!"
def test_scoping(self, env_trim):
tmpl = env_trim.from_string(
"""\
{% macro level1(data1) %}
{% macro level2(data2) %}{{ data1 }}|{{ data2 }}{% endmacro %}
{{ level2('bar') }}{% endmacro %}
{{ level1('foo') }}"""
)
assert tmpl.render() == "foo|bar"
def test_arguments(self, env_trim):
tmpl = env_trim.from_string(
"""\
{% macro m(a, b, c='c', d='d') %}{{ a }}|{{ b }}|{{ c }}|{{ d }}{% endmacro %}
{{ m() }}|{{ m('a') }}|{{ m('a', 'b') }}|{{ m(1, 2, 3) }}"""
)
assert tmpl.render() == "||c|d|a||c|d|a|b|c|d|1|2|3|d"
def test_arguments_defaults_nonsense(self, env_trim):
pytest.raises(
TemplateSyntaxError,
env_trim.from_string,
"""\
{% macro m(a, b=1, c) %}a={{ a }}, b={{ b }}, c={{ c }}{% endmacro %}""",
)
def test_caller_defaults_nonsense(self, env_trim):
pytest.raises(
TemplateSyntaxError,
env_trim.from_string,
"""\
{% macro a() %}{{ caller() }}{% endmacro %}
{% call(x, y=1, z) a() %}{% endcall %}""",
)
def test_varargs(self, env_trim):
tmpl = env_trim.from_string(
"""\
{% macro test() %}{{ varargs|join('|') }}{% endmacro %}\
{{ test(1, 2, 3) }}"""
)
assert tmpl.render() == "1|2|3"
def test_simple_call(self, env_trim):
tmpl = env_trim.from_string(
"""\
{% macro test() %}[[{{ caller() }}]]{% endmacro %}\
{% call test() %}data{% endcall %}"""
)
assert tmpl.render() == "[[data]]"
def test_complex_call(self, env_trim):
tmpl = env_trim.from_string(
"""\
{% macro test() %}[[{{ caller('data') }}]]{% endmacro %}\
{% call(data) test() %}{{ data }}{% endcall %}"""
)
assert tmpl.render() == "[[data]]"
def test_caller_undefined(self, env_trim):
tmpl = env_trim.from_string(
"""\
{% set caller = 42 %}\
{% macro test() %}{{ caller is not defined }}{% endmacro %}\
{{ test() }}"""
)
assert tmpl.render() == "True"
def test_include(self, env_trim):
env_trim = Environment(
loader=DictLoader(
{"include": "{% macro test(foo) %}[{{ foo }}]{% endmacro %}"}
)
)
tmpl = env_trim.from_string('{% from "include" import test %}{{ test("foo") }}')
assert tmpl.render() == "[foo]"
def test_macro_api(self, env_trim):
tmpl = env_trim.from_string(
"{% macro foo(a, b) %}{% endmacro %}"
"{% macro bar() %}{{ varargs }}{{ kwargs }}{% endmacro %}"
"{% macro baz() %}{{ caller() }}{% endmacro %}"
)
assert tmpl.module.foo.arguments == ("a", "b")
assert tmpl.module.foo.name == "foo"
assert not tmpl.module.foo.caller
assert not tmpl.module.foo.catch_kwargs
assert not tmpl.module.foo.catch_varargs
assert tmpl.module.bar.arguments == ()
assert not tmpl.module.bar.caller
assert tmpl.module.bar.catch_kwargs
assert tmpl.module.bar.catch_varargs
assert tmpl.module.baz.caller
def test_callself(self, env_trim):
tmpl = env_trim.from_string(
"{% macro foo(x) %}{{ x }}{% if x > 1 %}|"
"{{ foo(x - 1) }}{% endif %}{% endmacro %}"
"{{ foo(5) }}"
)
assert tmpl.render() == "5|4|3|2|1"
def test_macro_defaults_self_ref(self, env):
tmpl = env.from_string(
"""
{%- set x = 42 %}
{%- macro m(a, b=x, x=23) %}{{ a }}|{{ b }}|{{ x }}{% endmacro -%}
"""
)
assert tmpl.module.m(1) == "1||23"
assert tmpl.module.m(1, 2) == "1|2|23"
assert tmpl.module.m(1, 2, 3) == "1|2|3"
assert tmpl.module.m(1, x=7) == "1|7|7"
class TestSet:
def test_normal(self, env_trim):
tmpl = env_trim.from_string("{% set foo = 1 %}{{ foo }}")
assert tmpl.render() == "1"
assert tmpl.module.foo == 1
def test_block(self, env_trim):
tmpl = env_trim.from_string("{% set foo %}42{% endset %}{{ foo }}")
assert tmpl.render() == "42"
assert tmpl.module.foo == "42"
def test_block_escaping(self):
env = Environment(autoescape=True)
tmpl = env.from_string(
"{% set foo %}{{ test }}{% endset %}foo: {{ foo }}"
)
assert tmpl.render(test="") == "foo: <unsafe>"
def test_set_invalid(self, env_trim):
pytest.raises(
TemplateSyntaxError, env_trim.from_string, "{% set foo['bar'] = 1 %}"
)
tmpl = env_trim.from_string("{% set foo.bar = 1 %}")
exc_info = pytest.raises(TemplateRuntimeError, tmpl.render, foo={})
assert "non-namespace object" in exc_info.value.message
def test_namespace_redefined(self, env_trim):
tmpl = env_trim.from_string("{% set ns = namespace() %}{% set ns.bar = 'hi' %}")
exc_info = pytest.raises(TemplateRuntimeError, tmpl.render, namespace=dict)
assert "non-namespace object" in exc_info.value.message
def test_namespace(self, env_trim):
tmpl = env_trim.from_string(
"{% set ns = namespace() %}{% set ns.bar = '42' %}{{ ns.bar }}"
)
assert tmpl.render() == "42"
def test_namespace_block(self, env_trim):
tmpl = env_trim.from_string(
"{% set ns = namespace() %}{% set ns.bar %}42{% endset %}{{ ns.bar }}"
)
assert tmpl.render() == "42"
def test_init_namespace(self, env_trim):
tmpl = env_trim.from_string(
"{% set ns = namespace(d, self=37) %}"
"{% set ns.b = 42 %}"
"{{ ns.a }}|{{ ns.self }}|{{ ns.b }}"
)
assert tmpl.render(d={"a": 13}) == "13|37|42"
def test_namespace_loop(self, env_trim):
tmpl = env_trim.from_string(
"{% set ns = namespace(found=false) %}"
"{% for x in range(4) %}"
"{% if x == v %}"
"{% set ns.found = true %}"
"{% endif %}"
"{% endfor %}"
"{{ ns.found }}"
)
assert tmpl.render(v=3) == "True"
assert tmpl.render(v=4) == "False"
def test_namespace_macro(self, env_trim):
tmpl = env_trim.from_string(
"{% set ns = namespace() %}"
"{% set ns.a = 13 %}"
"{% macro magic(x) %}"
"{% set x.b = 37 %}"
"{% endmacro %}"
"{{ magic(ns) }}"
"{{ ns.a }}|{{ ns.b }}"
)
assert tmpl.render() == "13|37"
def test_namespace_set_tuple(self, env_trim):
tmpl = env_trim.from_string(
"{% set ns = namespace(a=12, b=36) %}"
"{% set ns.a, ns.b = ns.a + 1, ns.b + 1 %}"
"{{ ns.a }}|{{ ns.b }}"
)
assert tmpl.render() == "13|37"
def test_block_escaping_filtered(self):
env = Environment(autoescape=True)
tmpl = env.from_string(
"{% set foo | trim %}{{ test }} {% endset %}foo: {{ foo }}"
)
assert tmpl.render(test="") == "foo: <unsafe>"
def test_block_filtered(self, env_trim):
tmpl = env_trim.from_string(
"{% set foo | trim | length | string %} 42 {% endset %}{{ foo }}"
)
assert tmpl.render() == "2"
assert tmpl.module.foo == "2"
def test_block_filtered_set(self, env_trim):
def _myfilter(val, arg):
assert arg == " xxx "
return val
env_trim.filters["myfilter"] = _myfilter
tmpl = env_trim.from_string(
'{% set a = " xxx " %}'
"{% set foo | myfilter(a) | trim | length | string %}"
' {% set b = " yy " %} 42 {{ a }}{{ b }} '
"{% endset %}"
"{{ foo }}"
)
assert tmpl.render() == "11"
assert tmpl.module.foo == "11"
class TestWith:
def test_with(self, env):
tmpl = env.from_string(
"""\
{% with a=42, b=23 -%}
{{ a }} = {{ b }}
{% endwith -%}
{{ a }} = {{ b }}\
"""
)
assert [x.strip() for x in tmpl.render(a=1, b=2).splitlines()] == [
"42 = 23",
"1 = 2",
]
def test_with_argument_scoping(self, env):
tmpl = env.from_string(
"""\
{%- with a=1, b=2, c=b, d=e, e=5 -%}
{{ a }}|{{ b }}|{{ c }}|{{ d }}|{{ e }}
{%- endwith -%}
"""
)
assert tmpl.render(b=3, e=4) == "1|2|3|4|5"
'use strict'
var assert = require('node:assert')
var AsyncLocalStorage = require('node:async_hooks').AsyncLocalStorage
const { Buffer } = require('node:buffer');
var express = require('..')
var request = require('supertest')
describe('express.urlencoded()', function () {
before(function () {
this.app = createApp()
})
it('should parse x-www-form-urlencoded', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send('user=tobi')
.expect(200, '{"user":"tobi"}', done)
})
it('should 400 when invalid content-length', function (done) {
var app = express()
app.use(function (req, res, next) {
req.headers['content-length'] = '20' // bad length
next()
})
app.use(express.urlencoded())
app.post('/', function (req, res) {
res.json(req.body)
})
request(app)
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send('str=')
.expect(400, /content length/, done)
})
it('should handle Content-Length: 0', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.set('Content-Length', '0')
.send('')
.expect(200, '{}', done)
})
it('should handle empty message-body', function (done) {
request(createApp({ limit: '1kb' }))
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.set('Transfer-Encoding', 'chunked')
.send('')
.expect(200, '{}', done)
})
it('should handle duplicated middleware', function (done) {
var app = express()
app.use(express.urlencoded())
app.use(express.urlencoded())
app.post('/', function (req, res) {
res.json(req.body)
})
request(app)
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send('user=tobi')
.expect(200, '{"user":"tobi"}', done)
})
it('should not parse extended syntax', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send('user[name][first]=Tobi')
.expect(200, '{"user[name][first]":"Tobi"}', done)
})
describe('with extended option', function () {
describe('when false', function () {
before(function () {
this.app = createApp({ extended: false })
})
it('should not parse extended syntax', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send('user[name][first]=Tobi')
.expect(200, '{"user[name][first]":"Tobi"}', done)
})
it('should parse multiple key instances', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send('user=Tobi&user=Loki')
.expect(200, '{"user":["Tobi","Loki"]}', done)
})
})
describe('when true', function () {
before(function () {
this.app = createApp({ extended: true })
})
it('should parse multiple key instances', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send('user=Tobi&user=Loki')
.expect(200, '{"user":["Tobi","Loki"]}', done)
})
it('should parse extended syntax', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send('user[name][first]=Tobi')
.expect(200, '{"user":{"name":{"first":"Tobi"}}}', done)
})
it('should parse parameters with dots', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send('user.name=Tobi')
.expect(200, '{"user.name":"Tobi"}', done)
})
it('should parse fully-encoded extended syntax', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send('user%5Bname%5D%5Bfirst%5D=Tobi')
.expect(200, '{"user":{"name":{"first":"Tobi"}}}', done)
})
it('should parse array index notation', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send('foo[0]=bar&foo[1]=baz')
.expect(200, '{"foo":["bar","baz"]}', done)
})
it('should parse array index notation with large array', function (done) {
var str = 'f[0]=0'
for (var i = 1; i < 500; i++) {
str += '&f[' + i + ']=' + i.toString(16)
}
request(this.app)
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send(str)
.expect(function (res) {
var obj = JSON.parse(res.text)
assert.strictEqual(Object.keys(obj).length, 1)
assert.strictEqual(Array.isArray(obj.f), true)
assert.strictEqual(obj.f.length, 500)
})
.expect(200, done)
})
it('should parse array of objects syntax', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send('foo[0][bar]=baz&foo[0][fizz]=buzz&foo[]=done!')
.expect(200, '{"foo":[{"bar":"baz","fizz":"buzz"},"done!"]}', done)
})
it('should parse deep object', function (done) {
var str = 'foo'
for (var i = 0; i < 32; i++) {
str += '[p]'
}
str += '=bar'
request(this.app)
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send(str)
.expect(function (res) {
var obj = JSON.parse(res.text)
assert.strictEqual(Object.keys(obj).length, 1)
assert.strictEqual(typeof obj.foo, 'object')
var depth = 0
var ref = obj.foo
while ((ref = ref.p)) { depth++ }
assert.strictEqual(depth, 32)
})
.expect(200, done)
})
})
})
describe('with inflate option', function () {
describe('when false', function () {
before(function () {
this.app = createApp({ inflate: false })
})
it('should not accept content-encoding', function (done) {
var test = request(this.app).post('/')
test.set('Content-Encoding', 'gzip')
test.set('Content-Type', 'application/x-www-form-urlencoded')
test.write(Buffer.from('1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', 'hex'))
test.expect(415, '[encoding.unsupported] content encoding unsupported', done)
})
})
describe('when true', function () {
before(function () {
this.app = createApp({ inflate: true })
})
it('should accept content-encoding', function (done) {
var test = request(this.app).post('/')
test.set('Content-Encoding', 'gzip')
test.set('Content-Type', 'application/x-www-form-urlencoded')
test.write(Buffer.from('1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', 'hex'))
test.expect(200, '{"name":"论"}', done)
})
})
})
describe('with limit option', function () {
it('should 413 when over limit with Content-Length', function (done) {
var buf = Buffer.alloc(1024, '.')
request(createApp({ limit: '1kb' }))
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.set('Content-Length', '1028')
.send('str=' + buf.toString())
.expect(413, done)
})
it('should 413 when over limit with chunked encoding', function (done) {
var app = createApp({ limit: '1kb' })
var buf = Buffer.alloc(1024, '.')
var test = request(app).post('/')
test.set('Content-Type', 'application/x-www-form-urlencoded')
test.set('Transfer-Encoding', 'chunked')
test.write('str=')
test.write(buf.toString())
test.expect(413, done)
})
it('should 413 when inflated body over limit', function (done) {
var app = createApp({ limit: '1kb' })
var test = request(app).post('/')
test.set('Content-Encoding', 'gzip')
test.set('Content-Type', 'application/x-www-form-urlencoded')
test.write(Buffer.from('1f8b080000000000000a2b2e29b2d51b05a360148c580000a0351f9204040000', 'hex'))
test.expect(413, done)
})
it('should accept number of bytes', function (done) {
var buf = Buffer.alloc(1024, '.')
request(createApp({ limit: 1024 }))
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send('str=' + buf.toString())
.expect(413, done)
})
it('should not change when options altered', function (done) {
var buf = Buffer.alloc(1024, '.')
var options = { limit: '1kb' }
var app = createApp(options)
options.limit = '100kb'
request(app)
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send('str=' + buf.toString())
.expect(413, done)
})
it('should not hang response', function (done) {
var app = createApp({ limit: '8kb' })
var buf = Buffer.alloc(10240, '.')
var test = request(app).post('/')
test.set('Content-Type', 'application/x-www-form-urlencoded')
test.write(buf)
test.write(buf)
test.write(buf)
test.expect(413, done)
})
it('should not error when inflating', function (done) {
var app = createApp({ limit: '1kb' })
var test = request(app).post('/')
test.set('Content-Encoding', 'gzip')
test.set('Content-Type', 'application/x-www-form-urlencoded')
test.write(Buffer.from('1f8b080000000000000a2b2e29b2d51b05a360148c580000a0351f92040400', 'hex'))
test.expect(413, done)
})
})
describe('with parameterLimit option', function () {
describe('with extended: false', function () {
it('should reject 0', function () {
assert.throws(createApp.bind(null, { extended: false, parameterLimit: 0 }),
/TypeError: option parameterLimit must be a positive number/)
})
it('should reject string', function () {
assert.throws(createApp.bind(null, { extended: false, parameterLimit: 'beep' }),
/TypeError: option parameterLimit must be a positive number/)
})
it('should 413 if over limit', function (done) {
request(createApp({ extended: false, parameterLimit: 10 }))
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send(createManyParams(11))
.expect(413, '[parameters.too.many] too many parameters', done)
})
it('should work when at the limit', function (done) {
request(createApp({ extended: false, parameterLimit: 10 }))
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send(createManyParams(10))
.expect(expectKeyCount(10))
.expect(200, done)
})
it('should work if number is floating point', function (done) {
request(createApp({ extended: false, parameterLimit: 10.1 }))
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send(createManyParams(11))
.expect(413, /too many parameters/, done)
})
it('should work with large limit', function (done) {
request(createApp({ extended: false, parameterLimit: 5000 }))
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send(createManyParams(5000))
.expect(expectKeyCount(5000))
.expect(200, done)
})
it('should work with Infinity limit', function (done) {
request(createApp({ extended: false, parameterLimit: Infinity }))
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send(createManyParams(10000))
.expect(expectKeyCount(10000))
.expect(200, done)
})
})
describe('with extended: true', function () {
it('should reject 0', function () {
assert.throws(createApp.bind(null, { extended: true, parameterLimit: 0 }),
/TypeError: option parameterLimit must be a positive number/)
})
it('should reject string', function () {
assert.throws(createApp.bind(null, { extended: true, parameterLimit: 'beep' }),
/TypeError: option parameterLimit must be a positive number/)
})
it('should 413 if over limit', function (done) {
request(createApp({ extended: true, parameterLimit: 10 }))
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send(createManyParams(11))
.expect(413, '[parameters.too.many] too many parameters', done)
})
it('should work when at the limit', function (done) {
request(createApp({ extended: true, parameterLimit: 10 }))
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send(createManyParams(10))
.expect(expectKeyCount(10))
.expect(200, done)
})
it('should work if number is floating point', function (done) {
request(createApp({ extended: true, parameterLimit: 10.1 }))
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send(createManyParams(11))
.expect(413, /too many parameters/, done)
})
it('should work with large limit', function (done) {
request(createApp({ extended: true, parameterLimit: 5000 }))
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send(createManyParams(5000))
.expect(expectKeyCount(5000))
.expect(200, done)
})
it('should work with Infinity limit', function (done) {
request(createApp({ extended: true, parameterLimit: Infinity }))
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send(createManyParams(10000))
.expect(expectKeyCount(10000))
.expect(200, done)
})
})
})
describe('with type option', function () {
describe('when "application/vnd.x-www-form-urlencoded"', function () {
before(function () {
this.app = createApp({ type: 'application/vnd.x-www-form-urlencoded' })
})
it('should parse for custom type', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/vnd.x-www-form-urlencoded')
.send('user=tobi')
.expect(200, '{"user":"tobi"}', done)
})
it('should ignore standard type', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send('user=tobi')
.expect(200, '', done)
})
})
describe('when ["urlencoded", "application/x-pairs"]', function () {
before(function () {
this.app = createApp({
type: ['urlencoded', 'application/x-pairs']
})
})
it('should parse "application/x-www-form-urlencoded"', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send('user=tobi')
.expect(200, '{"user":"tobi"}', done)
})
it('should parse "application/x-pairs"', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/x-pairs')
.send('user=tobi')
.expect(200, '{"user":"tobi"}', done)
})
it('should ignore application/x-foo', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/x-foo')
.send('user=tobi')
.expect(200, '', done)
})
})
describe('when a function', function () {
it('should parse when truthy value returned', function (done) {
var app = createApp({ type: accept })
function accept (req) {
return req.headers['content-type'] === 'application/vnd.something'
}
request(app)
.post('/')
.set('Content-Type', 'application/vnd.something')
.send('user=tobi')
.expect(200, '{"user":"tobi"}', done)
})
it('should work without content-type', function (done) {
var app = createApp({ type: accept })
function accept (req) {
return true
}
var test = request(app).post('/')
test.write('user=tobi')
test.expect(200, '{"user":"tobi"}', done)
})
it('should not invoke without a body', function (done) {
var app = createApp({ type: accept })
function accept (req) {
throw new Error('oops!')
}
request(app)
.get('/')
.expect(404, done)
})
})
})
describe('with verify option', function () {
it('should assert value if function', function () {
assert.throws(createApp.bind(null, { verify: 'lol' }),
/TypeError: option verify must be function/)
})
it('should error from verify', function (done) {
var app = createApp({
verify: function (req, res, buf) {
if (buf[0] === 0x20) throw new Error('no leading space')
}
})
request(app)
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send(' user=tobi')
.expect(403, '[entity.verify.failed] no leading space', done)
})
it('should allow custom codes', function (done) {
var app = createApp({
verify: function (req, res, buf) {
if (buf[0] !== 0x20) return
var err = new Error('no leading space')
err.status = 400
throw err
}
})
request(app)
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send(' user=tobi')
.expect(400, '[entity.verify.failed] no leading space', done)
})
it('should allow custom type', function (done) {
var app = createApp({
verify: function (req, res, buf) {
if (buf[0] !== 0x20) return
var err = new Error('no leading space')
err.type = 'foo.bar'
throw err
}
})
request(app)
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send(' user=tobi')
.expect(403, '[foo.bar] no leading space', done)
})
it('should allow pass-through', function (done) {
var app = createApp({
verify: function (req, res, buf) {
if (buf[0] === 0x5b) throw new Error('no arrays')
}
})
request(app)
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send('user=tobi')
.expect(200, '{"user":"tobi"}', done)
})
it('should 415 on unknown charset prior to verify', function (done) {
var app = createApp({
verify: function (req, res, buf) {
throw new Error('unexpected verify call')
}
})
var test = request(app).post('/')
test.set('Content-Type', 'application/x-www-form-urlencoded; charset=x-bogus')
test.write(Buffer.from('00000000', 'hex'))
test.expect(415, '[charset.unsupported] unsupported charset "X-BOGUS"', done)
})
})
describe('async local storage', function () {
before(function () {
var app = express()
var store = { foo: 'bar' }
app.use(function (req, res, next) {
req.asyncLocalStorage = new AsyncLocalStorage()
req.asyncLocalStorage.run(store, next)
})
app.use(express.urlencoded())
app.use(function (req, res, next) {
var local = req.asyncLocalStorage.getStore()
if (local) {
res.setHeader('x-store-foo', String(local.foo))
}
next()
})
app.use(function (err, req, res, next) {
var local = req.asyncLocalStorage.getStore()
if (local) {
res.setHeader('x-store-foo', String(local.foo))
}
res.status(err.status || 500)
res.send('[' + err.type + '] ' + err.message)
})
app.post('/', function (req, res) {
res.json(req.body)
})
this.app = app
})
it('should persist store', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send('user=tobi')
.expect(200)
.expect('x-store-foo', 'bar')
.expect('{"user":"tobi"}')
.end(done)
})
it('should persist store when unmatched content-type', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/fizzbuzz')
.send('buzz')
.expect(200)
.expect('x-store-foo', 'bar')
.end(done)
})
it('should persist store when inflated', function (done) {
var test = request(this.app).post('/')
test.set('Content-Encoding', 'gzip')
test.set('Content-Type', 'application/x-www-form-urlencoded')
test.write(Buffer.from('1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', 'hex'))
test.expect(200)
test.expect('x-store-foo', 'bar')
test.expect('{"name":"论"}')
test.end(done)
})
it('should persist store when inflate error', function (done) {
var test = request(this.app).post('/')
test.set('Content-Encoding', 'gzip')
test.set('Content-Type', 'application/x-www-form-urlencoded')
test.write(Buffer.from('1f8b080000000000000bcb4bcc4db57db16e170099a4bad6080000', 'hex'))
test.expect(400)
test.expect('x-store-foo', 'bar')
test.end(done)
})
it('should persist store when limit exceeded', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send('user=' + Buffer.alloc(1024 * 100, '.').toString())
.expect(413)
.expect('x-store-foo', 'bar')
.end(done)
})
})
describe('charset', function () {
before(function () {
this.app = createApp()
})
it('should parse utf-8', function (done) {
var test = request(this.app).post('/')
test.set('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8')
test.write(Buffer.from('6e616d653de8aeba', 'hex'))
test.expect(200, '{"name":"论"}', done)
})
it('should parse when content-length != char length', function (done) {
var test = request(this.app).post('/')
test.set('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8')
test.set('Content-Length', '7')
test.write(Buffer.from('746573743dc3a5', 'hex'))
test.expect(200, '{"test":"å"}', done)
})
it('should default to utf-8', function (done) {
var test = request(this.app).post('/')
test.set('Content-Type', 'application/x-www-form-urlencoded')
test.write(Buffer.from('6e616d653de8aeba', 'hex'))
test.expect(200, '{"name":"论"}', done)
})
it('should fail on unknown charset', function (done) {
var test = request(this.app).post('/')
test.set('Content-Type', 'application/x-www-form-urlencoded; charset=koi8-r')
test.write(Buffer.from('6e616d653dcec5d4', 'hex'))
test.expect(415, '[charset.unsupported] unsupported charset "KOI8-R"', done)
})
})
describe('encoding', function () {
before(function () {
this.app = createApp({ limit: '10kb' })
})
it('should parse without encoding', function (done) {
var test = request(this.app).post('/')
test.set('Content-Type', 'application/x-www-form-urlencoded')
test.write(Buffer.from('6e616d653de8aeba', 'hex'))
test.expect(200, '{"name":"论"}', done)
})
it('should support identity encoding', function (done) {
var test = request(this.app).post('/')
test.set('Content-Encoding', 'identity')
test.set('Content-Type', 'application/x-www-form-urlencoded')
test.write(Buffer.from('6e616d653de8aeba', 'hex'))
test.expect(200, '{"name":"论"}', done)
})
it('should support gzip encoding', function (done) {
var test = request(this.app).post('/')
test.set('Content-Encoding', 'gzip')
test.set('Content-Type', 'application/x-www-form-urlencoded')
test.write(Buffer.from('1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', 'hex'))
test.expect(200, '{"name":"论"}', done)
})
it('should support deflate encoding', function (done) {
var test = request(this.app).post('/')
test.set('Content-Encoding', 'deflate')
test.set('Content-Type', 'application/x-www-form-urlencoded')
test.write(Buffer.from('789ccb4bcc4db57db16e17001068042f', 'hex'))
test.expect(200, '{"name":"论"}', done)
})
it('should be case-insensitive', function (done) {
var test = request(this.app).post('/')
test.set('Content-Encoding', 'GZIP')
test.set('Content-Type', 'application/x-www-form-urlencoded')
test.write(Buffer.from('1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', 'hex'))
test.expect(200, '{"name":"论"}', done)
})
it('should 415 on unknown encoding', function (done) {
var test = request(this.app).post('/')
test.set('Content-Encoding', 'nulls')
test.set('Content-Type', 'application/x-www-form-urlencoded')
test.write(Buffer.from('000000000000', 'hex'))
test.expect(415, '[encoding.unsupported] unsupported content encoding "nulls"', done)
})
})
})
function createManyParams (count) {
var str = ''
if (count === 0) {
return str
}
str += '0=0'
for (var i = 1; i < count; i++) {
var n = i.toString(36)
str += '&' + n + '=' + n
}
return str
}
function createApp (options) {
var app = express()
app.use(express.urlencoded(options))
app.use(function (err, req, res, next) {
res.status(err.status || 500)
res.send(String(req.headers['x-error-property']
? err[req.headers['x-error-property']]
: ('[' + err.type + '] ' + err.message)))
})
app.post('/', function (req, res) {
res.json(req.body)
})
return app
}
function expectKeyCount (count) {
return function (res) {
assert.strictEqual(Object.keys(JSON.parse(res.text)).length, count)
}
}
import re
from jinja2.exceptions import TemplateSyntaxError
from jinja2.ext import Extension
from jinja2.lexer import count_newlines
from jinja2.lexer import Token
_outside_re = re.compile(r"\\?(gettext|_)\(")
_inside_re = re.compile(r"\\?[()]")
class InlineGettext(Extension):
"""This extension implements support for inline gettext blocks::
_(Welcome)
_(This is a paragraph)
Requires the i18n extension to be loaded and configured.
"""
def filter_stream(self, stream):
paren_stack = 0
for token in stream:
if token.type != "data":
yield token
continue
pos = 0
lineno = token.lineno
while True:
if not paren_stack:
match = _outside_re.search(token.value, pos)
else:
match = _inside_re.search(token.value, pos)
if match is None:
break
new_pos = match.start()
if new_pos > pos:
preval = token.value[pos:new_pos]
yield Token(lineno, "data", preval)
lineno += count_newlines(preval)
gtok = match.group()
if gtok[0] == "\\":
yield Token(lineno, "data", gtok[1:])
elif not paren_stack:
yield Token(lineno, "block_begin", None)
yield Token(lineno, "name", "trans")
yield Token(lineno, "block_end", None)
paren_stack = 1
else:
if gtok == "(" or paren_stack > 1:
yield Token(lineno, "data", gtok)
paren_stack += -1 if gtok == ")" else 1
if not paren_stack:
yield Token(lineno, "block_begin", None)
yield Token(lineno, "name", "endtrans")
yield Token(lineno, "block_end", None)
pos = match.end()
if pos < len(token.value):
yield Token(lineno, "data", token.value[pos:])
if paren_stack:
raise TemplateSyntaxError(
"unclosed gettext expression",
token.lineno,
stream.name,
stream.filename,
)
lodash-fp Test Suite
import click
def test_filename_formatting():
assert click.format_filename(b"foo.txt") == "foo.txt"
assert click.format_filename(b"/x/foo.txt") == "/x/foo.txt"
assert click.format_filename("/x/foo.txt") == "/x/foo.txt"
assert click.format_filename("/x/foo.txt", shorten=True) == "foo.txt"
assert click.format_filename("/x/\ufffd.txt", shorten=True) == "�.txt"
name: Package Manager Builds
on: [push, pull_request]
jobs:
conan_builds:
name: Conan ${{matrix.conan_version}}
runs-on: ubuntu-22.04
strategy:
matrix:
conan_version:
- '1.63'
- '2.1'
include:
# Conan 1 has default profiles installed
- conan_version: '1.63'
profile_generate: 'false'
steps:
- uses: actions/checkout@v6
- name: Install conan
run: pip install conan==${{matrix.conan_version}}
- name: Setup conan profiles
if: matrix.profile_generate != 'false'
run: conan profile detect
- name: Run conan package create
run: conan create . -tf .conan/test_package
coverage:
precision: 2
round: nearest
range: "60...90"
status:
project:
default:
threshold: 2%
patch:
default:
target: 80%
ignore:
- "**/external/clara.hpp"
- "tests"
codecov:
branch: devel
max_report_age: off
comment:
layout: "diff"
'use strict'
var assert = require('node:assert')
var express = require('../');
var request = require('supertest');
describe('middleware', function(){
describe('.next()', function(){
it('should behave like connect', function(done){
var app = express()
, calls = [];
app.use(function(req, res, next){
calls.push('one');
next();
});
app.use(function(req, res, next){
calls.push('two');
next();
});
app.use(function(req, res){
var buf = '';
res.setHeader('Content-Type', 'application/json');
req.setEncoding('utf8');
req.on('data', function(chunk){ buf += chunk });
req.on('end', function(){
res.end(buf);
});
});
request(app)
.get('/')
.set('Content-Type', 'application/json')
.send('{"foo":"bar"}')
.expect('Content-Type', 'application/json')
.expect(function () { assert.deepEqual(calls, ['one', 'two']) })
.expect(200, '{"foo":"bar"}', done)
})
})
})
# Reporter events
**Contents**
[Test running events](#test-running-events)
[Benchmarking events](#benchmarking-events)
[Listings events](#listings-events)
[Miscellaneous events](#miscellaneous-events)
Reporter events are one of the customization points for user code. They
are used by [reporters](reporters.md#top) to customize Catch2's output,
and by [event listeners](event-listeners.md#top) to perform in-process
actions under some conditions.
There are currently 21 reporter events in Catch2, split between 4 distinct
event groups:
* test running events (10 events)
* benchmarking (4 events)
* listings (3 events)
* miscellaneous (4 events)
## Test running events
Test running events are always paired so that for each `fooStarting` event,
there is a `fooEnded` event. This means that the 10 test running events
consist of 5 pairs of events:
* `testRunStarting` and `testRunEnded`,
* `testCaseStarting` and `testCaseEnded`,
* `testCasePartialStarting` and `testCasePartialEnded`,
* `sectionStarting` and `sectionEnded`,
* `assertionStarting` and `assertionEnded`
### `testRun` events
```cpp
void testRunStarting( TestRunInfo const& testRunInfo );
void testRunEnded( TestRunStats const& testRunStats );
```
The `testRun` events bookend the entire test run. `testRunStarting` is
emitted before the first test case is executed, and `testRunEnded` is
emitted after all the test cases have been executed.
### `testCase` events
```cpp
void testCaseStarting( TestCaseInfo const& testInfo );
void testCaseEnded( TestCaseStats const& testCaseStats );
```
The `testCase` events bookend one _full_ run of a specific test case.
Individual runs through a test case, e.g. due to `SECTION`s or `GENERATE`s,
are handled by a different event.
### `testCasePartial` events
> Introduced in Catch2 3.0.1
```cpp
void testCasePartialStarting( TestCaseInfo const& testInfo, uint64_t partNumber );
void testCasePartialEnded(TestCaseStats const& testCaseStats, uint64_t partNumber );
```
`testCasePartial` events bookend one _partial_ run of a specific test case.
This means that for any given test case, these events can be emitted
multiple times, e.g. due to multiple leaf sections.
In regards to nesting with `testCase` events, `testCasePartialStarting`
will never be emitted before the corresponding `testCaseStarting`, and
`testCasePartialEnded` will always be emitted before the corresponding
`testCaseEnded`.
### `section` events
```cpp
void sectionStarting( SectionInfo const& sectionInfo );
void sectionEnded( SectionStats const& sectionStats );
```
`section` events are emitted only for active `SECTION`s, that is, sections
that are entered. Sections that are skipped in this test case run-through
do not cause events to be emitted.
_Note that test cases always contain one implicit section. The event for
this section is emitted after the corresponding `testCasePartialStarting`
event._
### `assertion` events
```cpp
void assertionStarting( AssertionInfo const& assertionInfo );
void assertionEnded( AssertionStats const& assertionStats );
```
The `assertionStarting` event is emitted before the expression in the
assertion is captured or evaluated and `assertionEnded` is emitted
afterwards. This means that given assertion like `REQUIRE(a + b == c + d)`,
Catch2 first emits `assertionStarting` event, then `a + b` and `c + d`
are evaluated, then their results are captured, the comparison is evaluated,
and then `assertionEnded` event is emitted.
## Benchmarking events
> [Introduced](https://github.com/catchorg/Catch2/issues/1616) in Catch2 2.9.0.
```cpp
void benchmarkPreparing( StringRef name ) override;
void benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) override;
void benchmarkEnded( BenchmarkStats<> const& benchmarkStats ) override;
void benchmarkFailed( StringRef error ) override;
```
Due to the benchmark lifecycle being bit more complicated, the benchmarking
events have their own category, even though they could be seen as parallel
to the `assertion*` events. You should expect running a benchmark to
generate at least 2 of the events above.
To understand the explanation below, you should read the [benchmarking
documentation](benchmarks.md#top) first.
* `benchmarkPreparing` event is sent after the environmental probe
finishes, but before the user code is first estimated.
* `benchmarkStarting` event is sent after the user code is estimated,
but has not been benchmarked yet.
* `benchmarkEnded` event is sent after the user code has been benchmarked,
and contains the benchmarking results.
* `benchmarkFailed` event is sent if either the estimation or the
benchmarking itself fails.
## Listings events
> Introduced in Catch2 3.0.1.
Listings events are events that correspond to the test binary being
invoked with `--list-foo` flag.
There are currently 3 listing events, one for reporters, one for tests,
and one for tags. Note that they are not exclusive to each other.
```cpp
void listReporters( std::vector const& descriptions );
void listTests( std::vector const& tests );
void listTags( std::vector const& tagInfos );
```
## Miscellaneous events
```cpp
void reportInvalidTestSpec( StringRef unmatchedSpec );
void fatalErrorEncountered( StringRef error );
void noMatchingTestCases( StringRef unmatchedSpec );
```
These are one-off events that do not neatly fit into other categories.
`reportInvalidTestSpec` is sent for each [test specification command line
argument](command-line.md#specifying-which-tests-to-run) that wasn't
parsed into a valid spec.
`fatalErrorEncountered` is sent when Catch2's POSIX signal handling
or Windows SE handler is called into with a fatal signal/exception.
`noMatchingTestCases` is sent for each user provided test specification
that did not match any registered tests.
---
[Home](Readme.md#top)
'use strict'
var express = require('../')
, request = require('supertest');
describe('req', function(){
describe('.path', function(){
it('should return the parsed pathname', function(done){
var app = express();
app.use(function(req, res){
res.end(req.path);
});
request(app)
.get('/login?redirect=/post/1/comments')
.expect('/login', done);
})
})
})
# Open Source projects using Catch2
Catch2 is great for open source. It is licensed under the [Boost Software
License (BSL)](../LICENSE.txt), has no further dependencies and supports
two file distribution.
As a result, Catch2 is used for testing in many different Open Source
projects. This page lists at least some of them, even though it will
obviously never be complete (and does not have the ambition to be
complete). Note that the list below is intended to be in alphabetical
order, to avoid implications of relative importance of the projects.
_Please only add projects here if you are their maintainer, or have the
maintainer's explicit consent._
## Libraries & Frameworks
### [accessorpp](https://github.com/wqking/accessorpp)
C++ library for implementing property and data binding.
### [alpaka](https://github.com/alpaka-group/alpaka)
A header-only C++14 abstraction library for accelerator development.
### [ApprovalTests.cpp](https://github.com/approvals/ApprovalTests.cpp)
C++11 implementation of Approval Tests, for quick, convenient testing of legacy code.
### [args](https://github.com/Taywee/args)
A simple header-only C++ argument parser library.
### [Azmq](https://github.com/zeromq/azmq)
Boost Asio style bindings for ZeroMQ.
### [Cataclysm: Dark Days Ahead](https://github.com/CleverRaven/Cataclysm-DDA)
Post-apocalyptic survival RPG.
### [ChaiScript](https://github.com/ChaiScript/ChaiScript)
A, header-only, embedded scripting language designed from the ground up to directly target C++ and take advantage of modern C++ development techniques.
### [ChakraCore](https://github.com/Microsoft/ChakraCore)
The core part of the Chakra JavaScript engine that powers Microsoft Edge.
### [Clara](https://github.com/philsquared/Clara)
A, single-header-only, type-safe, command line parser - which also prints formatted usage strings.
### [Couchbase-lite-core](https://github.com/couchbase/couchbase-lite-core)
The next-generation core storage and query engine for Couchbase Lite.
### [cppcodec](https://github.com/tplgy/cppcodec)
Header-only C++11 library to encode/decode base64, base64url, base32, base32hex and hex (a.k.a. base16) as specified in RFC 4648, plus Crockford's base32.
### [DtCraft](https://github.com/twhuang-uiuc/DtCraft)
A High-performance Cluster Computing Engine.
### [eventpp](https://github.com/wqking/eventpp)
C++ event library for callbacks, event dispatcher, and event queue. With eventpp you can easily implement signal and slot mechanism, publisher and subscriber pattern, or observer pattern.
### [forest](https://github.com/xorz57/forest)
Template Library of Tree Data Structures.
### [Fuxedo](https://github.com/fuxedo/fuxedo)
Open source Oracle Tuxedo-like XATMI middleware for C and C++.
### [HIP CPU Runtime](https://github.com/ROCm-Developer-Tools/HIP-CPU)
A header-only library that allows CPUs to execute unmodified HIP code. It is generic and does not assume a particular CPU vendor or architecture.
### [Inja](https://github.com/pantor/inja)
A header-only template engine for modern C++.
### [LLAMA](https://github.com/alpaka-group/llama)
A C++17 template header-only library for the abstraction of memory access patterns.
### [libcluon](https://github.com/chrberger/libcluon)
A single-header-only library written in C++14 to glue distributed software components (UDP, TCP, shared memory) supporting natively Protobuf, LCM/ZCM, MsgPack, and JSON for dynamic message transformations in-between.
### [MNMLSTC Core](https://github.com/mnmlstc/core)
A small and easy to use C++11 library that adds a functionality set that will be available in C++14 and later, as well as some useful additions.
### [nanodbc](https://github.com/lexicalunit/nanodbc/)
A small C++ library wrapper for the native C ODBC API.
### [Nonius](https://github.com/libnonius/nonius)
A header-only framework for benchmarking small snippets of C++ code.
### [OpenALpp](https://github.com/Laguna1989/OpenALpp)
A modern OOP C++14 audio library built on OpenAL for Windows, Linux and web (emscripten).
### [polymorphic_value](https://github.com/jbcoe/polymorphic_value)
A polymorphic value-type for C++.
### [Ppconsul](https://github.com/oliora/ppconsul)
A C++ client library for Consul. Consul is a distributed tool for discovering and configuring services in your infrastructure.
### [Reactive-Extensions/ RxCpp](https://github.com/Reactive-Extensions/RxCpp)
A library of algorithms for values-distributed-in-time.
### [SFML](https://github.com/SFML/SFML)
Simple and Fast Multimedia Library.
### [SOCI](https://github.com/SOCI/soci)
The C++ Database Access Library.
### [TextFlowCpp](https://github.com/philsquared/textflowcpp)
A small, single-header-only, library for wrapping and composing columns of text.
### [thor](https://github.com/xorz57/thor)
Wrapper Library for CUDA.
### [toml++](https://github.com/marzer/tomlplusplus)
A header-only TOML parser and serializer for modern C++.
### [Trompeloeil](https://github.com/rollbear/trompeloeil)
A thread-safe header-only mocking framework for C++14.
### [wxWidgets](https://www.wxwidgets.org/)
Cross-Platform C++ GUI Library.
### [xmlwrapp](https://github.com/vslavik/xmlwrapp)
C++ XML parsing library using libxml2.
## Applications & Tools
### [App Mesh](https://github.com/laoshanxi/app-mesh)
A high available cloud native micro-service application management platform implemented by modern C++.
### [ArangoDB](https://github.com/arangodb/arangodb)
ArangoDB is a native multi-model database with flexible data models for documents, graphs, and key-values.
### [Cytopia](https://github.com/CytopiaTeam/Cytopia)
Cytopia is a free, open source retro pixel-art city building game with a big focus on mods. It utilizes a custom isometric rendering engine based on SDL2.
### [d-SEAMS](https://github.com/d-SEAMS/seams-core)
Open source molecular dynamics simulation structure analysis suite of tools in modern C++.
### [Giada - Your Hardcore Loop Machine](https://github.com/monocasual/giada)
Minimal, open-source and cross-platform audio tool for live music production.
### [MAME](https://github.com/mamedev/mame)
MAME originally stood for Multiple Arcade Machine Emulator.
### [Newsbeuter](https://github.com/akrennmair/newsbeuter)
Newsbeuter is an open-source RSS/Atom feed reader for text terminals.
### [PopHead](https://github.com/SPC-Some-Polish-Coders/PopHead)
A 2D, Zombie, RPG game which is being made on our own engine.
### [raspigcd](https://github.com/pantadeusz/raspigcd)
Low level CLI app and library for execution of GCODE on Raspberry Pi without any additional microcontrollers (just RPi + Stepsticks).
### [SpECTRE](https://github.com/sxs-collaboration/spectre)
SpECTRE is a code for multi-scale, multi-physics problems in astrophysics and gravitational physics.
### [Standardese](https://github.com/foonathan/standardese)
Standardese aims to be a nextgen Doxygen.
---
[Home](Readme.md#top)
'use strict'
var express = require('../')
, request = require('supertest');
describe('throw after .end()', function(){
it('should fail gracefully', function(done){
var app = express();
app.get('/', function(req, res){
res.end('yay');
throw new Error('boom');
});
request(app)
.get('/')
.expect('yay')
.expect(200, done);
})
})
import {setTimeout as delay} from 'node:timers/promises';
import is, {assert} from '@sindresorhus/is';
import asPromise from './as-promise/index.js';
import type {
GotReturn,
ExtendOptions,
Got,
HTTPAlias,
InstanceDefaults,
GotPaginate,
GotStream,
GotRequestFunction,
OptionsWithPagination,
StreamOptions,
} from './types.js';
import Request from './core/index.js';
import type {Response} from './core/response.js';
import Options, {
applyUrlOverride,
assertUrlHasSameOriginAsPrefixUrlIfNeeded,
getUrlPrefixBoundary,
hasUrlOrPrefixUrlBoundaryChanged,
isSameOrigin,
snapshotCrossOriginState,
type OptionsInit,
} from './core/options.js';
import type {RequestPromise} from './as-promise/types.js';
const isGotInstance = (value: Got | ExtendOptions): value is Got => is.function(value);
const aliases: readonly HTTPAlias[] = [
'get',
'post',
'put',
'patch',
'head',
'delete',
'query',
];
const optionsObjectUrlErrorMessage = 'The `url` option is not supported in options objects. Pass it as the first argument instead.';
const assertNoUrlInOptionsObject = (options: Record): void => {
if (Object.hasOwn(options, 'url')) {
throw new TypeError(optionsObjectUrlErrorMessage);
}
};
const cloneWithProperty = >(value: Value, property: string, propertyValue: unknown): Value => {
const clone = Object.create(Object.getPrototypeOf(value), Object.getOwnPropertyDescriptors(value)) as Value;
Object.defineProperty(clone, property, {
value: propertyValue,
enumerable: true,
configurable: true,
writable: true,
});
return clone;
};
const create = (defaults: InstanceDefaults): Got => {
defaults = {
options: new Options(undefined, undefined, defaults.options),
handlers: [...defaults.handlers],
mutableDefaults: defaults.mutableDefaults,
};
Object.defineProperty(defaults, 'mutableDefaults', {
enumerable: true,
configurable: false,
writable: false,
});
const makeRequest = (url: string | URL | OptionsInit | undefined, options: OptionsInit | undefined, defaultOptions: Options, isStream: boolean): GotReturn => {
if (is.plainObject(url)) {
assertNoUrlInOptionsObject(url);
}
if (is.plainObject(options)) {
assertNoUrlInOptionsObject(options);
}
// `isStream` is skipped by `merge()`, so set it via the direct setter after construction.
// Avoid a synthetic second merge only for the single-options-object stream form.
const requestUrl = isStream && is.plainObject(url) ? cloneWithProperty(url, 'isStream', true) : url;
const requestOptions = isStream && !is.plainObject(url) && options ? cloneWithProperty(options, 'isStream', true) : options;
const request = new Request(requestUrl, requestOptions, defaultOptions);
if (isStream && request.options) {
request.options.isStream = true;
}
let promise: RequestPromise | undefined;
const urlBeforeHandlers = request.options?.url instanceof URL ? new URL(request.options.url) : undefined;
const boundaryBeforeHandlers = request.options ? getUrlPrefixBoundary(request.options) : undefined;
const lastHandler = (normalized: Options): GotReturn => {
if (
urlBeforeHandlers
&& boundaryBeforeHandlers
&& normalized?.url instanceof URL
&& hasUrlOrPrefixUrlBoundaryChanged(normalized, normalized.url, boundaryBeforeHandlers)
) {
assertUrlHasSameOriginAsPrefixUrlIfNeeded(normalized, normalized.url);
}
// Note: `options` is `undefined` when `new Options(...)` fails
request.options = normalized;
const shouldReturnStream = normalized?.isStream ?? isStream;
request._noPipe = !shouldReturnStream;
void request.flush();
if (shouldReturnStream) {
return request;
}
promise ??= asPromise(request);
return promise;
};
let iteration = 0;
const iterateHandlers = (newOptions: Options): GotReturn => {
const handler = defaults.handlers[iteration++] ?? lastHandler;
const result = handler(newOptions, iterateHandlers) as GotReturn;
if (is.promise(result) && !request.options?.isStream) {
promise ??= asPromise(request);
if (result !== promise) {
const descriptors = Object.getOwnPropertyDescriptors(promise);
for (const key in descriptors) {
if (key in result) {
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete
delete descriptors[key];
}
}
// eslint-disable-next-line @typescript-eslint/no-floating-promises
Object.defineProperties(result, descriptors);
}
}
return result;
};
return iterateHandlers(request.options);
};
// Got interface
const got: Got = ((url: string | URL | OptionsInit | undefined, options?: OptionsInit, defaultOptions: Options = defaults.options): GotReturn =>
makeRequest(url, options, defaultOptions, false)) as Got;
got.extend = (...instancesOrOptions) => {
const options = new Options(undefined, undefined, defaults.options);
const handlers = [...defaults.handlers];
let mutableDefaults: boolean | undefined;
for (const value of instancesOrOptions) {
if (isGotInstance(value)) {
options.merge(value.defaults.options);
handlers.push(...value.defaults.handlers);
mutableDefaults = value.defaults.mutableDefaults;
} else {
assertNoUrlInOptionsObject(value);
options.merge(value);
if (value.handlers) {
handlers.push(...value.handlers);
}
mutableDefaults = value.mutableDefaults;
}
}
return create({
options,
handlers,
mutableDefaults: Boolean(mutableDefaults),
});
};
// Pagination
const paginateEach = (async function * (url: string | URL, options?: OptionsWithPagination): AsyncIterableIterator {
if (is.plainObject(url)) {
assertNoUrlInOptionsObject(url);
}
if (is.plainObject(options)) {
assertNoUrlInOptionsObject(options);
}
let normalizedOptions = new Options(url, options as OptionsInit, defaults.options);
normalizedOptions.resolveBodyOnly = false;
const {pagination} = normalizedOptions;
assert.function(pagination.transform);
assert.function(pagination.shouldContinue);
assert.function(pagination.filter);
assert.function(pagination.paginate);
assert.number(pagination.countLimit);
assert.number(pagination.requestLimit);
assert.number(pagination.backoff);
const allItems: T[] = [];
let {countLimit} = pagination;
let numberOfRequests = 0;
while (numberOfRequests < pagination.requestLimit) {
if (numberOfRequests !== 0) {
// eslint-disable-next-line no-await-in-loop
await delay(pagination.backoff);
}
// eslint-disable-next-line no-await-in-loop
const response = (await got(undefined, undefined, normalizedOptions)) as Response;
// eslint-disable-next-line no-await-in-loop
const parsed: unknown[] = await pagination.transform(response);
const currentItems: T[] = [];
assert.array(parsed);
for (const item of parsed) {
if (pagination.filter({item, currentItems, allItems})) {
if (!pagination.shouldContinue({item, currentItems, allItems})) {
return;
}
yield item as T;
if (pagination.stackAllItems) {
allItems.push(item as T);
}
currentItems.push(item as T);
if (--countLimit <= 0) {
return;
}
}
}
const requestOptions = response.request.options;
const previousUrl = requestOptions.url ? new URL(requestOptions.url) : undefined;
const previousBoundary = getUrlPrefixBoundary(requestOptions);
const previousState = previousUrl ? snapshotCrossOriginState(requestOptions) : undefined;
// eslint-disable-next-line no-await-in-loop
const [optionsToMerge, changedState] = await requestOptions.trackStateMutations(async changedState => [
pagination.paginate!({
response,
currentItems,
allItems,
}),
changedState,
] as const);
if (optionsToMerge === false) {
return;
}
if (optionsToMerge === response.request.options) {
normalizedOptions = response.request.options;
normalizedOptions.clearUnchangedCookieHeader(previousState, changedState);
if (previousUrl) {
const nextUrl = normalizedOptions.url as URL | undefined;
if (
nextUrl
&& hasUrlOrPrefixUrlBoundaryChanged(normalizedOptions, nextUrl, previousBoundary)
) {
assertUrlHasSameOriginAsPrefixUrlIfNeeded(normalizedOptions, nextUrl);
}
if (nextUrl && !isSameOrigin(previousUrl, nextUrl)) {
normalizedOptions.prefixUrl = '';
normalizedOptions.stripUnchangedCrossOriginState(previousState!, changedState);
}
}
} else {
const paginationOptions = normalizedOptions;
const paginationUrl = paginationOptions.url instanceof URL ? new URL(paginationOptions.url) : undefined;
const paginationBoundary = getUrlPrefixBoundary(paginationOptions);
const hasExplicitBody = (Object.hasOwn(optionsToMerge, 'body') && optionsToMerge.body !== undefined)
|| (Object.hasOwn(optionsToMerge, 'json') && optionsToMerge.json !== undefined)
|| (Object.hasOwn(optionsToMerge, 'form') && optionsToMerge.form !== undefined);
const clearsCookieJar = Object.hasOwn(optionsToMerge, 'cookieJar') && optionsToMerge.cookieJar === undefined;
if (hasExplicitBody) {
paginationOptions.clearBody();
}
if (clearsCookieJar) {
paginationOptions.cookieJar = undefined;
}
const {url, ...optionsToMergeWithoutUrl} = optionsToMerge;
paginationOptions.merge(optionsToMergeWithoutUrl);
paginationOptions.syncCookieHeaderAfterMerge(previousState, optionsToMergeWithoutUrl.headers);
if (
paginationOptions.url instanceof URL
&& hasUrlOrPrefixUrlBoundaryChanged(paginationOptions, paginationOptions.url, paginationBoundary)
) {
assertUrlHasSameOriginAsPrefixUrlIfNeeded(paginationOptions, paginationOptions.url);
}
if (
url === undefined
&& previousUrl
&& paginationOptions.url instanceof URL
&& !isSameOrigin(previousUrl, paginationOptions.url)
) {
paginationOptions.stripSensitiveHeaders(previousUrl, paginationOptions.url, optionsToMerge);
if (!hasExplicitBody) {
paginationOptions.clearBody();
}
}
if (
previousUrl
&& paginationUrl
&& !isSameOrigin(paginationUrl, previousUrl)
) {
paginationOptions.stripSensitiveHeaders(paginationUrl, previousUrl, optionsToMerge);
if (!hasExplicitBody) {
paginationOptions.clearBody();
}
}
try {
assert.any([is.string, is.urlInstance, is.undefined], optionsToMerge.url);
} catch (error) {
if (error instanceof Error) {
error.message = `Option 'pagination.paginate.url': ${error.message}`;
}
throw error;
}
if (url !== undefined) {
const nextUrl = applyUrlOverride(paginationOptions, url, {
...optionsToMerge,
baseUrl: previousUrl,
});
if (
paginationOptions.prefixUrl.toString() !== paginationBoundary.prefixUrl
|| paginationOptions.allowAbsoluteUrls !== paginationBoundary.allowAbsoluteUrls
) {
assertUrlHasSameOriginAsPrefixUrlIfNeeded(paginationOptions, nextUrl);
}
if (previousUrl) {
paginationOptions.stripSensitiveHeaders(previousUrl, nextUrl, optionsToMerge);
if (!isSameOrigin(previousUrl, nextUrl) && !hasExplicitBody) {
paginationOptions.clearBody();
}
}
}
normalizedOptions = paginationOptions;
}
numberOfRequests++;
}
});
got.paginate = paginateEach as GotPaginate;
got.paginate.all = (async (url: string | URL, options?: OptionsWithPagination) => Array.fromAsync(paginateEach(url, options))) as GotPaginate['all'];
// For those who like very descriptive names
got.paginate.each = paginateEach as GotPaginate['each'];
// Stream API
got.stream = ((url: string | URL, options?: StreamOptions) =>
makeRequest(url, options, defaults.options, true)) as GotStream;
// Shortcuts
for (const method of aliases) {
got[method] = ((url: string | URL, options?: Options): GotReturn => got(url, {...options, method})) as GotRequestFunction;
got.stream[method] = ((url: string | URL, options?: StreamOptions) =>
makeRequest(url, {...options, method}, defaults.options, true)) as GotStream;
}
if (!defaults.mutableDefaults) {
Object.freeze(defaults.handlers);
defaults.options.freeze();
}
Object.defineProperty(got, 'defaults', {
value: defaults,
writable: false,
configurable: false,
enumerable: true,
});
return got;
};
export default create;
from __future__ import annotations
from typing_extensions import assert_type
from click import progressbar
from click._termui_impl import ProgressBar
def test_length_is_int() -> None:
with progressbar(length=5) as bar:
assert_type(bar, ProgressBar[int])
for i in bar:
assert_type(i, int)
def it() -> tuple[str, ...]:
return ("hello", "world")
def test_generic_on_iterable() -> None:
with progressbar(it()) as bar:
assert_type(bar, ProgressBar[str])
for s in bar:
assert_type(s, str)
import pytest
import click
@pytest.mark.parametrize(
("value", "max_length", "expect"),
[
pytest.param("", 10, "", id="empty"),
pytest.param("123 567 90", 10, "123 567 90", id="equal length, no dot"),
pytest.param("123 567 9. aaaa bbb", 10, "123 567 9.", id="sentence < max"),
pytest.param("123 567\n\n 9. aaaa bbb", 10, "123 567", id="paragraph < max"),
pytest.param("123 567 90123.", 10, "123 567...", id="truncate"),
pytest.param("123 5678 xxxxxx", 10, "123...", id="length includes suffix"),
pytest.param(
"token in ~/.netrc ciao ciao",
20,
"token in ~/.netrc...",
id="ignore dot in word",
),
],
)
@pytest.mark.parametrize(
"alter",
[
pytest.param(None, id=""),
pytest.param(
lambda text: "\n\b\n" + " ".join(text.split(" ")) + "\n", id="no-wrap mark"
),
],
)
def test_make_default_short_help(value, max_length, alter, expect):
assert len(expect) <= max_length
if alter:
value = alter(value)
out = click.utils._make_default_short_help(value, max_length)
assert out == expect
/** Used to map aliases to their real names. */
exports.aliasToReal = {
// Lodash aliases.
'each': 'forEach',
'eachRight': 'forEachRight',
'entries': 'toPairs',
'entriesIn': 'toPairsIn',
'extend': 'assignIn',
'extendAll': 'assignInAll',
'extendAllWith': 'assignInAllWith',
'extendWith': 'assignInWith',
'first': 'head',
// Methods that are curried variants of others.
'conforms': 'conformsTo',
'matches': 'isMatch',
'property': 'get',
// Ramda aliases.
'__': 'placeholder',
'F': 'stubFalse',
'T': 'stubTrue',
'all': 'every',
'allPass': 'overEvery',
'always': 'constant',
'any': 'some',
'anyPass': 'overSome',
'apply': 'spread',
'assoc': 'set',
'assocPath': 'set',
'complement': 'negate',
'compose': 'flowRight',
'contains': 'includes',
'dissoc': 'unset',
'dissocPath': 'unset',
'dropLast': 'dropRight',
'dropLastWhile': 'dropRightWhile',
'equals': 'isEqual',
'identical': 'eq',
'indexBy': 'keyBy',
'init': 'initial',
'invertObj': 'invert',
'juxt': 'over',
'omitAll': 'omit',
'nAry': 'ary',
'path': 'get',
'pathEq': 'matchesProperty',
'pathOr': 'getOr',
'paths': 'at',
'pickAll': 'pick',
'pipe': 'flow',
'pluck': 'map',
'prop': 'get',
'propEq': 'matchesProperty',
'propOr': 'getOr',
'props': 'at',
'symmetricDifference': 'xor',
'symmetricDifferenceBy': 'xorBy',
'symmetricDifferenceWith': 'xorWith',
'takeLast': 'takeRight',
'takeLastWhile': 'takeRightWhile',
'unapply': 'rest',
'unnest': 'flatten',
'useWith': 'overArgs',
'where': 'conformsTo',
'whereEq': 'isMatch',
'zipObj': 'zipObject'
};
/** Used to map ary to method names. */
exports.aryMethod = {
'1': [
'assignAll', 'assignInAll', 'attempt', 'castArray', 'ceil', 'create',
'curry', 'curryRight', 'defaultsAll', 'defaultsDeepAll', 'floor', 'flow',
'flowRight', 'fromPairs', 'invert', 'iteratee', 'memoize', 'method', 'mergeAll',
'methodOf', 'mixin', 'nthArg', 'over', 'overEvery', 'overSome','rest', 'reverse',
'round', 'runInContext', 'spread', 'template', 'trim', 'trimEnd', 'trimStart',
'uniqueId', 'words', 'zipAll'
],
'2': [
'add', 'after', 'ary', 'assign', 'assignAllWith', 'assignIn', 'assignInAllWith',
'at', 'before', 'bind', 'bindAll', 'bindKey', 'chunk', 'cloneDeepWith',
'cloneWith', 'concat', 'conformsTo', 'countBy', 'curryN', 'curryRightN',
'debounce', 'defaults', 'defaultsDeep', 'defaultTo', 'delay', 'difference',
'divide', 'drop', 'dropRight', 'dropRightWhile', 'dropWhile', 'endsWith', 'eq',
'every', 'filter', 'find', 'findIndex', 'findKey', 'findLast', 'findLastIndex',
'findLastKey', 'flatMap', 'flatMapDeep', 'flattenDepth', 'forEach',
'forEachRight', 'forIn', 'forInRight', 'forOwn', 'forOwnRight', 'get',
'groupBy', 'gt', 'gte', 'has', 'hasIn', 'includes', 'indexOf', 'intersection',
'invertBy', 'invoke', 'invokeMap', 'isEqual', 'isMatch', 'join', 'keyBy',
'lastIndexOf', 'lt', 'lte', 'map', 'mapKeys', 'mapValues', 'matchesProperty',
'maxBy', 'meanBy', 'merge', 'mergeAllWith', 'minBy', 'multiply', 'nth', 'omit',
'omitBy', 'overArgs', 'pad', 'padEnd', 'padStart', 'parseInt', 'partial',
'partialRight', 'partition', 'pick', 'pickBy', 'propertyOf', 'pull', 'pullAll',
'pullAt', 'random', 'range', 'rangeRight', 'rearg', 'reject', 'remove',
'repeat', 'restFrom', 'result', 'sampleSize', 'some', 'sortBy', 'sortedIndex',
'sortedIndexOf', 'sortedLastIndex', 'sortedLastIndexOf', 'sortedUniqBy',
'split', 'spreadFrom', 'startsWith', 'subtract', 'sumBy', 'take', 'takeRight',
'takeRightWhile', 'takeWhile', 'tap', 'throttle', 'thru', 'times', 'trimChars',
'trimCharsEnd', 'trimCharsStart', 'truncate', 'union', 'uniqBy', 'uniqWith',
'unset', 'unzipWith', 'without', 'wrap', 'xor', 'zip', 'zipObject',
'zipObjectDeep'
],
'3': [
'assignInWith', 'assignWith', 'clamp', 'differenceBy', 'differenceWith',
'findFrom', 'findIndexFrom', 'findLastFrom', 'findLastIndexFrom', 'getOr',
'includesFrom', 'indexOfFrom', 'inRange', 'intersectionBy', 'intersectionWith',
'invokeArgs', 'invokeArgsMap', 'isEqualWith', 'isMatchWith', 'flatMapDepth',
'lastIndexOfFrom', 'mergeWith', 'orderBy', 'padChars', 'padCharsEnd',
'padCharsStart', 'pullAllBy', 'pullAllWith', 'rangeStep', 'rangeStepRight',
'reduce', 'reduceRight', 'replace', 'set', 'slice', 'sortedIndexBy',
'sortedLastIndexBy', 'transform', 'unionBy', 'unionWith', 'update', 'xorBy',
'xorWith', 'zipWith'
],
'4': [
'fill', 'setWith', 'updateWith'
]
};
/** Used to map ary to rearg configs. */
exports.aryRearg = {
'2': [1, 0],
'3': [2, 0, 1],
'4': [3, 2, 0, 1]
};
/** Used to map method names to their iteratee ary. */
exports.iterateeAry = {
'dropRightWhile': 1,
'dropWhile': 1,
'every': 1,
'filter': 1,
'find': 1,
'findFrom': 1,
'findIndex': 1,
'findIndexFrom': 1,
'findKey': 1,
'findLast': 1,
'findLastFrom': 1,
'findLastIndex': 1,
'findLastIndexFrom': 1,
'findLastKey': 1,
'flatMap': 1,
'flatMapDeep': 1,
'flatMapDepth': 1,
'forEach': 1,
'forEachRight': 1,
'forIn': 1,
'forInRight': 1,
'forOwn': 1,
'forOwnRight': 1,
'map': 1,
'mapKeys': 1,
'mapValues': 1,
'partition': 1,
'reduce': 2,
'reduceRight': 2,
'reject': 1,
'remove': 1,
'some': 1,
'takeRightWhile': 1,
'takeWhile': 1,
'times': 1,
'transform': 2
};
/** Used to map method names to iteratee rearg configs. */
exports.iterateeRearg = {
'mapKeys': [1],
'reduceRight': [1, 0]
};
/** Used to map method names to rearg configs. */
exports.methodRearg = {
'assignInAllWith': [1, 0],
'assignInWith': [1, 2, 0],
'assignAllWith': [1, 0],
'assignWith': [1, 2, 0],
'differenceBy': [1, 2, 0],
'differenceWith': [1, 2, 0],
'getOr': [2, 1, 0],
'intersectionBy': [1, 2, 0],
'intersectionWith': [1, 2, 0],
'isEqualWith': [1, 2, 0],
'isMatchWith': [2, 1, 0],
'mergeAllWith': [1, 0],
'mergeWith': [1, 2, 0],
'padChars': [2, 1, 0],
'padCharsEnd': [2, 1, 0],
'padCharsStart': [2, 1, 0],
'pullAllBy': [2, 1, 0],
'pullAllWith': [2, 1, 0],
'rangeStep': [1, 2, 0],
'rangeStepRight': [1, 2, 0],
'setWith': [3, 1, 2, 0],
'sortedIndexBy': [2, 1, 0],
'sortedLastIndexBy': [2, 1, 0],
'unionBy': [1, 2, 0],
'unionWith': [1, 2, 0],
'updateWith': [3, 1, 2, 0],
'xorBy': [1, 2, 0],
'xorWith': [1, 2, 0],
'zipWith': [1, 2, 0]
};
/** Used to map method names to spread configs. */
exports.methodSpread = {
'assignAll': { 'start': 0 },
'assignAllWith': { 'start': 0 },
'assignInAll': { 'start': 0 },
'assignInAllWith': { 'start': 0 },
'defaultsAll': { 'start': 0 },
'defaultsDeepAll': { 'start': 0 },
'invokeArgs': { 'start': 2 },
'invokeArgsMap': { 'start': 2 },
'mergeAll': { 'start': 0 },
'mergeAllWith': { 'start': 0 },
'partial': { 'start': 1 },
'partialRight': { 'start': 1 },
'without': { 'start': 1 },
'zipAll': { 'start': 0 }
};
/** Used to identify methods which mutate arrays or objects. */
exports.mutate = {
'array': {
'fill': true,
'pull': true,
'pullAll': true,
'pullAllBy': true,
'pullAllWith': true,
'pullAt': true,
'remove': true,
'reverse': true
},
'object': {
'assign': true,
'assignAll': true,
'assignAllWith': true,
'assignIn': true,
'assignInAll': true,
'assignInAllWith': true,
'assignInWith': true,
'assignWith': true,
'defaults': true,
'defaultsAll': true,
'defaultsDeep': true,
'defaultsDeepAll': true,
'merge': true,
'mergeAll': true,
'mergeAllWith': true,
'mergeWith': true,
},
'set': {
'set': true,
'setWith': true,
'unset': true,
'update': true,
'updateWith': true
}
};
/** Used to map real names to their aliases. */
exports.realToAlias = (function() {
var hasOwnProperty = Object.prototype.hasOwnProperty,
object = exports.aliasToReal,
result = {};
for (var key in object) {
var value = object[key];
if (hasOwnProperty.call(result, value)) {
result[value].push(key);
} else {
result[value] = [key];
}
}
return result;
}());
/** Used to map method names to other names. */
exports.remap = {
'assignAll': 'assign',
'assignAllWith': 'assignWith',
'assignInAll': 'assignIn',
'assignInAllWith': 'assignInWith',
'curryN': 'curry',
'curryRightN': 'curryRight',
'defaultsAll': 'defaults',
'defaultsDeepAll': 'defaultsDeep',
'findFrom': 'find',
'findIndexFrom': 'findIndex',
'findLastFrom': 'findLast',
'findLastIndexFrom': 'findLastIndex',
'getOr': 'get',
'includesFrom': 'includes',
'indexOfFrom': 'indexOf',
'invokeArgs': 'invoke',
'invokeArgsMap': 'invokeMap',
'lastIndexOfFrom': 'lastIndexOf',
'mergeAll': 'merge',
'mergeAllWith': 'mergeWith',
'padChars': 'pad',
'padCharsEnd': 'padEnd',
'padCharsStart': 'padStart',
'propertyOf': 'get',
'rangeStep': 'range',
'rangeStepRight': 'rangeRight',
'restFrom': 'rest',
'spreadFrom': 'spread',
'trimChars': 'trim',
'trimCharsEnd': 'trimEnd',
'trimCharsStart': 'trimStart',
'zipAll': 'zip'
};
/** Used to track methods that skip fixing their arity. */
exports.skipFixed = {
'castArray': true,
'flow': true,
'flowRight': true,
'iteratee': true,
'mixin': true,
'rearg': true,
'runInContext': true
};
/** Used to track methods that skip rearranging arguments. */
exports.skipRearg = {
'add': true,
'assign': true,
'assignIn': true,
'bind': true,
'bindKey': true,
'concat': true,
'difference': true,
'divide': true,
'eq': true,
'gt': true,
'gte': true,
'isEqual': true,
'lt': true,
'lte': true,
'matchesProperty': true,
'merge': true,
'multiply': true,
'overArgs': true,
'partial': true,
'partialRight': true,
'propertyOf': true,
'random': true,
'range': true,
'rangeRight': true,
'subtract': true,
'zip': true,
'zipObject': true,
'zipObjectDeep': true
};
'use strict'
var after = require('after')
var express = require('../')
, request = require('supertest');
describe('app', function(){
describe('.response', function(){
it('should extend the response prototype', function(done){
var app = express();
app.response.shout = function(str){
this.send(str.toUpperCase());
};
app.use(function(req, res){
res.shout('hey');
});
request(app)
.get('/')
.expect('HEY', done);
})
it('should only extend for the referenced app', function (done) {
var app1 = express()
var app2 = express()
var cb = after(2, done)
app1.response.shout = function (str) {
this.send(str.toUpperCase())
}
app1.get('/', function (req, res) {
res.shout('foo')
})
app2.get('/', function (req, res) {
res.shout('foo')
})
request(app1)
.get('/')
.expect(200, 'FOO', cb)
request(app2)
.get('/')
.expect(500, /(?:not a function|has no method)/, cb)
})
it('should inherit to sub apps', function (done) {
var app1 = express()
var app2 = express()
var cb = after(2, done)
app1.response.shout = function (str) {
this.send(str.toUpperCase())
}
app1.use('/sub', app2)
app1.get('/', function (req, res) {
res.shout('foo')
})
app2.get('/', function (req, res) {
res.shout('foo')
})
request(app1)
.get('/')
.expect(200, 'FOO', cb)
request(app1)
.get('/sub')
.expect(200, 'FOO', cb)
})
it('should allow sub app to override', function (done) {
var app1 = express()
var app2 = express()
var cb = after(2, done)
app1.response.shout = function (str) {
this.send(str.toUpperCase())
}
app2.response.shout = function (str) {
this.send(str + '!')
}
app1.use('/sub', app2)
app1.get('/', function (req, res) {
res.shout('foo')
})
app2.get('/', function (req, res) {
res.shout('foo')
})
request(app1)
.get('/')
.expect(200, 'FOO', cb)
request(app1)
.get('/sub')
.expect(200, 'foo!', cb)
})
it('should not pollute parent app', function (done) {
var app1 = express()
var app2 = express()
var cb = after(2, done)
app1.response.shout = function (str) {
this.send(str.toUpperCase())
}
app2.response.shout = function (str) {
this.send(str + '!')
}
app1.use('/sub', app2)
app1.get('/sub/foo', function (req, res) {
res.shout('foo')
})
app2.get('/', function (req, res) {
res.shout('foo')
})
request(app1)
.get('/sub')
.expect(200, 'foo!', cb)
request(app1)
.get('/sub/foo')
.expect(200, 'FOO', cb)
})
})
})
'use strict'
/**
* Module dependencies.
*/
var https = require('node:https');
var path = require('node:path');
var extname = path.extname;
/**
* Expose `GithubView`.
*/
module.exports = GithubView;
/**
* Custom view that fetches and renders
* remove github templates. You could
* render templates from a database etc.
*/
function GithubView(name, options){
this.name = name;
options = options || {};
this.engine = options.engines[extname(name)];
// "root" is the app.set('views') setting, however
// in your own implementation you could ignore this
this.path = '/' + options.root + '/master/' + name;
}
/**
* Render the view.
*/
GithubView.prototype.render = function(options, fn){
var self = this;
var opts = {
host: 'raw.githubusercontent.com',
port: 443,
path: this.path,
method: 'GET'
};
https.request(opts, function(res) {
var buf = '';
res.setEncoding('utf8');
res.on('data', function(str){ buf += str });
res.on('end', function(){
self.engine(buf, options, fn);
});
}).end();
};
import process from 'node:process';
import {Buffer} from 'node:buffer';
import {promisify} from 'node:util';
import stream from 'node:stream';
import {pipeline as streamPipeline} from 'node:stream/promises';
import fs from 'node:fs';
// @ts-expect-error Fails to find slow-stream/index.d.ts
import SlowStream from 'slow-stream';
import getStream from 'get-stream';
import {temporaryFile} from 'tempy';
import is from '@sindresorhus/is';
import test, {type ExecutionContext} from 'ava';
import type {Handler} from 'express';
import {pEvent} from 'p-event';
import {chunk, chunkFromAsync} from 'chunk-data';
import type {Progress} from '../source/index.js';
import withServer from './helpers/with-server.js';
const checkEvents = (t: ExecutionContext, events: Progress[], bodySize?: number) => {
t.true(events.length >= 2);
let lastEvent = events.shift()!;
if (!is.number(bodySize)) {
t.is(lastEvent.percent, 0);
}
for (const [index, event] of events.entries()) {
const isLastEvent = index === events.length - 1;
if (is.number(bodySize)) {
t.is(event.percent, event.transferred / bodySize);
t.true(event.percent > lastEvent.percent);
t.true(event.transferred > lastEvent.transferred);
} else if (isLastEvent) {
t.is(event.percent, 1);
t.is(event.transferred, lastEvent.transferred);
t.is(event.total, event.transferred);
} else {
t.is(event.percent, 0);
t.true(event.transferred > lastEvent.transferred);
}
lastEvent = event;
}
};
const file = Buffer.alloc(1024 * 1024 * 2);
const downloadEndpoint: Handler = (_request, response) => {
response.setHeader('content-length', file.length);
(async () => {
try {
await streamPipeline(
stream.Readable.from(file),
new SlowStream({maxWriteInterval: 50}),
response,
);
} catch {}
response.end();
})();
};
const noTotalEndpoint: Handler = (_request, response) => {
response.write('hello');
response.end();
};
const uploadEndpoint: Handler = (request, response) => {
(async () => {
try {
await streamPipeline(
request,
new SlowStream({maxWriteInterval: 100}),
);
} catch {}
response.end();
})();
};
test('download progress', withServer, async (t, server, got) => {
server.get('/', downloadEndpoint);
const events: Progress[] = [];
const {body} = await got({responseType: 'buffer'})
.on('downloadProgress', event => {
events.push(event);
});
checkEvents(t, events, body.length);
});
test('download progress - missing total size', withServer, async (t, server, got) => {
server.get('/', noTotalEndpoint);
const events: Progress[] = [];
await got('').on('downloadProgress', (event: Progress) => {
events.push(event);
});
t.is(events[0]?.total, undefined);
checkEvents(t, events);
});
test('download progress - stream', withServer, async (t, server, got) => {
server.get('/', downloadEndpoint);
const events: Progress[] = [];
const stream = got.stream({responseType: 'buffer'})
.on('downloadProgress', event => {
events.push(event);
});
await getStream(stream);
checkEvents(t, events, file.length);
});
test('upload progress - file', withServer, async (t, server, got) => {
server.post('/', uploadEndpoint);
const events: Progress[] = [];
await got.post({body: file}).on('uploadProgress', (event: Progress) => {
events.push(event);
});
checkEvents(t, events, file.length);
});
test('upload progress - file stream', withServer, async (t, server, got) => {
server.post('/', uploadEndpoint);
const path = temporaryFile();
fs.writeFileSync(path, file);
const {size} = await promisify(fs.stat)(path);
const events: Progress[] = [];
await got.post({
body: fs.createReadStream(path),
headers: {
'content-length': size.toString(),
},
})
.on('uploadProgress', (event: Progress) => {
events.push(event);
});
checkEvents(t, events, file.length);
});
test('upload progress - form data', withServer, async (t, server, got) => {
server.post('/', uploadEndpoint);
const events: Progress[] = [];
const body = new globalThis.FormData();
body.set('key', 'value');
body.set('file', new File([file], 'file'));
await got.post({body}).on('uploadProgress', (event: Progress) => {
events.push(event);
});
checkEvents(t, events);
});
test('upload progress - json', withServer, async (t, server, got) => {
server.post('/', uploadEndpoint);
const body = JSON.stringify({key: 'value'});
const size = Buffer.byteLength(body);
const events: Progress[] = [];
await got.post({body}).on('uploadProgress', (event: Progress) => {
events.push(event);
});
checkEvents(t, events, size);
});
test('upload progress - measures bytes correctly for non-UTF-8 encoded strings', withServer, async (t, server, got) => {
server.post('/', uploadEndpoint);
// String with emoji - 'Hello 👋' is 10 bytes in UTF-8, but 16 bytes in UTF-16LE
const text = 'Hello 👋';
const utf8Size = Buffer.from(text, 'utf8').byteLength; // 10 bytes
const utf16Size = Buffer.from(text, 'utf16le').byteLength; // 16 bytes
t.is(utf8Size, 10);
t.is(utf16Size, 16);
const events: Progress[] = [];
// Upload as UTF-8 (default)
await got.post({body: text}).on('uploadProgress', (event: Progress) => {
events.push(event);
});
// Verify the progress measures UTF-8 bytes correctly
const finalEvent = events.at(-1)!;
t.is(finalEvent.transferred, utf8Size);
t.is(finalEvent.total, utf8Size);
});
test('upload progress - stream with known body size', withServer, async (t, server, got) => {
server.post('/', uploadEndpoint);
const events: Progress[] = [];
const options = {
headers: {'content-length': file.length.toString()},
};
const request = got.stream.post(options)
.on('uploadProgress', event => {
events.push(event);
});
await streamPipeline(stream.Readable.from(file), request);
await getStream(request);
checkEvents(t, events, file.length);
});
test('upload progress - stream with unknown body size', withServer, async (t, server, got) => {
server.post('/', uploadEndpoint);
const events: Progress[] = [];
const request = got.stream.post('')
.on('uploadProgress', event => {
events.push(event);
});
await streamPipeline(stream.Readable.from(file), request);
await getStream(request);
t.is(events[0]?.total, undefined);
checkEvents(t, events);
});
test('upload progress - no body', withServer, async (t, server, got) => {
server.post('/', uploadEndpoint);
const events: Progress[] = [];
await got.post('').on('uploadProgress', (event: Progress) => {
events.push(event);
});
t.deepEqual(events, [
{
percent: 0,
transferred: 0,
total: undefined,
},
{
percent: 1,
transferred: 0,
total: 0,
},
]);
});
test('upload progress - no events when immediately removed listener', withServer, async (t, server, got) => {
server.post('/', uploadEndpoint);
const events: Progress[] = [];
const listener = (event: Progress) => {
events.push(event);
};
const promise = got.post('')
.on('uploadProgress', listener)
.off('uploadProgress', listener);
await promise;
t.is(events.length, 0);
});
test('upload progress - one event when removed listener', withServer, async (t, server, got) => {
server.post('/', uploadEndpoint);
const events: Progress[] = [];
const promise = got.post('');
const listener = (event: Progress) => {
events.push(event);
void promise.off('uploadProgress', listener);
};
void promise.on('uploadProgress', listener);
await promise;
t.deepEqual(events, [
{
percent: 0,
transferred: 0,
total: undefined,
},
]);
});
test('does not emit uploadProgress after cancelation', withServer, async (t, server, got) => {
server.post('/', () => {});
const stream = got.stream.post();
stream.once('uploadProgress', () => { // 0%
stream.once('uploadProgress', () => { // 'foo'
stream.write('bar');
process.nextTick(() => {
process.nextTick(() => {
stream.on('uploadProgress', () => {
t.fail('Emitted uploadProgress after cancelation');
});
stream.destroy();
});
});
});
});
stream.write('foo');
await pEvent(stream, 'close');
t.pass();
});
test('upload progress - chunk generator with buffer', withServer, async (t, server, got) => {
server.post('/', uploadEndpoint);
const events: Progress[] = [];
await got.post({
body: chunk(file, 65_536),
headers: {
'content-length': file.length.toString(),
},
})
.on('uploadProgress', (event: Progress) => {
events.push(event);
});
checkEvents(t, events, file.length);
// Ensure we got more than just 0% and 100%
t.true(events.length > 2, `Expected more than 2 events with chunk, got ${events.length}`);
});
test('upload progress - chunkFromAsync async generator with stream', withServer, async (t, server, got) => {
server.post('/', uploadEndpoint);
const events: Progress[] = [];
await got.post({
body: chunkFromAsync(stream.Readable.from([file]), 65_536),
headers: {
'content-length': file.length.toString(),
},
})
.on('uploadProgress', (event: Progress) => {
events.push(event);
});
checkEvents(t, events, file.length);
// Ensure we got more than just 0% and 100%
t.true(events.length > 2, `Expected more than 2 events with chunkFromAsync, got ${events.length}`);
});
test('upload progress - buffer body', withServer, async (t, server, got) => {
server.post('/', uploadEndpoint);
const events: Progress[] = [];
const body = Buffer.alloc(1024 * 256); // 256 KB
await got.post({
body,
headers: {'content-length': body.byteLength.toString()},
}).on('uploadProgress', (event: Progress) => {
events.push(event);
});
checkEvents(t, events, body.byteLength);
// Ensure we got more than just 0% and 100%
t.true(events.length > 2, `Expected more than 2 events with buffer body, got ${events.length}`);
});
test('upload progress - typed array body', withServer, async (t, server, got) => {
server.post('/', uploadEndpoint);
const events: Progress[] = [];
const body = new Uint8Array(1024 * 256); // 256 KB
await got.post({
body,
headers: {'content-length': body.byteLength.toString()},
}).on('uploadProgress', (event: Progress) => {
events.push(event);
});
checkEvents(t, events, body.byteLength);
// Ensure we got more than just 0% and 100%
t.true(events.length > 2, `Expected more than 2 events with typed array body, got ${events.length}`);
});
test('upload progress - small json option', withServer, async (t, server, got) => {
server.post('/', uploadEndpoint);
const events: Progress[] = [];
const payload = {key: 'value'};
const size = Buffer.byteLength(JSON.stringify(payload));
await got.post({json: payload}).on('uploadProgress', (event: Progress) => {
events.push(event);
});
checkEvents(t, events, size);
});
test('upload progress - json option', withServer, async (t, server, got) => {
server.post('/', uploadEndpoint);
const events: Progress[] = [];
const payload = {key: '.'.repeat(1e6)};
const size = Buffer.byteLength(JSON.stringify(payload));
await got.post({json: payload}).on('uploadProgress', (event: Progress) => {
events.push(event);
});
checkEvents(t, events, size);
// Ensure we got more than just 0% and 100%
t.true(events.length > 2, `Expected more than 2 events with json option, got ${events.length}`);
});
test('upload progress - form option', withServer, async (t, server, got) => {
server.post('/', uploadEndpoint);
const events: Progress[] = [];
const payload = {key: '.'.repeat(1e6)};
const size = Buffer.byteLength(new URLSearchParams(payload).toString());
await got.post({form: payload}).on('uploadProgress', (event: Progress) => {
events.push(event);
});
checkEvents(t, events, size);
// Ensure we got more than just 0% and 100%
t.true(events.length > 2, `Expected more than 2 events with form option, got ${events.length}`);
});
# Migrating from v2 to v3
v3 is the next major version of Catch2 and brings three significant changes:
* Catch2 is now split into multiple headers
* Catch2 is now compiled as a static library
* C++14 is the minimum required C++ version
There are many reasons why we decided to go from the old single-header
distribution model to a more standard library distribution model. The
big one is compile-time performance, but moving over to a split header
distribution model also improves the future maintainability and
extendability of the codebase. For example v3 adds a new kind of matchers
without impacting the compilation times of users that do not use matchers
in their tests. The new model is also more friendly towards package
managers, such as vcpkg and Conan.
The result of this move is a significant improvement in compilation
times, e.g. the inclusion overhead of Catch2 in the common case has been
reduced by roughly 80%. The improved ease of maintenance also led to
various runtime performance improvements and the introduction of new features.
For details, look at [the release notes of 3.0.1](release-notes.md#301).
_Note that we still provide one header + one translation unit (TU)
distribution but do not consider it the primarily supported option. You
should also expect that the compilation times will be worse if you use
this option._
## How to migrate projects from v2 to v3
To migrate to v3, there are two basic approaches to do so.
1. Use `catch_amalgamated.hpp` and `catch_amalgamated.cpp`.
2. Build Catch2 as a proper (static) library, and move to piecewise headers
Doing 1 means downloading the [amalgamated header](/extras/catch_amalgamated.hpp)
and the [amalgamated sources](/extras/catch_amalgamated.cpp) from `extras`,
dropping them into your test project, and rewriting your includes from
`` to `"catch_amalgamated.hpp"` (or something similar,
based on how you set up your paths).
The disadvantage of using this approach are increased compilation times,
at least compared to the second approach, but it does let you avoid
dealing with consuming libraries in your build system of choice.
However, we recommend doing 2, and taking extra time to migrate to v3
properly. This lets you reap the benefits of significantly improved
compilation times in the v3 version. The basic steps to do so are:
1. Change your CMakeLists.txt to link against `Catch2WithMain` target if
you use Catch2's default main. (If you do not, keep linking against
the `Catch2` target.). If you use pkg-config, change `pkg-config catch2` to
`pkg-config catch2-with-main`.
2. Delete TU with `CATCH_CONFIG_RUNNER` or `CATCH_CONFIG_MAIN` defined,
as it is no longer needed.
3. Change `#include ` to `#include `
4. Check that everything compiles. You might have to modify namespaces,
or perform some other changes (see the
[Things that can break during porting](#things-that-can-break-during-porting)
section for the most common things).
5. Start migrating your test TUs from including ``
to piecemeal includes. You will likely want to start by including
``, and then go from there. (see
[other notes](#other-notes) for further ideas)
## Other notes
* The main test include is now ``
* Big "subparts" like Matchers, or Generators, have their own folder, and
also their own "big header", so if you just want to include all matchers,
you can include ``,
or ``
## Things that can break during porting
* The namespaces of Matchers were flattened and cleaned up.
Matchers are no longer declared deep within an internal namespace and
then brought up into `Catch` namespace. All Matchers now live in the
`Catch::Matchers` namespace.
* The `Contains` string matcher was renamed to `ContainsSubstring`.
* The reporter interfaces changed in a breaking manner.
If you are using a custom reporter or listener, you will likely need to
modify them to conform to the new interfaces. Unlike before in v2,
the [interfaces](reporters.md#top) and the [events](reporter-events.md#top)
are now documented.
---
[Home](Readme.md#top)
from urllib import parse as urlparse
import click
def validate_count(ctx, param, value):
if value < 0 or value % 2 != 0:
raise click.BadParameter("Should be a positive, even integer.")
return value
class URL(click.ParamType[urlparse.ParseResult]):
name = "url"
def convert(self, value, param, ctx) -> urlparse.ParseResult:
if not isinstance(value, tuple):
value = urlparse.urlparse(value)
if value.scheme not in ("http", "https"):
self.fail(
f"invalid URL scheme ({value.scheme}). Only HTTP URLs are allowed",
param,
ctx,
)
return value
@click.command()
@click.option(
"--count", default=2, callback=validate_count, help="A positive even number."
)
@click.option("--foo", help="A mysterious parameter.")
@click.option("--url", help="A URL", type=URL())
@click.version_option()
def cli(count, foo, url):
"""Validation.
This example validates parameters in different ways. It does it
through callbacks, through a custom type as well as by validating
manually in the function.
"""
if foo is not None and foo != "wat":
raise click.BadParameter(
'If a value is provided it needs to be the value "wat".',
param_hint=["--foo"],
)
click.echo(f"count: {count}")
click.echo(f"foo: {foo}")
click.echo(f"url: {url!r}")
name: CI Browsers
on:
push:
branches: [ main ]
pull_request:
# Run on every PR, regardless of branch
branches: [ '*' ]
workflow_dispatch:
jobs:
test-docs:
name: Modern Browsers Test
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1
- name: Install Node
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version: '24'
- name: Install dependencies
run: |
npm install
npx playwright install --with-deps
npm install -D @playwright/test@latest
- name: Build project
run: npm run build
- name: Start server
run: |
npx http-server -p 9001 &
sleep 2
- name: Run Playwright tests
run: npx playwright test
import {Buffer} from 'node:buffer';
import test from 'ava';
import type {Handler} from 'express';
import getStream from 'get-stream';
import {HTTPError, ParseError} from '../source/index.js';
import withServer from './helpers/with-server.js';
const dog = {data: 'dog'};
const jsonResponse = JSON.stringify(dog);
const defaultHandler: Handler = (_request, response) => {
response.end(jsonResponse);
};
test('`options.resolveBodyOnly` works', withServer, async (t, server, got) => {
server.get('/', defaultHandler);
t.deepEqual(await got>({responseType: 'json', resolveBodyOnly: true}), dog);
});
test('`options.resolveBodyOnly` combined with `options.throwHttpErrors`', withServer, async (t, server, got) => {
server.get('/', (_request, response) => {
response.statusCode = 404;
response.end('/');
});
t.is(await got({resolveBodyOnly: true, throwHttpErrors: false}), '/');
});
test('JSON response', withServer, async (t, server, got) => {
server.get('/', defaultHandler);
t.deepEqual((await got({responseType: 'json'})).body, dog);
});
test('Uint8Array response', withServer, async (t, server, got) => {
server.get('/', defaultHandler);
const {body} = await got({responseType: 'buffer'});
t.deepEqual(body, new TextEncoder().encode(jsonResponse));
t.true(body instanceof Uint8Array);
t.false(Buffer.isBuffer(body));
});
test('rawBody is compatible with web APIs', withServer, async (t, server, got) => {
server.get('/', defaultHandler);
const {rawBody} = await got({responseType: 'text'});
t.true(rawBody.buffer instanceof ArrayBuffer);
t.is(await new Blob([rawBody]).text(), jsonResponse);
t.is(await new Response(rawBody).text(), jsonResponse);
});
test('Text response', withServer, async (t, server, got) => {
server.get('/', defaultHandler);
t.is((await got({responseType: 'text'})).body, jsonResponse);
});
test('Text response #2', withServer, async (t, server, got) => {
server.get('/', defaultHandler);
t.is((await got({responseType: undefined})).body, jsonResponse);
});
test('Text response preserves UTF-8 BOM', withServer, async (t, server, got) => {
server.get('/', (_request, response) => {
response.end(Buffer.from([0xEF, 0xBB, 0xBF, ...Buffer.from('hello')]));
});
t.is((await got({responseType: 'text'})).body, '\uFEFFhello');
});
test('Text response shortcut strips UTF-8 BOM', withServer, async (t, server, got) => {
server.get('/', (_request, response) => {
response.end(Buffer.from([0xEF, 0xBB, 0xBF, ...Buffer.from('hello')]));
});
t.is(await got('').text(), 'hello');
});
test('JSON response - promise.json()', withServer, async (t, server, got) => {
server.get('/', defaultHandler);
t.deepEqual(await got('').json(), dog);
});
test('Uint8Array response - promise.buffer()', withServer, async (t, server, got) => {
server.get('/', defaultHandler);
const body = await got('').buffer();
t.deepEqual(body, new TextEncoder().encode(jsonResponse));
t.true(body instanceof Uint8Array);
t.false(Buffer.isBuffer(body));
});
test('Text response - promise.text()', withServer, async (t, server, got) => {
server.get('/', defaultHandler);
t.is(await got('').text(), jsonResponse);
});
test('Text response - promise.json().text()', withServer, async (t, server, got) => {
server.get('/', defaultHandler);
t.is(await got('').json().text(), jsonResponse);
});
test('works if promise has been already resolved', withServer, async (t, server, got) => {
server.get('/', defaultHandler);
const promise = got('').text();
t.is(await promise, jsonResponse);
t.deepEqual(await promise.json(), dog);
});
test('throws an error on invalid response type', withServer, async (t, server, got) => {
server.get('/', defaultHandler);
// @ts-expect-error Error tests
const error = await t.throwsAsync(got({responseType: 'invalid'}));
t.is(error?.message, 'Invalid `responseType` option: invalid');
});
test('wraps parsing errors', withServer, async (t, server, got) => {
server.get('/', (_request, response) => {
response.end('/');
});
const error = await t.throwsAsync(got({responseType: 'json'}), {instanceOf: ParseError});
t.true(error?.message.includes((error.options.url as URL).hostname));
t.is((error?.options.url as URL).pathname, '/');
t.is(error?.code, 'ERR_BODY_PARSE_FAILURE');
});
test('credentials are stripped from ParseError message URL', withServer, async (t, server, got) => {
server.get('/', (_request, response) => {
response.end('/');
});
const url = new URL(server.url);
url.username = 'user';
url.password = 'secret';
const error = await t.throwsAsync(got(url, {responseType: 'json'}), {instanceOf: ParseError});
t.false(error?.message.includes('user'));
t.false(error?.message.includes('secret'));
t.regex(error?.message ?? '', /in "http:\/\/localhost:\d+\/"$/v);
});
test('JSON response with UTF-8 BOM throws ParseError', withServer, async (t, server, got) => {
server.get('/', (_request, response) => {
response.end(Buffer.from([0xEF, 0xBB, 0xBF, ...Buffer.from(jsonResponse)]));
});
await t.throwsAsync(got({responseType: 'json'}), {instanceOf: ParseError});
});
test('parses non-200 responses', withServer, async (t, server, got) => {
server.get('/', (_request, response) => {
response.statusCode = 500;
response.end(jsonResponse);
});
const error = await t.throwsAsync(got({responseType: 'json', retry: {limit: 0}}), {instanceOf: HTTPError});
t.deepEqual(error?.response.body, dog);
});
test('ignores errors on invalid non-200 responses', withServer, async (t, server, got) => {
server.get('/', (_request, response) => {
response.statusCode = 500;
response.end('Internal error');
});
const error = await t.throwsAsync(got({responseType: 'json', retry: {limit: 0}}), {
instanceOf: HTTPError,
message: /^Request failed with status code 500 \(Internal Server Error\): GET http:\/\/localhost:\d+\/$/v,
});
t.is(error?.response.body, 'Internal error');
t.is((error?.options.url as URL).pathname, '/');
});
test('parse errors have `response` property', withServer, async (t, server, got) => {
server.get('/', (_request, response) => {
response.end('/');
});
const error = await t.throwsAsync(got({responseType: 'json'}), {instanceOf: ParseError});
t.is(error?.response.statusCode, 200);
t.is(error?.response.body, '/');
t.is(error?.code, 'ERR_BODY_PARSE_FAILURE');
});
test('sets correct headers', withServer, async (t, server, got) => {
server.post('/', (request, response) => {
response.end(JSON.stringify(request.headers));
});
const {body: headers} = await got.post>({responseType: 'json', json: {}});
t.is(headers['content-type'], 'application/json');
t.is(headers.accept, 'application/json');
});
test('doesn\'t throw on 204 No Content', withServer, async (t, server, got) => {
server.get('/', (_request, response) => {
response.statusCode = 204;
response.end();
});
const body = await got('').json();
t.is(body, '');
});
test('doesn\'t throw on empty bodies', withServer, async (t, server, got) => {
server.get('/', (_request, response) => {
response.statusCode = 200;
response.end();
});
const body = await got('').json();
t.is(body, '');
});
test('.buffer() returns binary content', withServer, async (t, server, got) => {
const body = Buffer.from('89504E470D0A1A0A0000000D49484452', 'hex');
server.get('/', (_request, response) => {
response.end(body);
});
const buffer = await got('').buffer();
t.is(Buffer.compare(buffer, body), 0);
});
test('shortcuts throw ParseErrors', withServer, async (t, server, got) => {
server.get('/', (_request, response) => {
response.end('not a json');
});
await t.throwsAsync(got('').json(), {
instanceOf: ParseError,
message: /^Unexpected token/v,
code: 'ERR_BODY_PARSE_FAILURE',
});
});
test('shortcuts result properly when retrying in afterResponse', withServer, async (t, server, got) => {
const nasty = JSON.stringify({hello: 'nasty'});
const proper = JSON.stringify({hello: 'world'});
server.get('/', (request, response) => {
if (request.headers.token === 'unicorn') {
response.end(proper);
} else {
response.statusCode = 401;
response.end(nasty);
}
});
const promise = got({
hooks: {
afterResponse: [
(response, retryWithMergedOptions) => {
if (response.statusCode === 401) {
return retryWithMergedOptions({
headers: {
token: 'unicorn',
},
});
}
return response;
},
],
},
});
const json = await promise.json<{hello: string}>();
const text = await promise.text();
const buffer = await promise.buffer();
t.is(json.hello, 'world');
t.is(text, proper);
t.is(Buffer.from(buffer).compare(Buffer.from(proper)), 0);
});
test('responseType is optional when using template', withServer, async (t, server, got) => {
const data = {hello: 'world'};
server.post('/', async (request, response) => {
response.end(await getStream(request));
});
const jsonClient = got.extend({responseType: 'json'});
const {body} = await jsonClient.post('', {json: data});
t.deepEqual(body, data);
});
test('JSON response custom parser', withServer, async (t, server, got) => {
server.get('/', defaultHandler);
t.deepEqual((await got({
responseType: 'json',
parseJson: text => ({...JSON.parse(text), custom: 'parser'}),
})).body, {...dog, custom: 'parser'});
});
test.serial('incrementally decodes UTF-8 text response while downloading', withServer, async (t, server, got) => {
if (globalThis.TextDecoder === undefined) {
t.pass();
return;
}
const originalDecode = globalThis.TextDecoder.prototype.decode;
let responseEnded = false;
let streamDecodeCallCount = 0;
let decodedBeforeResponseEnded = false;
globalThis.TextDecoder.prototype.decode = function (input?: BufferSource, options?: TextDecodeOptions): string {
if (options?.stream) {
streamDecodeCallCount++;
if (!responseEnded) {
decodedBeforeResponseEnded = true;
}
}
return originalDecode.call(this, input, options);
};
server.get('/', (_request, response) => {
response.write('hello ');
setTimeout(() => {
responseEnded = true;
response.end('world');
}, 25);
});
try {
const {body} = await got({responseType: 'text'});
t.is(body, 'hello world');
t.true(streamDecodeCallCount > 0);
t.true(decodedBeforeResponseEnded);
} finally {
globalThis.TextDecoder.prototype.decode = originalDecode;
}
});
test.serial('incrementally decodes UTF-8 JSON response while downloading', withServer, async (t, server, got) => {
if (globalThis.TextDecoder === undefined) {
t.pass();
return;
}
const originalDecode = globalThis.TextDecoder.prototype.decode;
let responseEnded = false;
let streamDecodeCallCount = 0;
let decodedBeforeResponseEnded = false;
globalThis.TextDecoder.prototype.decode = function (input?: BufferSource, options?: TextDecodeOptions): string {
if (options?.stream) {
streamDecodeCallCount++;
if (!responseEnded) {
decodedBeforeResponseEnded = true;
}
}
return originalDecode.call(this, input, options);
};
server.get('/', (_request, response) => {
response.write('{"hello":"');
setTimeout(() => {
responseEnded = true;
response.end('world"}');
}, 25);
});
try {
const {body} = await got<{hello: string}>({responseType: 'json'});
t.deepEqual(body, {hello: 'world'});
t.true(streamDecodeCallCount > 0);
t.true(decodedBeforeResponseEnded);
} finally {
globalThis.TextDecoder.prototype.decode = originalDecode;
}
});
test.serial('falls back to buffered decode when incremental decode throws', withServer, async (t, server, got) => {
if (globalThis.TextDecoder === undefined) {
t.pass();
return;
}
const originalDecode = globalThis.TextDecoder.prototype.decode;
const payload = {hello: 'world'};
let thrown = false;
globalThis.TextDecoder.prototype.decode = function (input?: BufferSource, options?: TextDecodeOptions): string {
if (!thrown && options?.stream) {
thrown = true;
throw new TypeError('Injected decode failure');
}
return originalDecode.call(this, input, options);
};
server.get('/', (_request, response) => {
response.end(JSON.stringify(payload));
});
try {
const {body} = await got({responseType: 'json'});
t.true(thrown);
t.deepEqual(body, payload);
} finally {
globalThis.TextDecoder.prototype.decode = originalDecode;
}
});
test.serial('falls back to buffered decode when incremental decoder final flush throws', withServer, async (t, server, got) => {
if (globalThis.TextDecoder === undefined) {
t.pass();
return;
}
const originalDecode = globalThis.TextDecoder.prototype.decode;
const payload = {hello: 'world'};
let thrown = false;
globalThis.TextDecoder.prototype.decode = function (input?: BufferSource, options?: TextDecodeOptions): string {
if (!thrown && options === undefined) {
thrown = true;
throw new TypeError('Injected final flush decode failure');
}
return originalDecode.call(this, input, options);
};
server.get('/', (_request, response) => {
response.end(JSON.stringify(payload));
});
try {
const {body} = await got({responseType: 'json'});
t.true(thrown);
t.deepEqual(body, payload);
} finally {
globalThis.TextDecoder.prototype.decode = originalDecode;
}
});
test.serial('does not incrementally decode for non-UTF-8 encoding', withServer, async (t, server, got) => {
if (globalThis.TextDecoder === undefined) {
t.pass();
return;
}
const originalDecode = globalThis.TextDecoder.prototype.decode;
const payload = 'a'.repeat(1024);
let streamDecodeCallCount = 0;
globalThis.TextDecoder.prototype.decode = function (input?: BufferSource, options?: TextDecodeOptions): string {
if (options?.stream) {
streamDecodeCallCount++;
}
return originalDecode.call(this, input, options);
};
server.get('/', (_request, response) => {
response.end(payload);
});
try {
const {body} = await got({
responseType: 'text',
encoding: 'base64',
});
t.is(body, Buffer.from(payload).toString('base64'));
t.is(streamDecodeCallCount, 0);
} finally {
globalThis.TextDecoder.prototype.decode = originalDecode;
}
});
test.serial('incrementally decodes for case-insensitive UTF-8 encoding names', withServer, async (t, server, got) => {
if (globalThis.TextDecoder === undefined) {
t.pass();
return;
}
const originalDecode = globalThis.TextDecoder.prototype.decode;
const payload = 'hello world';
const encoding = Buffer.from([85, 84, 70, 45, 56]).toString() as BufferEncoding;
let streamDecodeCallCount = 0;
globalThis.TextDecoder.prototype.decode = function (input?: BufferSource, options?: TextDecodeOptions): string {
if (options?.stream) {
streamDecodeCallCount++;
}
return originalDecode.call(this, input, options);
};
server.get('/', (_request, response) => {
response.end(payload);
});
try {
const encodingWithoutHyphen = Buffer.from([85, 84, 70, 56]).toString() as BufferEncoding;
const responses = await Promise.all([
got({
responseType: 'text',
encoding,
}),
got({
responseType: 'text',
encoding: encodingWithoutHyphen,
}),
]);
for (const response of responses) {
t.is(response.body, payload);
}
t.true(streamDecodeCallCount > 0);
} finally {
globalThis.TextDecoder.prototype.decode = originalDecode;
}
});
test.serial('does not incrementally decode in stream mode', withServer, async (t, server, got) => {
if (globalThis.TextDecoder === undefined) {
t.pass();
return;
}
const originalDecode = globalThis.TextDecoder.prototype.decode;
let streamDecodeCallCount = 0;
globalThis.TextDecoder.prototype.decode = function (input?: BufferSource, options?: TextDecodeOptions): string {
if (options?.stream) {
streamDecodeCallCount++;
}
return originalDecode.call(this, input, options);
};
server.get('/', (_request, response) => {
response.end('hello');
});
try {
await new Promise((resolve, reject) => {
const streamRequest = got.stream({responseType: 'text'});
streamRequest.on('error', reject);
streamRequest.on('end', resolve);
streamRequest.resume();
});
t.is(streamDecodeCallCount, 0);
} finally {
globalThis.TextDecoder.prototype.decode = originalDecode;
}
});
export default function isUnixSocketUrl(url: URL) {
return url.protocol === 'unix:' || url.hostname === 'unix';
}
/**
Extract the socket path from a UNIX socket URL.
@example
```
getUnixSocketPath(new URL('http://unix/foo:/path'));
//=> '/foo'
getUnixSocketPath(new URL('unix:/foo:/path'));
//=> '/foo'
getUnixSocketPath(new URL('http://example.com'));
//=> undefined
```
*/
export function getUnixSocketPath(url: URL): string | undefined {
if (!isUnixSocketUrl(url)) {
return undefined;
}
return /^(?[^:]+):/v.exec(`${url.pathname}${url.search}`)?.groups?.socketPath;
}
'use strict'
module.exports = User;
// faux model
function User(name, age, species) {
this.name = name;
this.age = age;
this.species = species;
}
User.all = function(fn){
// process.nextTick makes sure this function API
// behaves in an asynchronous manner, like if it
// was a real DB query to read all users.
process.nextTick(function(){
fn(null, users);
});
};
User.count = function(fn){
process.nextTick(function(){
fn(null, users.length);
});
};
// faux database
var users = [];
users.push(new User('Tobi', 2, 'ferret'));
users.push(new User('Loki', 1, 'ferret'));
users.push(new User('Jane', 6, 'ferret'));
users.push(new User('Luna', 1, 'cat'));
users.push(new User('Manny', 1, 'cat'));
from jinja2 import Environment
env = Environment(extensions=["jinja2.ext.i18n"])
env.globals["gettext"] = {"Hello %(user)s!": "Hallo %(user)s!"}.__getitem__
env.globals["ngettext"] = lambda s, p, n: {
"%(count)s user": "%(count)d Benutzer",
"%(count)s users": "%(count)d Benutzer",
}[s if n == 1 else p]
print(
env.from_string(
"""\
{% trans %}Hello {{ user }}!{% endtrans %}
{% trans count=users|count -%}
{{ count }} user{% pluralize %}{{ count }} users
{% endtrans %}
"""
).render(user="someone", users=[1, 2, 3])
)
[> Back to homepage](../readme.md#documentation)
## Retry API
**Note:**
> If you're looking for retry implementation using streams, check out the [Retry Stream API](3-streams.md#retry).
**Tip:**
> You can trigger a retry by throwing the [`RetryError`](8-errors.md#retryerror) in any hook.
**Tip:**
> The `afterResponse` hook exposes a dedicated function to retry with merged options. [Read more](9-hooks.md#afterresponse).
### `retry`
**Type: `object`**\
**Default:**
```js
{
limit: 2,
methods: [
'GET',
'PUT',
'HEAD',
'DELETE',
'OPTIONS',
'TRACE',
'QUERY'
],
statusCodes: [
408,
413,
429,
500,
502,
503,
504,
521,
522,
524
],
errorCodes: [
'ETIMEDOUT',
'ECONNRESET',
'EADDRINUSE',
'ECONNREFUSED',
'EPIPE',
'ENOTFOUND',
'ENETUNREACH',
'EAI_AGAIN'
],
maxRetryAfter: undefined,
calculateDelay: ({computedValue}) => computedValue,
backoffLimit: Number.POSITIVE_INFINITY,
noise: 100
}
```
This option represents the `retry` object.
#### `limit`
**Type: `number`**
The maximum retry count.
#### `methods`
**Type: `string[]`**
The allowed methods to retry on.
**Note:**
> - By default, Got does not retry on `POST`.
#### `statusCodes`
**Type: `number[]`**
**Note:**
> - Only [**unsuccessful**](8-errors.md#) requests are retried. In order to retry successful requests, use an [`afterResponse`](9-hooks.md#afterresponse) hook.
The allowed [HTTP status codes](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status) to retry on.
#### `errorCodes`
**Type: `string[]`**
The allowed error codes to retry on.
- `ETIMEDOUT` - One of the [timeout limits](6-timeout.md) was reached.
- `ECONNRESET`- The connection was forcibly closed.
- `EADDRINUSE`- Could not bind to any free port.
- `ECONNREFUSED`- The connection was refused by the server.
- `EPIPE` - The remote side of the stream being written has been closed.
- `ENOTFOUND` - Could not resolve the hostname to an IP address.
- `ENETUNREACH` - No internet connection.
- `EAI_AGAIN` - DNS lookup timed out.
#### `maxRetryAfter`
**Type: `number | undefined`**\
**Default: `options.timeout.request`**
The upper limit of [`retry-after` header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After). If `undefined`, it will use `options.timeout` as the value.
If the limit is exceeded, the request is aborted.
#### `calculateDelay`
**Type: `Function`**
```ts
(retryObject: RetryObject) => Promisable
```
```ts
interface RetryObject {
attemptCount: number;
retryOptions: RetryOptions;
error: RequestError;
computedValue: number;
retryAfter?: number;
}
```
The function used to calculate the delay before the next request is made. Returning `0` aborts the retry.
**Note:**
> - By default, retry rules are enforced before `calculateDelay` runs (`enforceRetryRules: true`), so this function is only called when a retry is allowed.
> - If you set `enforceRetryRules: false`, `calculateDelay` takes full control of retry behavior. In that mode, check `computedValue` and return `0` when it is `0` to preserve default retry safeguards.
**Tip:**
> - This is especially useful when you want to scale down the computed value.
```js
import got from 'got';
await got('https://httpbin.org/anything', {
retry: {
limit: 3,
calculateDelay: ({computedValue}) => {
// When computedValue is 0, the default logic says don't retry
// (limit exceeded, non-retryable error, etc.)
if (computedValue === 0) {
return 0;
}
// Scale down the delay
return computedValue / 10;
}
}
});
```
#### `backoffLimit`
**Type: `number`**
The upper limit of the `computedValue`.
By default, the `computedValue` is calculated in the following way:
```ts
((2 ** (attemptCount - 1)) * 1000) + noise
```
The delay increases exponentially.\
In order to prevent this, you can set this value to a fixed value, such as `1000`.
#### `noise`
**Type: `number`**
The maximum acceptable retry noise in the range of `-100` to `+100`.
import {errorMonitor} from 'node:events';
import {types} from 'node:util';
import type {ClientRequest, IncomingMessage} from 'node:http';
import type {Socket} from 'node:net';
import deferToConnect from './defer-to-connect.js';
type InitialConnectionTimings = {
dnsPhase: number;
tcpPhase: number;
tlsPhase?: number;
};
const getInitialConnectionTimings = (socket: Socket): InitialConnectionTimings | undefined => Reflect.get(socket, '__initial_connection_timings__');
const setInitialConnectionTimings = (socket: Socket, timings: InitialConnectionTimings): void => {
Reflect.set(socket, '__initial_connection_timings__', timings);
};
export type Timings = {
start: number;
socket?: number;
lookup?: number;
connect?: number;
secureConnect?: number;
upload?: number;
response?: number;
end?: number;
error?: number;
abort?: number;
phases: {
wait?: number;
dns?: number;
tcp?: number;
tls?: number;
request?: number;
firstByte?: number;
download?: number;
total?: number;
};
};
export type ClientRequestWithTimings = ClientRequest & {
timings?: Timings;
};
export type IncomingMessageWithTimings = IncomingMessage & {
timings?: Timings;
};
const timer = (request: ClientRequestWithTimings): Timings => {
if (request.timings) {
return request.timings;
}
const timings: Timings = {
start: Date.now(),
socket: undefined,
lookup: undefined,
connect: undefined,
secureConnect: undefined,
upload: undefined,
response: undefined,
end: undefined,
error: undefined,
abort: undefined,
phases: {
wait: undefined,
dns: undefined,
tcp: undefined,
tls: undefined,
request: undefined,
firstByte: undefined,
download: undefined,
total: undefined,
},
};
request.timings = timings;
const handleError = (origin: ClientRequest | IncomingMessage) => {
origin.once(errorMonitor, () => {
timings.error = Date.now();
timings.phases.total = timings.error - timings.start;
});
};
handleError(request);
const onAbort = () => {
timings.abort = Date.now();
timings.phases.total = timings.abort - timings.start;
};
request.prependOnceListener('abort', onAbort);
const onSocket = (socket: Socket) => {
timings.socket = Date.now();
timings.phases.wait = timings.socket - timings.start;
if (types.isProxy(socket)) {
// HTTP/2: The socket is a proxy, so connection events won't fire.
// We can't measure connection timings, so leave them undefined.
// This prevents NaN in phases.request calculation.
return;
}
// Check if socket is already connected (reused from connection pool)
const socketAlreadyConnected = socket.writable && !socket.connecting;
if (socketAlreadyConnected) {
// Socket reuse detected: the socket was already connected from a previous request.
// For reused sockets, set all connection timestamps to socket time since no new
// connection was made for THIS request. But preserve phase durations from the
// original connection so they're not lost.
timings.lookup = timings.socket;
timings.connect = timings.socket;
const initialConnectionTimings = getInitialConnectionTimings(socket);
if (initialConnectionTimings) {
// Restore the phase timings from the initial connection
timings.phases.dns = initialConnectionTimings.dnsPhase;
timings.phases.tcp = initialConnectionTimings.tcpPhase;
timings.phases.tls = initialConnectionTimings.tlsPhase;
// Set secureConnect timestamp if there was TLS
if (timings.phases.tls !== undefined) {
timings.secureConnect = timings.socket;
}
} else {
// Socket reused but no initial timings stored (e.g., from external code)
// Set phases to 0
timings.phases.dns = 0;
timings.phases.tcp = 0;
}
return;
}
const lookupListener = () => {
timings.lookup = Date.now();
timings.phases.dns = timings.lookup - timings.socket!;
};
socket.prependOnceListener('lookup', lookupListener);
deferToConnect(socket, {
connect() {
timings.connect = Date.now();
if (timings.lookup === undefined) {
// No DNS lookup occurred (e.g., connecting to an IP address directly)
// Set lookup to socket time (no time elapsed for DNS)
socket.removeListener('lookup', lookupListener);
timings.lookup = timings.socket!;
timings.phases.dns = 0;
}
timings.phases.tcp = timings.connect - timings.lookup;
// If lookup and connect happen at the EXACT same time (tcp = 0),
// DNS was served from cache and the dns value is just event loop overhead.
// Set dns to 0 to indicate no actual DNS resolution occurred.
// Fixes https://github.com/szmarczak/http-timer/issues/35
if (timings.phases.tcp === 0 && timings.phases.dns && timings.phases.dns > 0) {
timings.phases.dns = 0;
}
// Store connection phase timings on socket for potential reuse
if (!getInitialConnectionTimings(socket)) {
setInitialConnectionTimings(socket, {
dnsPhase: timings.phases.dns!,
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion -- TypeScript can't prove this is defined due to callback structure
tcpPhase: timings.phases.tcp!,
});
}
},
secureConnect() {
timings.secureConnect = Date.now();
timings.phases.tls = timings.secureConnect - timings.connect!;
// Update stored timings with TLS phase timing
const initialConnectionTimings = getInitialConnectionTimings(socket);
if (initialConnectionTimings) {
initialConnectionTimings.tlsPhase = timings.phases.tls;
}
},
});
};
if (request.socket) {
onSocket(request.socket);
} else {
request.prependOnceListener('socket', onSocket);
}
const onUpload = () => {
timings.upload = Date.now();
// Calculate request phase if we have connection timings
const secureOrConnect = timings.secureConnect ?? timings.connect;
if (secureOrConnect !== undefined) {
timings.phases.request = timings.upload - secureOrConnect;
}
// If both are undefined (HTTP/2), phases.request stays undefined (not NaN)
};
if (request.writableFinished) {
onUpload();
} else {
request.prependOnceListener('finish', onUpload);
}
request.prependOnceListener('response', (response: IncomingMessageWithTimings) => {
timings.response = Date.now();
timings.phases.firstByte = timings.response - timings.upload!;
response.timings = timings;
handleError(response);
response.prependOnceListener('end', () => {
request.off('abort', onAbort);
response.off('aborted', onAbort);
if (timings.phases.total !== undefined) {
// Aborted or errored
return;
}
timings.end = Date.now();
timings.phases.download = timings.end - timings.response!;
timings.phases.total = timings.end - timings.start;
});
response.prependOnceListener('aborted', onAbort);
});
return timings;
};
export default timer;
'use strict'
var express = require('../')
, request = require('supertest')
, assert = require('node:assert');
var utils = require('./support/utils');
describe('res', function(){
describe('.jsonp(object)', function(){
it('should respond with jsonp', function(done){
var app = express();
app.use(function(req, res){
res.jsonp({ count: 1 });
});
request(app)
.get('/?callback=something')
.expect('Content-Type', 'text/javascript; charset=utf-8')
.expect(200, /something\(\{"count":1\}\);/, done);
})
it('should use first callback parameter with jsonp', function(done){
var app = express();
app.use(function(req, res){
res.jsonp({ count: 1 });
});
request(app)
.get('/?callback=something&callback=somethingelse')
.expect('Content-Type', 'text/javascript; charset=utf-8')
.expect(200, /something\(\{"count":1\}\);/, done);
})
it('should ignore object callback parameter with jsonp', function(done){
var app = express();
app.use(function(req, res){
res.jsonp({ count: 1 });
});
request(app)
.get('/?callback[a]=something')
.expect('Content-Type', 'application/json; charset=utf-8')
.expect(200, '{"count":1}', done)
})
it('should allow renaming callback', function(done){
var app = express();
app.set('jsonp callback name', 'clb');
app.use(function(req, res){
res.jsonp({ count: 1 });
});
request(app)
.get('/?clb=something')
.expect('Content-Type', 'text/javascript; charset=utf-8')
.expect(200, /something\(\{"count":1\}\);/, done);
})
it('should allow []', function(done){
var app = express();
app.use(function(req, res){
res.jsonp({ count: 1 });
});
request(app)
.get('/?callback=callbacks[123]')
.expect('Content-Type', 'text/javascript; charset=utf-8')
.expect(200, /callbacks\[123\]\(\{"count":1\}\);/, done);
})
it('should disallow arbitrary js', function(done){
var app = express();
app.use(function(req, res){
res.jsonp({});
});
request(app)
.get('/?callback=foo;bar()')
.expect('Content-Type', 'text/javascript; charset=utf-8')
.expect(200, /foobar\(\{\}\);/, done);
})
it('should escape utf whitespace', function(done){
var app = express();
app.use(function(req, res){
res.jsonp({ str: '\u2028 \u2029 woot' });
});
request(app)
.get('/?callback=foo')
.expect('Content-Type', 'text/javascript; charset=utf-8')
.expect(200, /foo\(\{"str":"\\u2028 \\u2029 woot"\}\);/, done);
});
it('should not escape utf whitespace for json fallback', function(done){
var app = express();
app.use(function(req, res){
res.jsonp({ str: '\u2028 \u2029 woot' });
});
request(app)
.get('/')
.expect('Content-Type', 'application/json; charset=utf-8')
.expect(200, '{"str":"\u2028 \u2029 woot"}', done);
});
it('should include security header and prologue', function (done) {
var app = express();
app.use(function(req, res){
res.jsonp({ count: 1 });
});
request(app)
.get('/?callback=something')
.expect('Content-Type', 'text/javascript; charset=utf-8')
.expect('X-Content-Type-Options', 'nosniff')
.expect(200, /^\/\*\*\//, done);
})
it('should not override previous Content-Types with no callback', function(done){
var app = express();
app.get('/', function(req, res){
res.type('application/vnd.example+json');
res.jsonp({ hello: 'world' });
});
request(app)
.get('/')
.expect('Content-Type', 'application/vnd.example+json; charset=utf-8')
.expect(utils.shouldNotHaveHeader('X-Content-Type-Options'))
.expect(200, '{"hello":"world"}', done);
})
it('should override previous Content-Types with callback', function(done){
var app = express();
app.get('/', function(req, res){
res.type('application/vnd.example+json');
res.jsonp({ hello: 'world' });
});
request(app)
.get('/?callback=cb')
.expect('Content-Type', 'text/javascript; charset=utf-8')
.expect('X-Content-Type-Options', 'nosniff')
.expect(200, /cb\(\{"hello":"world"\}\);$/, done);
})
describe('when given undefined', function () {
it('should invoke callback with no arguments', function (done) {
var app = express()
app.use(function (req, res) {
res.jsonp(undefined)
})
request(app)
.get('/?callback=cb')
.expect('Content-Type', 'text/javascript; charset=utf-8')
.expect(200, /cb\(\)/, done)
})
})
describe('when given null', function () {
it('should invoke callback with null', function (done) {
var app = express()
app.use(function (req, res) {
res.jsonp(null)
})
request(app)
.get('/?callback=cb')
.expect('Content-Type', 'text/javascript; charset=utf-8')
.expect(200, /cb\(null\)/, done)
})
})
describe('when given a string', function () {
it('should invoke callback with a string', function (done) {
var app = express()
app.use(function (req, res) {
res.jsonp('tobi')
})
request(app)
.get('/?callback=cb')
.expect('Content-Type', 'text/javascript; charset=utf-8')
.expect(200, /cb\("tobi"\)/, done)
})
})
describe('when given a number', function () {
it('should invoke callback with a number', function (done) {
var app = express()
app.use(function (req, res) {
res.jsonp(42)
})
request(app)
.get('/?callback=cb')
.expect('Content-Type', 'text/javascript; charset=utf-8')
.expect(200, /cb\(42\)/, done)
})
})
describe('when given an array', function () {
it('should invoke callback with an array', function (done) {
var app = express()
app.use(function (req, res) {
res.jsonp(['foo', 'bar', 'baz'])
})
request(app)
.get('/?callback=cb')
.expect('Content-Type', 'text/javascript; charset=utf-8')
.expect(200, /cb\(\["foo","bar","baz"\]\)/, done)
})
})
describe('when given an object', function () {
it('should invoke callback with an object', function (done) {
var app = express()
app.use(function (req, res) {
res.jsonp({ name: 'tobi' })
})
request(app)
.get('/?callback=cb')
.expect('Content-Type', 'text/javascript; charset=utf-8')
.expect(200, /cb\(\{"name":"tobi"\}\)/, done)
})
})
describe('"json escape" setting', function () {
it('should be undefined by default', function () {
var app = express()
assert.strictEqual(app.get('json escape'), undefined)
})
it('should unicode escape HTML-sniffing characters', function (done) {
var app = express()
app.enable('json escape')
app.use(function (req, res) {
res.jsonp({ '&': '\u2028