├── .eslintrc.json
├── .gitignore
├── .prettierrc
├── .travis.yml
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── jest.eslint.config.js
├── jest.test.config.js
├── package.json
├── src
├── clean.js
├── comments.js
├── index.js
├── options.js
├── parser.js
├── printer.js
└── util.js
├── tests
├── ast-nodes
│ ├── assignment-statement
│ │ ├── __snapshots__
│ │ │ └── jsfmt.spec.js.snap
│ │ ├── jsfmt.spec.js
│ │ └── main.lua
│ ├── binary-expression
│ │ ├── __snapshots__
│ │ │ └── jsfmt.spec.js.snap
│ │ ├── jsfmt.spec.js
│ │ └── main.lua
│ ├── break-statement
│ │ ├── __snapshots__
│ │ │ └── jsfmt.spec.js.snap
│ │ ├── jsfmt.spec.js
│ │ └── main.lua
│ ├── call-statement
│ │ ├── __snapshots__
│ │ │ └── jsfmt.spec.js.snap
│ │ ├── jsfmt.spec.js
│ │ └── main.lua
│ ├── do-statement
│ │ ├── __snapshots__
│ │ │ └── jsfmt.spec.js.snap
│ │ ├── jsfmt.spec.js
│ │ └── main.lua
│ ├── for-generic-statement
│ │ ├── __snapshots__
│ │ │ └── jsfmt.spec.js.snap
│ │ ├── jsfmt.spec.js
│ │ └── main.lua
│ ├── for-numeric-statement
│ │ ├── __snapshots__
│ │ │ └── jsfmt.spec.js.snap
│ │ ├── jsfmt.spec.js
│ │ └── main.lua
│ ├── function-statement
│ │ ├── __snapshots__
│ │ │ └── jsfmt.spec.js.snap
│ │ ├── jsfmt.spec.js
│ │ └── main.lua
│ ├── goto-statement
│ │ ├── __snapshots__
│ │ │ └── jsfmt.spec.js.snap
│ │ ├── jsfmt.spec.js
│ │ └── main.lua
│ ├── identifier
│ │ ├── __snapshots__
│ │ │ └── jsfmt.spec.js.snap
│ │ ├── jsfmt.spec.js
│ │ └── main.lua
│ ├── if-statement
│ │ ├── __snapshots__
│ │ │ └── jsfmt.spec.js.snap
│ │ ├── jsfmt.spec.js
│ │ └── main.lua
│ ├── index-expression
│ │ ├── __snapshots__
│ │ │ └── jsfmt.spec.js.snap
│ │ ├── jsfmt.spec.js
│ │ └── main.lua
│ ├── label-statement
│ │ ├── __snapshots__
│ │ │ └── jsfmt.spec.js.snap
│ │ ├── jsfmt.spec.js
│ │ └── main.lua
│ ├── literals
│ │ ├── __snapshots__
│ │ │ └── jsfmt.spec.js.snap
│ │ ├── jsfmt.spec.js
│ │ └── main.lua
│ ├── local-statement
│ │ ├── __snapshots__
│ │ │ └── jsfmt.spec.js.snap
│ │ ├── jsfmt.spec.js
│ │ └── main.lua
│ ├── member-expression
│ │ ├── __snapshots__
│ │ │ └── jsfmt.spec.js.snap
│ │ ├── jsfmt.spec.js
│ │ └── main.lua
│ ├── repeat-statement
│ │ ├── __snapshots__
│ │ │ └── jsfmt.spec.js.snap
│ │ ├── jsfmt.spec.js
│ │ └── main.lua
│ ├── return-statement
│ │ ├── __snapshots__
│ │ │ └── jsfmt.spec.js.snap
│ │ ├── jsfmt.spec.js
│ │ └── main.lua
│ ├── tables
│ │ ├── __snapshots__
│ │ │ └── jsfmt.spec.js.snap
│ │ ├── jsfmt.spec.js
│ │ └── main.lua
│ ├── unary-expression
│ │ ├── __snapshots__
│ │ │ └── jsfmt.spec.js.snap
│ │ ├── jsfmt.spec.js
│ │ └── main.lua
│ └── while-statement
│ │ ├── __snapshots__
│ │ └── jsfmt.spec.js.snap
│ │ ├── jsfmt.spec.js
│ │ └── main.lua
├── comments
│ ├── __snapshots__
│ │ └── jsfmt.spec.js.snap
│ ├── empty_with_comment.lua
│ ├── jsfmt.spec.js
│ ├── main.lua
│ └── prettier-ignore.lua
├── examples
│ ├── BUSTED_LICENSE
│ ├── busted
│ │ ├── TAP.lua
│ │ ├── __snapshots__
│ │ │ └── jsfmt.spec.js.snap
│ │ ├── ar.lua
│ │ ├── async_spec.lua
│ │ ├── base.lua
│ │ ├── block.lua
│ │ ├── cl_error_messages.lua
│ │ ├── cl_errors.lua
│ │ ├── cl_execute_fail.lua
│ │ ├── cl_failing_support.lua
│ │ ├── cl_filter.lua
│ │ ├── cl_gc_error.lua
│ │ ├── cl_helper_script.lua
│ │ ├── cl_list.lua
│ │ ├── cl_lua_path.lua
│ │ ├── cl_output_handler.lua
│ │ ├── cl_pending.lua
│ │ ├── cl_random_seed.lua
│ │ ├── cl_randomize.lua
│ │ ├── cl_sort.lua
│ │ ├── cl_spec.lua
│ │ ├── cl_standalone.lua
│ │ ├── cl_success.lua
│ │ ├── cl_tags.lua
│ │ ├── cl_test_module.lua
│ │ ├── cl_two_failures.lua
│ │ ├── cli.lua
│ │ ├── cli_spec.lua
│ │ ├── compatibility.lua
│ │ ├── configuration_loader.lua
│ │ ├── configuration_loader_spec.lua
│ │ ├── context.lua
│ │ ├── core.lua
│ │ ├── core_spec.lua
│ │ ├── de.lua
│ │ ├── done.lua
│ │ ├── en.lua
│ │ ├── environment.lua
│ │ ├── es.lua
│ │ ├── execute.lua
│ │ ├── execution_order_sync_spec.lua
│ │ ├── export_spec.lua
│ │ ├── expose_file1.lua
│ │ ├── expose_file2.lua
│ │ ├── file_context_support_spec.lua
│ │ ├── file_loader_spec.lua
│ │ ├── file_randomize_spec.lua
│ │ ├── filter_loader.lua
│ │ ├── fr.lua
│ │ ├── gtest.lua
│ │ ├── helper_loader.lua
│ │ ├── init.lua
│ │ ├── insulate-expose_spec.lua
│ │ ├── insulate_file1.lua
│ │ ├── insulate_file2.lua
│ │ ├── interface_spec.lua
│ │ ├── it.lua
│ │ ├── ja.lua
│ │ ├── jsfmt.spec.js
│ │ ├── json.lua
│ │ ├── junit.lua
│ │ ├── lua.lua
│ │ ├── luacov.lua
│ │ ├── luacov_spec.lua
│ │ ├── moonscript.lua
│ │ ├── nl.lua
│ │ ├── options.lua
│ │ ├── output_handler_loader.lua
│ │ ├── output_handler_loader_spec.lua
│ │ ├── plainTerminal.lua
│ │ ├── pt-BR.lua
│ │ ├── randomize_spec.lua
│ │ ├── ru.lua
│ │ ├── runner.lua
│ │ ├── sound.lua
│ │ ├── standalone_loader.lua
│ │ ├── status.lua
│ │ ├── strict.lua
│ │ ├── strict_spec.lua
│ │ ├── terra.lua
│ │ ├── test_file_loader.lua
│ │ ├── th.lua
│ │ ├── ua.lua
│ │ ├── utfTerminal.lua
│ │ ├── utils.lua
│ │ └── zh.lua
│ ├── misc
│ │ ├── __snapshots__
│ │ │ └── jsfmt.spec.js.snap
│ │ ├── hook.lua
│ │ ├── jsfmt.spec.js
│ │ ├── local_with_call_near_print_width.lua
│ │ └── simple_return.lua
│ └── using-busted
│ │ ├── __snapshots__
│ │ └── jsfmt.spec.js.snap
│ │ ├── jsfmt.spec.js
│ │ └── main.lua
├── semicolons
│ ├── __snapshots__
│ │ └── jsfmt.spec.js.snap
│ ├── jsfmt.spec.js
│ └── main.lua
└── unnecessary-parens
│ ├── __snapshots__
│ └── jsfmt.spec.js.snap
│ ├── jsfmt.spec.js
│ └── main.lua
├── tests_config
├── raw-serializer.js
└── run_spec.js
└── yarn.lock
/.eslintrc.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": ["unobtrusive", "unobtrusive/import"],
3 | "plugins": ["prettier"],
4 | "env": {
5 | "es6": true,
6 | "node": true,
7 | "jest": true
8 | },
9 | "rules": {
10 | "prettier/prettier": "warn"
11 | },
12 | "overrides": [
13 | {
14 | "files": "tests/**/*.js",
15 | "globals": {
16 | "run_spec": true
17 | }
18 | }
19 | ]
20 | }
21 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
2 | *.log
3 | /test.py
4 | /.vscode
5 | .DS_Store
6 | coverage
7 | .idea
8 | __pycache__/
9 | *.pyc
10 | *.swp
11 |
--------------------------------------------------------------------------------
/.prettierrc:
--------------------------------------------------------------------------------
1 | {
2 | "trailingComma": "es5",
3 | "arrowParens": "always"
4 | }
5 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | ---
2 | language: node_js
3 | node_js:
4 | - 10
5 | - 12
6 | cache:
7 | yarn: true
8 | directories:
9 | - node_modules
10 | install:
11 | - yarn install
12 | script:
13 | - AST_COMPARE=1 yarn test -- --runInBand
14 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing to Prettier for Lua
2 |
3 | To get up and running, install the dependencies and run the tests:
4 |
5 | ```bash
6 | yarn
7 | yarn test
8 | ```
9 |
10 | Here's what you need to know about the tests:
11 |
12 | * The tests use [Jest](https://facebook.github.io/jest/) snapshots.
13 | * You can make changes and run `jest -u` (or `yarn test -u`) to update the snapshots. Then run `git diff` to take a look at what changed. Always update the snapshots when opening a PR.
14 | * You can run `AST_COMPARE=1 yarn test` for a more robust test run. That formats each file, re-parses it, and compares the new AST with the original one and makes sure they are semantically equivalent.
15 | * If you would like to debug prettier locally, you can either debug it in node or the browser. The easiest way to debug it in the browser is to run the interactive `docs` REPL locally. The easiest way to debug it in node, is to create a local test file and run it in an editor like VS Code.
16 |
17 | Run `yarn lint --fix` to automatically format files.
18 |
19 | If you can, take look at [commands.md](commands.md) and check out [Wadler's paper](http://homepages.inf.ed.ac.uk/wadler/papers/prettier/prettier.pdf) to understand how Prettier works.
20 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Copyright 2018 Suchipi, SpiralP
2 |
3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4 |
5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6 |
7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
8 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 | 🚧 Not Actively Maintained 🚧
3 |
4 |
5 |
6 |

8 |

10 |
11 |
12 | Prettier Lua Plugin
13 |
14 | ## Unfinished
15 |
16 | Please note that this plugin is currently unfinished. We don't recommend it for production use.
17 |
18 | ## Intro
19 |
20 | Prettier is an opinionated code formatter. It enforces a consistent style by parsing your code and re-printing it with its own rules that take the maximum line length into account, wrapping code when necessary.
21 |
22 | This plugin adds support for the Lua language to Prettier.
23 |
24 | ### Input
25 |
26 | ```lua
27 | function deepcopy(orig)
28 | local orig_type = type(orig)
29 | local copy
30 |
31 | if orig_type == 'table' then; copy = {}
32 | for orig_key, orig_value in next, orig, nil do
33 | copy[deepcopy(orig_key)] = deepcopy(orig_value)
34 | end
35 | setmetatable(
36 | copy,
37 | deepcopy(
38 | getmetatable(orig)))
39 | else
40 | copy = orig
41 | end
42 | return copy
43 | end
44 | ```
45 |
46 | ### Output
47 |
48 | ```lua
49 | function deepcopy(orig)
50 | local orig_type = type(orig)
51 | local copy
52 |
53 | if orig_type == "table" then
54 | copy = {}
55 | for orig_key, orig_value in next, orig, nil do
56 | copy[deepcopy(orig_key)] = deepcopy(orig_value)
57 | end
58 | setmetatable(copy, deepcopy(getmetatable(orig)))
59 | else
60 | copy = orig
61 | end
62 | return copy
63 | end
64 | ```
65 |
66 | ## Install
67 |
68 | yarn:
69 |
70 | ```bash
71 | yarn add --dev prettier @prettier/plugin-lua
72 | # or globally
73 | yarn global add prettier @prettier/plugin-lua
74 | ```
75 |
76 | npm:
77 |
78 | ```bash
79 | npm install --save-dev prettier @prettier/plugin-lua
80 | # or globally
81 | npm install --global prettier @prettier/plugin-lua
82 | ```
83 |
84 | ## Use
85 |
86 | If you installed prettier as a local dependency, you can add prettier as a script in your `package.json`,
87 |
88 | ```json
89 | "scripts": {
90 | "prettier": "prettier"
91 | }
92 | ```
93 |
94 | also add it as a plugin to your [prettierrc](https://prettier.io/docs/en/configuration.html),
95 |
96 | ```json
97 | "plugins": [
98 | "@prettier/plugin-lua"
99 | ]
100 | ```
101 |
102 | and then run it via
103 |
104 | ```bash
105 | yarn run prettier path/to/file.lua --write
106 | # or
107 | npm run prettier -- path/to/file.lua --write
108 | ```
109 |
110 | If you installed globally, run
111 |
112 | ```bash
113 | prettier path/to/file.lua --write
114 | ```
115 |
116 | ## Editor integration
117 |
118 | Integration in the prettier plugin for your favorite editor might not be working yet, see the related issues for [VS Code](https://github.com/prettier/prettier-vscode/issues/395), [Atom](https://github.com/prettier/prettier-atom/issues/395) and [Vim](https://github.com/prettier/vim-prettier/issues/119).
119 |
120 | For the moment, you can set up prettier to run on save like this:
121 |
122 | ### Atom
123 |
124 | Install [save-autorun](https://atom.io/packages/save-autorun) and create a `.save.cson` file in your project with the following content:
125 |
126 | ```cson
127 | "**/*.lua": "prettier ${path} --write"
128 | ```
129 |
130 | ### VScode
131 |
132 | Install [Run on Save](https://marketplace.visualstudio.com/items?itemName=emeraldwalk.RunOnSave) and add the following section to your settings:
133 |
134 | ```json
135 | "emeraldwalk.runonsave": {
136 | "commands": [
137 | {
138 | "match": "\\.lua$",
139 | "cmd": "prettier ${file} --write"
140 | }
141 | ]
142 | }
143 | ```
144 |
145 | ### Vim
146 |
147 | Adding the following to `.vimrc` will define a custom command `:PrettierLua` that runs the plugin while preserving the cursor position and run it on save.
148 |
149 | ```vim
150 | " Prettier for Lua
151 | function PrettierLuaCursor()
152 | let save_pos = getpos(".")
153 | %! prettier --stdin --parser=lua
154 | call setpos('.', save_pos)
155 | endfunction
156 | " define custom command
157 | command PrettierLua call PrettierLuaCursor()
158 | " format on save
159 | autocmd BufwritePre *.lua PrettierLua
160 | ```
161 |
162 | ### Sublime Text
163 |
164 | Install [JsPrettier](https://packagecontrol.io/packages/JsPrettier) using [Package Control](https://packagecontrol.io/installation) and add the following to your `.sublime-project` project-level file:
165 |
166 | ```
167 | {
168 | "settings": {
169 | "js_prettier": {
170 | "auto_format_on_save": true,
171 | "custom_file_extensions": ["lua"],
172 | }
173 | }
174 | }
175 |
176 | ```
177 |
178 | Alternatively, `"custom_file_extensions": ["lua"]` can be added to the JsPrettier plugin user settings.
179 |
180 | ## Contributing
181 |
182 | If you're interested in contributing to the development of Prettier for Lua, you can follow the [CONTRIBUTING guide from Prettier](https://github.com/prettier/prettier/blob/master/CONTRIBUTING.md), as it all applies to this repository too.
183 |
184 | To test it out on a Lua file:
185 |
186 | - Clone this repository.
187 | - Run `yarn`.
188 | - Create a file called `test.lua`.
189 | - Run `yarn prettier test.lua` to check the output.
190 |
--------------------------------------------------------------------------------
/jest.eslint.config.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 |
3 | module.exports = {
4 | runner: "jest-runner-eslint",
5 | displayName: "lint",
6 | testMatch: ["/**/*.js"],
7 | testPathIgnorePatterns: ["node_modules/"]
8 | };
9 |
--------------------------------------------------------------------------------
/jest.test.config.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 |
3 | const ENABLE_COVERAGE = false; // !!process.env.CI;
4 |
5 | module.exports = {
6 | displayName: "test",
7 | setupFiles: ["/tests_config/run_spec.js"],
8 | snapshotSerializers: ["/tests_config/raw-serializer.js"],
9 | testRegex: "jsfmt\\.spec\\.js$|__tests__/.*\\.js$",
10 | testPathIgnorePatterns: [],
11 | collectCoverage: ENABLE_COVERAGE,
12 | collectCoverageFrom: ["src/**/*.js", "!/node_modules/"],
13 | transform: {}
14 | };
15 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "@prettier/plugin-lua",
3 | "version": "0.0.3",
4 | "description": "Prettier Lua Plugin",
5 | "repository": "prettier/plugin-lua",
6 | "author": "Suchipi ",
7 | "license": "MIT",
8 | "main": "src",
9 | "engines": {
10 | "node": ">=10.13.0"
11 | },
12 | "files": [
13 | "src"
14 | ],
15 | "dependencies": {
16 | "luaparse": "0.2.1"
17 | },
18 | "devDependencies": {
19 | "cross-env": "^7.0.2",
20 | "eslint": "^7.7.0",
21 | "eslint-config-unobtrusive": "^1.2.5",
22 | "eslint-plugin-import": "^2.22.0",
23 | "eslint-plugin-prettier": "^3.1.4",
24 | "jest": "^24.9.0",
25 | "jest-runner-eslint": "^0.10.0",
26 | "prettier": "^2.1.1"
27 | },
28 | "peerDependencies": {
29 | "prettier": ">=2.0.0"
30 | },
31 | "scripts": {
32 | "test": "cross-env AST_COMPARE=1 jest",
33 | "test:watch": "cross-env AST_COMPARE=1 jest --watchAll --updateSnapshot",
34 | "prettier": "prettier --plugin=. --parser=lua"
35 | },
36 | "jest": {
37 | "projects": [
38 | "/jest.*.config.js"
39 | ]
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/src/clean.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 | const { isValidIdentifier } = require("./util");
3 |
4 | /**
5 | * This function takes the existing ast node and a copy, by reference
6 | * We use it for testing, so that we can compare pre-post versions of the AST,
7 | * excluding things we don't care about (like node location, case that will be
8 | * changed by the printer, etc.)
9 | */
10 | function clean(node, newObj, parent) {
11 | if (
12 | node.type === "TableKey" &&
13 | node.key.type === "StringLiteral" &&
14 | isValidIdentifier(node.key.value)
15 | ) {
16 | // we convert TableKeys to TableKeyStrings
17 | return {
18 | type: "TableKeyString",
19 | key: { type: "Identifier", name: node.key.value },
20 | value: node.value,
21 | };
22 | }
23 |
24 | // We remove parens when it's safe to do so
25 | delete newObj.inParens;
26 | }
27 |
28 | module.exports = clean;
29 |
--------------------------------------------------------------------------------
/src/comments.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 |
3 | const {
4 | addLeadingComment,
5 | addDanglingComment,
6 | addTrailingComment,
7 | } = require("prettier").util;
8 | const { concat, join, indent, hardline } = require("prettier").doc.builders;
9 | const { isValidIdentifier, isExpression } = require("./util");
10 |
11 | // https://github.com/prettier/prettier/blob/c052d9c0866025c6af1cf2e5ef086f53dc3effff/src/main/comments.js#L335
12 | function printComment(commentPath, options) {
13 | const comment = commentPath.getValue();
14 | comment.printed = true;
15 |
16 | return comment.raw;
17 | }
18 |
19 | // https://github.com/prettier/prettier/blob/c052d9c0866025c6af1cf2e5ef086f53dc3effff/src/main/comments.js#L440
20 | function printDanglingComments(path, options, sameIndent, filter) {
21 | const parts = [];
22 | const node = path.getValue();
23 |
24 | if (!node || !node.comments) {
25 | return "";
26 | }
27 |
28 | path.each((commentPath) => {
29 | const comment = commentPath.getValue();
30 | if (
31 | comment &&
32 | !comment.leading &&
33 | !comment.trailing &&
34 | (!filter || filter(comment))
35 | ) {
36 | parts.push(printComment(commentPath, options));
37 | }
38 | }, "comments");
39 |
40 | if (parts.length === 0) {
41 | return "";
42 | }
43 |
44 | if (sameIndent) {
45 | return join(hardline, parts);
46 | }
47 | return indent(concat([hardline, join(hardline, parts)]));
48 | }
49 |
50 | /*
51 | Comment functions are meant to inspect various edge cases using given comment nodes,
52 | with information about where those comment nodes exist in the tree (ie enclosingNode,
53 | previousNode, followingNode), and then either call the built in functions to handle
54 | certain cases (ie addLeadingComment, addTrailingComment, addDanglingComment), or just
55 | let prettier core handle them. To signal that the plugin is taking over, the comment
56 | handler function should return true, otherwise returning false signals that prettier
57 | core should handle the comment
58 |
59 | args:
60 | comment
61 | text
62 | options
63 | ast
64 | isLastComment
65 | */
66 |
67 | const handleComments = {
68 | ownLine(comment, text, options, ast, isLastComment) {
69 | return (
70 | handleCommentInEmptyBody(comment, text, options, ast, isLastComment) ||
71 | false
72 | );
73 | },
74 | endOfLine(comment, text, options, ast, isLastComment) {
75 | return false;
76 | },
77 | remaining(comment, text, options, ast, isLastComment) {
78 | return false;
79 | },
80 | };
81 |
82 | function handleCommentInEmptyBody(comment, text, options, ast, isLastComment) {
83 | if (
84 | comment.enclosingNode &&
85 | comment.enclosingNode.body &&
86 | comment.enclosingNode.body.length === 0
87 | ) {
88 | addDanglingComment(comment.enclosingNode, comment);
89 | return true;
90 | }
91 |
92 | return false;
93 | }
94 |
95 | function canAttachComment(node) {
96 | return true;
97 | }
98 |
99 | function getCommentChildNodes(node) {
100 | const children = [];
101 | Object.keys(node).forEach((key) => {
102 | const value = node[key];
103 | if (value == null) return;
104 | if (key === "range") return;
105 | if (key === "comments") return;
106 |
107 | if (typeof value === "object") {
108 | if (value.type) {
109 | children.push(value);
110 | } else if (Array.isArray(value)) {
111 | value.forEach((node, key) => {
112 | children.push(node);
113 | });
114 | }
115 | }
116 | });
117 |
118 | return children;
119 | }
120 |
121 | function isDanglingComment(comment) {
122 | return !comment.leading && !comment.trailing;
123 | }
124 |
125 | function isLeadingComment(comment) {
126 | return comment.leading;
127 | }
128 |
129 | function isTrailingComment(comment) {
130 | return comment.trailing;
131 | }
132 |
133 | function isBlockComment(comment) {
134 | return /^\-\-\[=*\[/.test(comment.raw);
135 | }
136 |
137 | function commentsHavePrettierIgnore(comments) {
138 | return comments.find(comment =>
139 | comment.value.includes("prettier-ignore")
140 | )
141 | }
142 |
143 | module.exports = {
144 | handleComments,
145 | printDanglingComments,
146 | getCommentChildNodes,
147 | canAttachComment,
148 | printComment,
149 | isDanglingComment,
150 | isLeadingComment,
151 | isTrailingComment,
152 | isBlockComment,
153 | commentsHavePrettierIgnore,
154 | };
155 |
--------------------------------------------------------------------------------
/src/index.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 |
3 | const parse = require("./parser");
4 | const print = require("./printer");
5 | const options = require("./options");
6 | const clean = require("./clean");
7 | const {
8 | handleComments,
9 | getCommentChildNodes,
10 | canAttachComment,
11 | printComment,
12 | isBlockComment,
13 | } = require("./comments");
14 |
15 | const languages = [
16 | {
17 | name: "Lua",
18 | parsers: ["lua"],
19 | tmScope: "source.lua",
20 | aceMode: "lua",
21 | codemirrorMode: "lua",
22 | extensions: [".lua", ".fcgi", ".nse", ".p8", ".pd_lua", ".rbxs", ".wlua"],
23 | filenames: [],
24 | vscodeLanguageIds: ["lua"],
25 | linguistLanguageId: 213,
26 | },
27 | ];
28 |
29 | const parsers = {
30 | lua: {
31 | parse,
32 | astFormat: "luaparse",
33 | locStart: function locStart(node) {
34 | return node.range[0];
35 | },
36 | locEnd: function locEnd(node) {
37 | return node.range[1];
38 | },
39 | },
40 | };
41 |
42 | const printers = {
43 | luaparse: {
44 | print,
45 | massageAstNode: clean,
46 | handleComments,
47 | getCommentChildNodes,
48 | canAttachComment,
49 | printComment,
50 | isBlockComment,
51 | },
52 | };
53 |
54 | module.exports = {
55 | languages,
56 | printers,
57 | parsers,
58 | options,
59 | defaultOptions: {
60 | tabWidth: 4,
61 | useTabs: true,
62 | },
63 | };
64 |
--------------------------------------------------------------------------------
/src/options.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 |
3 | module.exports = {};
4 |
--------------------------------------------------------------------------------
/src/parser.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 | const luaparse = require("luaparse");
3 |
4 | function parse(text, parsers, options) {
5 | return luaparse.parse(text, {
6 | ranges: true,
7 | luaVersion: "5.3",
8 | });
9 | }
10 |
11 | module.exports = parse;
12 |
--------------------------------------------------------------------------------
/src/util.js:
--------------------------------------------------------------------------------
1 | function isValidIdentifier(str) {
2 | return !isKeyword(str) && Boolean(str.match(/^[A-Za-z_][A-Za-z_0-9]*$/));
3 | }
4 |
5 | function isKeyword(str) {
6 | switch (str) {
7 | case "do":
8 | case "if":
9 | case "in":
10 | case "or":
11 | case "and":
12 | case "end":
13 | case "for":
14 | case "nil":
15 | case "not":
16 | case "else":
17 | case "then":
18 | case "true":
19 | case "goto":
20 | case "break":
21 | case "false":
22 | case "local":
23 | case "until":
24 | case "while":
25 | case "elseif":
26 | case "repeat":
27 | case "return":
28 | case "function":
29 | return true;
30 | default:
31 | return false;
32 | }
33 | }
34 |
35 | function isExpression(node) {
36 | switch (node.type) {
37 | case "Identifier":
38 | case "CallExpression":
39 | case "TableCallExpression":
40 | case "StringCallExpression":
41 | case "BooleanLiteral":
42 | case "NilLiteral":
43 | case "NumericLiteral":
44 | case "StringLiteral":
45 | case "VarargLiteral":
46 | case "IndexExpression":
47 | case "MemberExpression":
48 | case "UnaryExpression":
49 | case "TableConstructorExpression": {
50 | return true;
51 | }
52 | case "FunctionDeclaration": {
53 | return node.identifier == null;
54 | }
55 | case "BinaryExpression":
56 | case "LogicalExpression": {
57 | return node.inParens;
58 | }
59 | }
60 | }
61 |
62 | module.exports = { isValidIdentifier, isExpression };
63 |
--------------------------------------------------------------------------------
/tests/ast-nodes/assignment-statement/__snapshots__/jsfmt.spec.js.snap:
--------------------------------------------------------------------------------
1 | // Jest Snapshot v1, https://goo.gl/fbAQLP
2 |
3 | exports[`main.lua - lua-verify: main.lua 1`] = `
4 | one = 1
5 |
6 | one, two = 1, 2
7 |
8 | one, two, three, four, five, size, seven, eight, nine, ten, eleven, twelve, thirteen = 6
9 |
10 | numbers = one, two, three, four, five, size, seven, eight, nine, ten, eleven, twelve, thirteen
11 |
12 | one, two, three, four, five, size, seven, eight, nine, ten, eleven, twelve, thirteen = one, two, three, four, five, size, seven, eight, nine, ten, eleven, twelve, thirteen
13 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
14 | one = 1
15 |
16 | one, two = 1, 2
17 |
18 | one,
19 | two,
20 | three,
21 | four,
22 | five,
23 | size,
24 | seven,
25 | eight,
26 | nine,
27 | ten,
28 | eleven,
29 | twelve,
30 | thirteen
31 | = 6
32 |
33 | numbers =
34 | one,
35 | two,
36 | three,
37 | four,
38 | five,
39 | size,
40 | seven,
41 | eight,
42 | nine,
43 | ten,
44 | eleven,
45 | twelve,
46 | thirteen
47 |
48 | one,
49 | two,
50 | three,
51 | four,
52 | five,
53 | size,
54 | seven,
55 | eight,
56 | nine,
57 | ten,
58 | eleven,
59 | twelve,
60 | thirteen
61 | =
62 | one,
63 | two,
64 | three,
65 | four,
66 | five,
67 | size,
68 | seven,
69 | eight,
70 | nine,
71 | ten,
72 | eleven,
73 | twelve,
74 | thirteen
75 |
76 | `;
77 |
78 | exports[`main.lua - lua-verify: main.lua 2`] = `
79 | one = 1
80 |
81 | one, two = 1, 2
82 |
83 | one, two, three, four, five, size, seven, eight, nine, ten, eleven, twelve, thirteen = 6
84 |
85 | numbers = one, two, three, four, five, size, seven, eight, nine, ten, eleven, twelve, thirteen
86 |
87 | one, two, three, four, five, size, seven, eight, nine, ten, eleven, twelve, thirteen = one, two, three, four, five, size, seven, eight, nine, ten, eleven, twelve, thirteen
88 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
89 | one = 1
90 |
91 | one, two = 1, 2
92 |
93 | one,
94 | two,
95 | three,
96 | four,
97 | five,
98 | size,
99 | seven,
100 | eight,
101 | nine,
102 | ten,
103 | eleven,
104 | twelve,
105 | thirteen
106 | = 6
107 |
108 | numbers =
109 | one,
110 | two,
111 | three,
112 | four,
113 | five,
114 | size,
115 | seven,
116 | eight,
117 | nine,
118 | ten,
119 | eleven,
120 | twelve,
121 | thirteen
122 |
123 | one,
124 | two,
125 | three,
126 | four,
127 | five,
128 | size,
129 | seven,
130 | eight,
131 | nine,
132 | ten,
133 | eleven,
134 | twelve,
135 | thirteen
136 | =
137 | one,
138 | two,
139 | three,
140 | four,
141 | five,
142 | size,
143 | seven,
144 | eight,
145 | nine,
146 | ten,
147 | eleven,
148 | twelve,
149 | thirteen
150 |
151 | `;
152 |
--------------------------------------------------------------------------------
/tests/ast-nodes/assignment-statement/jsfmt.spec.js:
--------------------------------------------------------------------------------
1 | run_spec(__dirname, ["lua"]);
2 | run_spec(__dirname, ["lua"], { trailingComma: "all", singleQuote: true });
3 |
--------------------------------------------------------------------------------
/tests/ast-nodes/assignment-statement/main.lua:
--------------------------------------------------------------------------------
1 | one = 1
2 |
3 | one, two = 1, 2
4 |
5 | one, two, three, four, five, size, seven, eight, nine, ten, eleven, twelve, thirteen = 6
6 |
7 | numbers = one, two, three, four, five, size, seven, eight, nine, ten, eleven, twelve, thirteen
8 |
9 | one, two, three, four, five, size, seven, eight, nine, ten, eleven, twelve, thirteen = one, two, three, four, five, size, seven, eight, nine, ten, eleven, twelve, thirteen
10 |
--------------------------------------------------------------------------------
/tests/ast-nodes/binary-expression/__snapshots__/jsfmt.spec.js.snap:
--------------------------------------------------------------------------------
1 | // Jest Snapshot v1, https://goo.gl/fbAQLP
2 |
3 | exports[`main.lua - lua-verify: main.lua 1`] = `
4 | logical_and = ja and no
5 | logical_or = ja or no
6 | mixed_logical = ja and no or yes or no and maybe
7 |
8 | binary_addition = 2 + 2
9 | binary_subtraction = 2 - 1
10 | binary_add_subtract_mixed = 2 + 2 - 1
11 |
12 | binary_mult = 2 * 2
13 | binary_divide = 2 / 2
14 | binary_modulo = 2 % 2
15 | binary_mult_divid = 2 * 2 / 2
16 |
17 | binary_oh_the_math = 2 + 2 - 1 * 6 / 6.23e-23 % 68
18 |
19 | bitshift_left = a << b
20 | bitshift_right = a >> b
21 | bitshift_mixed = a << b >> please_dont_do_this
22 |
23 | compare_lt = 2 < 3
24 | compare_gt = 3 > 2
25 | compare_le = 2 <= 3
26 | compare_ge = 3 >= 2
27 | compare_eq = 3 == 2
28 | compare_ne = 3 ~= 2
29 |
30 | big_compare = 2 < 3 > 4 <= 5 and 6 or 42 and 69 == 414
31 |
32 | hat = 2 ^ 4
33 | concat = "a" .. "b" .. c
34 |
35 | everything = yes and no or maybe + 1 - 2 * 3 / 4 % 5 << 6 >> 7 < 8 > 9 <= 10 >= 11 == 12 ~= 13 ^ "14" .. 15
36 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
37 | logical_and = ja and no
38 | logical_or = ja or no
39 | mixed_logical = ja and no or yes or no and maybe
40 |
41 | binary_addition = 2 + 2
42 | binary_subtraction = 2 - 1
43 | binary_add_subtract_mixed = 2 + 2 - 1
44 |
45 | binary_mult = 2 * 2
46 | binary_divide = 2 / 2
47 | binary_modulo = 2 % 2
48 | binary_mult_divid = 2 * 2 / 2
49 |
50 | binary_oh_the_math = 2 + 2 - 1 * 6 / 6.23e-23 % 68
51 |
52 | bitshift_left = a << b
53 | bitshift_right = a >> b
54 | bitshift_mixed = a << b >> please_dont_do_this
55 |
56 | compare_lt = 2 < 3
57 | compare_gt = 3 > 2
58 | compare_le = 2 <= 3
59 | compare_ge = 3 >= 2
60 | compare_eq = 3 == 2
61 | compare_ne = 3 ~= 2
62 |
63 | big_compare = 2 < 3 > 4 <= 5 and 6 or 42 and 69 == 414
64 |
65 | hat = 2 ^ 4
66 | concat = "a" .. "b" .. c
67 |
68 | everything =
69 | yes and no or maybe + 1 - 2 * 3 / 4 % 5 << 6 >> 7 < 8 > 9 <= 10 >= 11 == 12 ~= 13 ^ "14" .. 15
70 |
71 | `;
72 |
73 | exports[`main.lua - lua-verify: main.lua 2`] = `
74 | logical_and = ja and no
75 | logical_or = ja or no
76 | mixed_logical = ja and no or yes or no and maybe
77 |
78 | binary_addition = 2 + 2
79 | binary_subtraction = 2 - 1
80 | binary_add_subtract_mixed = 2 + 2 - 1
81 |
82 | binary_mult = 2 * 2
83 | binary_divide = 2 / 2
84 | binary_modulo = 2 % 2
85 | binary_mult_divid = 2 * 2 / 2
86 |
87 | binary_oh_the_math = 2 + 2 - 1 * 6 / 6.23e-23 % 68
88 |
89 | bitshift_left = a << b
90 | bitshift_right = a >> b
91 | bitshift_mixed = a << b >> please_dont_do_this
92 |
93 | compare_lt = 2 < 3
94 | compare_gt = 3 > 2
95 | compare_le = 2 <= 3
96 | compare_ge = 3 >= 2
97 | compare_eq = 3 == 2
98 | compare_ne = 3 ~= 2
99 |
100 | big_compare = 2 < 3 > 4 <= 5 and 6 or 42 and 69 == 414
101 |
102 | hat = 2 ^ 4
103 | concat = "a" .. "b" .. c
104 |
105 | everything = yes and no or maybe + 1 - 2 * 3 / 4 % 5 << 6 >> 7 < 8 > 9 <= 10 >= 11 == 12 ~= 13 ^ "14" .. 15
106 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
107 | logical_and = ja and no
108 | logical_or = ja or no
109 | mixed_logical = ja and no or yes or no and maybe
110 |
111 | binary_addition = 2 + 2
112 | binary_subtraction = 2 - 1
113 | binary_add_subtract_mixed = 2 + 2 - 1
114 |
115 | binary_mult = 2 * 2
116 | binary_divide = 2 / 2
117 | binary_modulo = 2 % 2
118 | binary_mult_divid = 2 * 2 / 2
119 |
120 | binary_oh_the_math = 2 + 2 - 1 * 6 / 6.23e-23 % 68
121 |
122 | bitshift_left = a << b
123 | bitshift_right = a >> b
124 | bitshift_mixed = a << b >> please_dont_do_this
125 |
126 | compare_lt = 2 < 3
127 | compare_gt = 3 > 2
128 | compare_le = 2 <= 3
129 | compare_ge = 3 >= 2
130 | compare_eq = 3 == 2
131 | compare_ne = 3 ~= 2
132 |
133 | big_compare = 2 < 3 > 4 <= 5 and 6 or 42 and 69 == 414
134 |
135 | hat = 2 ^ 4
136 | concat = 'a' .. 'b' .. c
137 |
138 | everything =
139 | yes and no or maybe + 1 - 2 * 3 / 4 % 5 << 6 >> 7 < 8 > 9 <= 10 >= 11 == 12 ~= 13 ^ '14' .. 15
140 |
141 | `;
142 |
--------------------------------------------------------------------------------
/tests/ast-nodes/binary-expression/jsfmt.spec.js:
--------------------------------------------------------------------------------
1 | run_spec(__dirname, ["lua"]);
2 | run_spec(__dirname, ["lua"], { trailingComma: "all", singleQuote: true });
3 |
--------------------------------------------------------------------------------
/tests/ast-nodes/binary-expression/main.lua:
--------------------------------------------------------------------------------
1 | logical_and = ja and no
2 | logical_or = ja or no
3 | mixed_logical = ja and no or yes or no and maybe
4 |
5 | binary_addition = 2 + 2
6 | binary_subtraction = 2 - 1
7 | binary_add_subtract_mixed = 2 + 2 - 1
8 |
9 | binary_mult = 2 * 2
10 | binary_divide = 2 / 2
11 | binary_modulo = 2 % 2
12 | binary_mult_divid = 2 * 2 / 2
13 |
14 | binary_oh_the_math = 2 + 2 - 1 * 6 / 6.23e-23 % 68
15 |
16 | bitshift_left = a << b
17 | bitshift_right = a >> b
18 | bitshift_mixed = a << b >> please_dont_do_this
19 |
20 | compare_lt = 2 < 3
21 | compare_gt = 3 > 2
22 | compare_le = 2 <= 3
23 | compare_ge = 3 >= 2
24 | compare_eq = 3 == 2
25 | compare_ne = 3 ~= 2
26 |
27 | big_compare = 2 < 3 > 4 <= 5 and 6 or 42 and 69 == 414
28 |
29 | hat = 2 ^ 4
30 | concat = "a" .. "b" .. c
31 |
32 | everything = yes and no or maybe + 1 - 2 * 3 / 4 % 5 << 6 >> 7 < 8 > 9 <= 10 >= 11 == 12 ~= 13 ^ "14" .. 15
33 |
--------------------------------------------------------------------------------
/tests/ast-nodes/break-statement/__snapshots__/jsfmt.spec.js.snap:
--------------------------------------------------------------------------------
1 | // Jest Snapshot v1, https://goo.gl/fbAQLP
2 |
3 | exports[`main.lua - lua-verify: main.lua 1`] = `
4 | break
5 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
6 | break
7 |
8 | `;
9 |
10 | exports[`main.lua - lua-verify: main.lua 2`] = `
11 | break
12 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
13 | break
14 |
15 | `;
16 |
--------------------------------------------------------------------------------
/tests/ast-nodes/break-statement/jsfmt.spec.js:
--------------------------------------------------------------------------------
1 | run_spec(__dirname, ["lua"]);
2 | run_spec(__dirname, ["lua"], { trailingComma: "all", singleQuote: true });
3 |
--------------------------------------------------------------------------------
/tests/ast-nodes/break-statement/main.lua:
--------------------------------------------------------------------------------
1 | break
2 |
--------------------------------------------------------------------------------
/tests/ast-nodes/call-statement/__snapshots__/jsfmt.spec.js.snap:
--------------------------------------------------------------------------------
1 | // Jest Snapshot v1, https://goo.gl/fbAQLP
2 |
3 | exports[`main.lua - lua-verify: main.lua 1`] = `
4 | foo()
5 |
6 | foo(one, two, three)
7 |
8 | foo(one, two, this_one_is_really_long_okay_like_so_long_look_at_this_wow, three, four)
9 |
10 | bar(67)(62)
11 |
12 | foo(function()
13 | print("hi")
14 | end)
15 |
16 | foo("a", "b", function()
17 | print("hi!!!")
18 | end)
19 |
20 | foo("a", "b", "dkjfldsjfkldsjfjdslfjdskjfdsjkfdsjfjdsfjkdjfkdsfdjfjkdsjkfjdslflksdfjlk", function()
21 | print("hi!!!")
22 | end)
23 |
24 | foo(function()
25 | print("first");
26 | end, function()
27 | print("second");
28 | end)
29 |
30 | foo({
31 | djfkdsjflkdjsfkljdsklfjsdlfklsdjfdsjf = "djfkdsjkfldjslkfldskxjlksjdklsklfkjldsjflsdk",
32 | dsjfkdjslkfjdslkfjdslkfjldsfkdls = "347584375897438957348957438957349",
33 | [3475837598734.3274892] = dfjkldsjflkdsfkljdslkfs,
34 | }, "a")
35 |
36 | foo({
37 | djfkdsjflkdjsfkljdsklfjsdlfklsdjfdsjf = "djfkdsjkfldjslkfldskxjlksjdklsklfkjldsjflsdk",
38 | dsjfkdjslkfjdslkfjdslkfjldsfkdls = "347584375897438957348957438957349",
39 | [3475837598734.3274892] = dfjkldsjflkdsfkljdslkfs,
40 | }, "a", function()
41 | print("hello?")
42 | end)
43 |
44 | bar{ a }
45 |
46 | bar"a"
47 |
48 | bar[[ a ]]
49 |
50 | bar[[
51 | a!!!
52 | ]]
53 |
54 | bar'a'
55 |
56 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
57 | foo()
58 |
59 | foo(one, two, three)
60 |
61 | foo(
62 | one,
63 | two,
64 | this_one_is_really_long_okay_like_so_long_look_at_this_wow,
65 | three,
66 | four
67 | )
68 |
69 | bar(67)(62)
70 |
71 | foo(function()
72 | print("hi")
73 | end)
74 |
75 | foo("a", "b", function()
76 | print("hi!!!")
77 | end)
78 |
79 | foo(
80 | "a",
81 | "b",
82 | "dkjfldsjfkldsjfjdslfjdskjfdsjkfdsjfjdsfjkdjfkdsfdjfjkdsjkfjdslflksdfjlk",
83 | function()
84 | print("hi!!!")
85 | end
86 | )
87 |
88 | foo(
89 | function()
90 | print("first")
91 | end,
92 | function()
93 | print("second")
94 | end
95 | )
96 |
97 | foo(
98 | {
99 | djfkdsjflkdjsfkljdsklfjsdlfklsdjfdsjf = "djfkdsjkfldjslkfldskxjlksjdklsklfkjldsjflsdk",
100 | dsjfkdjslkfjdslkfjdslkfjldsfkdls = "347584375897438957348957438957349",
101 | [3475837598734.3274892] = dfjkldsjflkdsfkljdslkfs
102 | },
103 | "a"
104 | )
105 |
106 | foo(
107 | {
108 | djfkdsjflkdjsfkljdsklfjsdlfklsdjfdsjf = "djfkdsjkfldjslkfldskxjlksjdklsklfkjldsjflsdk",
109 | dsjfkdjslkfjdslkfjdslkfjldsfkdls = "347584375897438957348957438957349",
110 | [3475837598734.3274892] = dfjkldsjflkdsfkljdslkfs
111 | },
112 | "a",
113 | function()
114 | print("hello?")
115 | end
116 | )
117 |
118 | bar{ a }
119 |
120 | bar"a"
121 |
122 | bar[[ a ]]
123 |
124 | bar[[
125 | a!!!
126 | ]]
127 |
128 | bar"a"
129 |
130 | `;
131 |
132 | exports[`main.lua - lua-verify: main.lua 2`] = `
133 | foo()
134 |
135 | foo(one, two, three)
136 |
137 | foo(one, two, this_one_is_really_long_okay_like_so_long_look_at_this_wow, three, four)
138 |
139 | bar(67)(62)
140 |
141 | foo(function()
142 | print("hi")
143 | end)
144 |
145 | foo("a", "b", function()
146 | print("hi!!!")
147 | end)
148 |
149 | foo("a", "b", "dkjfldsjfkldsjfjdslfjdskjfdsjkfdsjfjdsfjkdjfkdsfdjfjkdsjkfjdslflksdfjlk", function()
150 | print("hi!!!")
151 | end)
152 |
153 | foo(function()
154 | print("first");
155 | end, function()
156 | print("second");
157 | end)
158 |
159 | foo({
160 | djfkdsjflkdjsfkljdsklfjsdlfklsdjfdsjf = "djfkdsjkfldjslkfldskxjlksjdklsklfkjldsjflsdk",
161 | dsjfkdjslkfjdslkfjdslkfjldsfkdls = "347584375897438957348957438957349",
162 | [3475837598734.3274892] = dfjkldsjflkdsfkljdslkfs,
163 | }, "a")
164 |
165 | foo({
166 | djfkdsjflkdjsfkljdsklfjsdlfklsdjfdsjf = "djfkdsjkfldjslkfldskxjlksjdklsklfkjldsjflsdk",
167 | dsjfkdjslkfjdslkfjdslkfjldsfkdls = "347584375897438957348957438957349",
168 | [3475837598734.3274892] = dfjkldsjflkdsfkljdslkfs,
169 | }, "a", function()
170 | print("hello?")
171 | end)
172 |
173 | bar{ a }
174 |
175 | bar"a"
176 |
177 | bar[[ a ]]
178 |
179 | bar[[
180 | a!!!
181 | ]]
182 |
183 | bar'a'
184 |
185 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
186 | foo()
187 |
188 | foo(one, two, three)
189 |
190 | foo(
191 | one,
192 | two,
193 | this_one_is_really_long_okay_like_so_long_look_at_this_wow,
194 | three,
195 | four
196 | )
197 |
198 | bar(67)(62)
199 |
200 | foo(function()
201 | print('hi')
202 | end)
203 |
204 | foo('a', 'b', function()
205 | print('hi!!!')
206 | end)
207 |
208 | foo(
209 | 'a',
210 | 'b',
211 | 'dkjfldsjfkldsjfjdslfjdskjfdsjkfdsjfjdsfjkdjfkdsfdjfjkdsjkfjdslflksdfjlk',
212 | function()
213 | print('hi!!!')
214 | end
215 | )
216 |
217 | foo(
218 | function()
219 | print('first')
220 | end,
221 | function()
222 | print('second')
223 | end
224 | )
225 |
226 | foo(
227 | {
228 | djfkdsjflkdjsfkljdsklfjsdlfklsdjfdsjf = 'djfkdsjkfldjslkfldskxjlksjdklsklfkjldsjflsdk',
229 | dsjfkdjslkfjdslkfjdslkfjldsfkdls = '347584375897438957348957438957349',
230 | [3475837598734.3274892] = dfjkldsjflkdsfkljdslkfs,
231 | },
232 | 'a'
233 | )
234 |
235 | foo(
236 | {
237 | djfkdsjflkdjsfkljdsklfjsdlfklsdjfdsjf = 'djfkdsjkfldjslkfldskxjlksjdklsklfkjldsjflsdk',
238 | dsjfkdjslkfjdslkfjdslkfjldsfkdls = '347584375897438957348957438957349',
239 | [3475837598734.3274892] = dfjkldsjflkdsfkljdslkfs,
240 | },
241 | 'a',
242 | function()
243 | print('hello?')
244 | end
245 | )
246 |
247 | bar{ a }
248 |
249 | bar'a'
250 |
251 | bar[[ a ]]
252 |
253 | bar[[
254 | a!!!
255 | ]]
256 |
257 | bar'a'
258 |
259 | `;
260 |
--------------------------------------------------------------------------------
/tests/ast-nodes/call-statement/jsfmt.spec.js:
--------------------------------------------------------------------------------
1 | run_spec(__dirname, ["lua"]);
2 | run_spec(__dirname, ["lua"], { trailingComma: "all", singleQuote: true });
3 |
--------------------------------------------------------------------------------
/tests/ast-nodes/call-statement/main.lua:
--------------------------------------------------------------------------------
1 | foo()
2 |
3 | foo(one, two, three)
4 |
5 | foo(one, two, this_one_is_really_long_okay_like_so_long_look_at_this_wow, three, four)
6 |
7 | bar(67)(62)
8 |
9 | foo(function()
10 | print("hi")
11 | end)
12 |
13 | foo("a", "b", function()
14 | print("hi!!!")
15 | end)
16 |
17 | foo("a", "b", "dkjfldsjfkldsjfjdslfjdskjfdsjkfdsjfjdsfjkdjfkdsfdjfjkdsjkfjdslflksdfjlk", function()
18 | print("hi!!!")
19 | end)
20 |
21 | foo(function()
22 | print("first");
23 | end, function()
24 | print("second");
25 | end)
26 |
27 | foo({
28 | djfkdsjflkdjsfkljdsklfjsdlfklsdjfdsjf = "djfkdsjkfldjslkfldskxjlksjdklsklfkjldsjflsdk",
29 | dsjfkdjslkfjdslkfjdslkfjldsfkdls = "347584375897438957348957438957349",
30 | [3475837598734.3274892] = dfjkldsjflkdsfkljdslkfs,
31 | }, "a")
32 |
33 | foo({
34 | djfkdsjflkdjsfkljdsklfjsdlfklsdjfdsjf = "djfkdsjkfldjslkfldskxjlksjdklsklfkjldsjflsdk",
35 | dsjfkdjslkfjdslkfjdslkfjldsfkdls = "347584375897438957348957438957349",
36 | [3475837598734.3274892] = dfjkldsjflkdsfkljdslkfs,
37 | }, "a", function()
38 | print("hello?")
39 | end)
40 |
41 | bar{ a }
42 |
43 | bar"a"
44 |
45 | bar[[ a ]]
46 |
47 | bar[[
48 | a!!!
49 | ]]
50 |
51 | bar'a'
52 |
53 |
--------------------------------------------------------------------------------
/tests/ast-nodes/do-statement/__snapshots__/jsfmt.spec.js.snap:
--------------------------------------------------------------------------------
1 | // Jest Snapshot v1, https://goo.gl/fbAQLP
2 |
3 | exports[`main.lua - lua-verify: main.lua 1`] = `
4 | do end
5 |
6 | do
7 | end
8 |
9 | do
10 | print("just do it!")
11 | end~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
12 | do
13 | end
14 |
15 | do
16 | end
17 |
18 | do
19 | print("just do it!")
20 | end
21 |
22 | `;
23 |
24 | exports[`main.lua - lua-verify: main.lua 2`] = `
25 | do end
26 |
27 | do
28 | end
29 |
30 | do
31 | print("just do it!")
32 | end~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
33 | do
34 | end
35 |
36 | do
37 | end
38 |
39 | do
40 | print('just do it!')
41 | end
42 |
43 | `;
44 |
--------------------------------------------------------------------------------
/tests/ast-nodes/do-statement/jsfmt.spec.js:
--------------------------------------------------------------------------------
1 | run_spec(__dirname, ["lua"]);
2 | run_spec(__dirname, ["lua"], { trailingComma: "all", singleQuote: true });
3 |
--------------------------------------------------------------------------------
/tests/ast-nodes/do-statement/main.lua:
--------------------------------------------------------------------------------
1 | do end
2 |
3 | do
4 | end
5 |
6 | do
7 | print("just do it!")
8 | end
--------------------------------------------------------------------------------
/tests/ast-nodes/for-generic-statement/jsfmt.spec.js:
--------------------------------------------------------------------------------
1 | run_spec(__dirname, ["lua"]);
2 | run_spec(__dirname, ["lua"], { trailingComma: "all", singleQuote: true });
3 |
--------------------------------------------------------------------------------
/tests/ast-nodes/for-generic-statement/main.lua:
--------------------------------------------------------------------------------
1 | for k,v in pairs(i) do
2 | end
3 |
4 | for a,b,c,d,e,f,g,h,i,j,k,l in pairs(i) do
5 | end
6 |
7 | for a,b,c,d,e,f,g,h,i,j,k,l in m,n,o,p,q,r,s,t,u,v do
8 | end
9 |
10 | for file in pairs(files) do
11 | end
12 |
13 | for k, v in next, t do
14 | end
15 |
16 | for k in next, t do
17 | end
18 |
19 | for this_is_a_song_for_your_poor_sick_penguin_he_has_a_fever_and_his_toes_are_blue, but_if_i_sing_to_your_poor_sick_penguin_he_will_feel_better in a_day, or_two do
20 | end
21 |
22 | for this_is_a_song_for_your_poor_sick_penguin_he_has_a_fever_and_his_toes_are_blue_but_if_i_sing_to_your_poor_sick_penguin_he_will_feel_better in a_day_or_two do
23 | end
24 |
25 | for this_is in a_song_for_your_poor_sick_penguin_he_has_a_fever_and_his_toes_are_blue, but_if_i_sing_to_your_poor_sick_penguin_he_will_feel_better_in, a_day, or_two do
26 | end
27 |
28 | for k,v in pairs(i) do
29 | print("hi")
30 | end
31 |
32 | for a,b,c,d,e,f,g,h,i,j,k,l in pairs(i) do
33 | print("hi")
34 | end
35 |
36 | for a,b,c,d,e,f,g,h,i,j,k,l in m,n,o,p,q,r,s,t,u,v do
37 | print("hi")
38 | end
39 |
40 | for file in pairs(files) do
41 | print("hi")
42 | end
43 |
44 | for k, v in next, t do
45 | print("hi")
46 | end
47 |
48 | for k in next, t do
49 | print("hi")
50 | end
51 |
52 | for this_is_a_song_for_your_poor_sick_penguin_he_has_a_fever_and_his_toes_are_blue, but_if_i_sing_to_your_poor_sick_penguin_he_will_feel_better in a_day, or_two do
53 | print("hi")
54 | end
55 |
56 | for this_is_a_song_for_your_poor_sick_penguin_he_has_a_fever_and_his_toes_are_blue_but_if_i_sing_to_your_poor_sick_penguin_he_will_feel_better in a_day_or_two do
57 | print("hi")
58 | end
59 |
60 | for this_is in a_song_for_your_poor_sick_penguin_he_has_a_fever_and_his_toes_are_blue, but_if_i_sing_to_your_poor_sick_penguin_he_will_feel_better_in, a_day, or_two do
61 | print("hi")
62 | end
--------------------------------------------------------------------------------
/tests/ast-nodes/for-numeric-statement/__snapshots__/jsfmt.spec.js.snap:
--------------------------------------------------------------------------------
1 | // Jest Snapshot v1, https://goo.gl/fbAQLP
2 |
3 | exports[`main.lua - lua-verify: main.lua 1`] = `
4 | for i = 10, 20, 2 do
5 | end
6 |
7 | for i = 10, 20 do
8 | end
9 |
10 | for i = 100000000000000000000000000000000000000000000, 20000000000000000000000, 20000000000000 do
11 | end
12 |
13 | for i = 10, 20, 2 do
14 | print("hi")
15 | end
16 |
17 | for i = 10, 20 do
18 | print("hi")
19 | end
20 |
21 | for i = 100000000000000000000000000000000000000000000, 20000000000000000000000, 20000000000000 do
22 | print("hi")
23 | end
24 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
25 | for i = 10, 20, 2 do
26 | end
27 |
28 | for i = 10, 20 do
29 | end
30 |
31 | for i = 100000000000000000000000000000000000000000000, 20000000000000000000000, 20000000000000 do
32 | end
33 |
34 | for i = 10, 20, 2 do
35 | print("hi")
36 | end
37 |
38 | for i = 10, 20 do
39 | print("hi")
40 | end
41 |
42 | for i = 100000000000000000000000000000000000000000000, 20000000000000000000000, 20000000000000 do
43 | print("hi")
44 | end
45 |
46 | `;
47 |
48 | exports[`main.lua - lua-verify: main.lua 2`] = `
49 | for i = 10, 20, 2 do
50 | end
51 |
52 | for i = 10, 20 do
53 | end
54 |
55 | for i = 100000000000000000000000000000000000000000000, 20000000000000000000000, 20000000000000 do
56 | end
57 |
58 | for i = 10, 20, 2 do
59 | print("hi")
60 | end
61 |
62 | for i = 10, 20 do
63 | print("hi")
64 | end
65 |
66 | for i = 100000000000000000000000000000000000000000000, 20000000000000000000000, 20000000000000 do
67 | print("hi")
68 | end
69 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
70 | for i = 10, 20, 2 do
71 | end
72 |
73 | for i = 10, 20 do
74 | end
75 |
76 | for i = 100000000000000000000000000000000000000000000, 20000000000000000000000, 20000000000000 do
77 | end
78 |
79 | for i = 10, 20, 2 do
80 | print('hi')
81 | end
82 |
83 | for i = 10, 20 do
84 | print('hi')
85 | end
86 |
87 | for i = 100000000000000000000000000000000000000000000, 20000000000000000000000, 20000000000000 do
88 | print('hi')
89 | end
90 |
91 | `;
92 |
--------------------------------------------------------------------------------
/tests/ast-nodes/for-numeric-statement/jsfmt.spec.js:
--------------------------------------------------------------------------------
1 | run_spec(__dirname, ["lua"]);
2 | run_spec(__dirname, ["lua"], { trailingComma: "all", singleQuote: true });
3 |
--------------------------------------------------------------------------------
/tests/ast-nodes/for-numeric-statement/main.lua:
--------------------------------------------------------------------------------
1 | for i = 10, 20, 2 do
2 | end
3 |
4 | for i = 10, 20 do
5 | end
6 |
7 | for i = 100000000000000000000000000000000000000000000, 20000000000000000000000, 20000000000000 do
8 | end
9 |
10 | for i = 10, 20, 2 do
11 | print("hi")
12 | end
13 |
14 | for i = 10, 20 do
15 | print("hi")
16 | end
17 |
18 | for i = 100000000000000000000000000000000000000000000, 20000000000000000000000, 20000000000000 do
19 | print("hi")
20 | end
21 |
--------------------------------------------------------------------------------
/tests/ast-nodes/function-statement/jsfmt.spec.js:
--------------------------------------------------------------------------------
1 | run_spec(__dirname, ["lua"]);
2 | run_spec(__dirname, ["lua"], { trailingComma: "all", singleQuote: true });
3 |
--------------------------------------------------------------------------------
/tests/ast-nodes/function-statement/main.lua:
--------------------------------------------------------------------------------
1 | function empty()
2 | end
3 |
4 | function empty(one, two, three)
5 | end
6 |
7 | local function local_function()
8 | end
9 |
10 | (function()
11 | end)();
12 |
13 | (function(lots, und, lotta_lots, of, params, are, going, here, yup, thats, right, you, know, it)
14 | end)()
15 |
16 | function empty(lots, und, lotta_lots, of, params, are, going, here, yup, thats, right)
17 | end
18 |
19 | function META:doIt()
20 | end
21 |
22 | function META:doIt(lots, und, lotta_lots, of, params, are, going, here, yup, thats, right)
23 | end
24 |
25 | function response.parse()
26 | end
27 |
28 | function response.parse(lots, und, lotta_lots, of, params, are, going, here, yup, thats, right)
29 | end
30 |
31 | function empty()
32 | print("hi!")
33 | end
34 |
35 | function empty(one, two, three)
36 | print("hi!")
37 | end
38 |
39 | local function local_function()
40 | print("hi!")
41 | end
42 |
43 | (function()
44 | print("hi!")
45 | end)();
46 |
47 | (function(lots, und, lotta_lots, of, params, are, going, here, yup, thats, right, you, know, it)
48 | print("hi!")
49 | end)()
50 |
51 | function empty(lots, und, lotta_lots, of, params, are, going, here, yup, thats, right)
52 | print("hi!")
53 | end
54 |
55 | function META:doIt()
56 | print("hi!")
57 | end
58 |
59 | function META:doIt(lots, und, lotta_lots, of, params, are, going, here, yup, thats, right)
60 | print("hi!")
61 | end
62 |
63 | function response.parse()
64 | print("hi!")
65 | end
66 |
67 | function response.parse(lots, und, lotta_lots, of, params, are, going, here, yup, thats, right)
68 | print("hi!")
69 | end
70 |
71 | function empty()
72 |
73 |
74 |
75 |
76 |
77 | print("hi!")
78 |
79 |
80 |
81 |
82 | print("hi!")
83 |
84 |
85 |
86 | end
87 |
88 | function empty(one, two, three)
89 |
90 |
91 |
92 |
93 |
94 | print("hi!")
95 |
96 |
97 |
98 |
99 | print("hi!")
100 |
101 |
102 |
103 | end
104 |
105 | local function local_function()
106 |
107 |
108 |
109 |
110 |
111 | print("hi!")
112 |
113 |
114 |
115 |
116 | print("hi!")
117 |
118 |
119 |
120 | end
121 |
122 | (function()
123 |
124 |
125 |
126 |
127 |
128 | print("hi!")
129 |
130 |
131 |
132 |
133 | print("hi!")
134 |
135 |
136 |
137 | end)();
138 |
139 | (function(lots, und, lotta_lots, of, params, are, going, here, yup, thats, right, you, know, it)
140 |
141 |
142 |
143 |
144 |
145 | print("hi!")
146 |
147 |
148 |
149 |
150 | print("hi!")
151 |
152 |
153 |
154 | end)()
155 |
156 | function empty(lots, und, lotta_lots, of, params, are, going, here, yup, thats, right)
157 |
158 |
159 |
160 |
161 |
162 | print("hi!")
163 |
164 |
165 |
166 |
167 | print("hi!")
168 |
169 |
170 |
171 | end
172 |
173 | function META:doIt()
174 |
175 |
176 |
177 |
178 |
179 | print("hi!")
180 |
181 |
182 |
183 |
184 | print("hi!")
185 |
186 |
187 |
188 | end
189 |
190 | function META:doIt(lots, und, lotta_lots, of, params, are, going, here, yup, thats, right)
191 |
192 |
193 |
194 |
195 |
196 | print("hi!")
197 |
198 |
199 |
200 |
201 | print("hi!")
202 |
203 |
204 |
205 | end
206 |
207 | function response.parse()
208 |
209 |
210 |
211 |
212 |
213 | print("hi!")
214 |
215 |
216 |
217 |
218 | print("hi!")
219 |
220 |
221 |
222 | end
223 |
224 | function response.parse(lots, und, lotta_lots, of, params, are, going, here, yup, thats, right)
225 |
226 |
227 |
228 |
229 |
230 | print("hi!")
231 |
232 |
233 |
234 |
235 | print("hi!")
236 |
237 |
238 |
239 | end
240 |
--------------------------------------------------------------------------------
/tests/ast-nodes/goto-statement/__snapshots__/jsfmt.spec.js.snap:
--------------------------------------------------------------------------------
1 | // Jest Snapshot v1, https://goo.gl/fbAQLP
2 |
3 | exports[`main.lua - lua-verify: main.lua 1`] = `
4 | goto label
5 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
6 | goto label
7 |
8 | `;
9 |
10 | exports[`main.lua - lua-verify: main.lua 2`] = `
11 | goto label
12 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
13 | goto label
14 |
15 | `;
16 |
--------------------------------------------------------------------------------
/tests/ast-nodes/goto-statement/jsfmt.spec.js:
--------------------------------------------------------------------------------
1 | run_spec(__dirname, ["lua"]);
2 | run_spec(__dirname, ["lua"], { trailingComma: "all", singleQuote: true });
3 |
--------------------------------------------------------------------------------
/tests/ast-nodes/goto-statement/main.lua:
--------------------------------------------------------------------------------
1 | goto label
2 |
--------------------------------------------------------------------------------
/tests/ast-nodes/identifier/__snapshots__/jsfmt.spec.js.snap:
--------------------------------------------------------------------------------
1 | // Jest Snapshot v1, https://goo.gl/fbAQLP
2 |
3 | exports[`main.lua - lua-verify: main.lua 1`] = `
4 | call(identifier)
5 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
6 | call(identifier)
7 |
8 | `;
9 |
10 | exports[`main.lua - lua-verify: main.lua 2`] = `
11 | call(identifier)
12 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
13 | call(identifier)
14 |
15 | `;
16 |
--------------------------------------------------------------------------------
/tests/ast-nodes/identifier/jsfmt.spec.js:
--------------------------------------------------------------------------------
1 | run_spec(__dirname, ["lua"]);
2 | run_spec(__dirname, ["lua"], { trailingComma: "all", singleQuote: true });
3 |
--------------------------------------------------------------------------------
/tests/ast-nodes/identifier/main.lua:
--------------------------------------------------------------------------------
1 | call(identifier)
2 |
--------------------------------------------------------------------------------
/tests/ast-nodes/if-statement/__snapshots__/jsfmt.spec.js.snap:
--------------------------------------------------------------------------------
1 | // Jest Snapshot v1, https://goo.gl/fbAQLP
2 |
3 | exports[`main.lua - lua-verify: main.lua 1`] = `
4 | if condition then
5 | print("condition")
6 | end
7 |
8 | if condition1 then
9 | print("condition1")
10 | elseif condition2 then
11 | print("condition2")
12 | end
13 |
14 | if condition_outer then
15 | print("condition_outer")
16 | else if condition2 then
17 | print("condition_inner")
18 | end
19 | end
20 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
21 | if condition then
22 | print("condition")
23 | end
24 |
25 | if condition1 then
26 | print("condition1")
27 | elseif condition2 then
28 | print("condition2")
29 | end
30 |
31 | if condition_outer then
32 | print("condition_outer")
33 | else
34 | if condition2 then
35 | print("condition_inner")
36 | end
37 | end
38 |
39 | `;
40 |
41 | exports[`main.lua - lua-verify: main.lua 2`] = `
42 | if condition then
43 | print("condition")
44 | end
45 |
46 | if condition1 then
47 | print("condition1")
48 | elseif condition2 then
49 | print("condition2")
50 | end
51 |
52 | if condition_outer then
53 | print("condition_outer")
54 | else if condition2 then
55 | print("condition_inner")
56 | end
57 | end
58 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
59 | if condition then
60 | print('condition')
61 | end
62 |
63 | if condition1 then
64 | print('condition1')
65 | elseif condition2 then
66 | print('condition2')
67 | end
68 |
69 | if condition_outer then
70 | print('condition_outer')
71 | else
72 | if condition2 then
73 | print('condition_inner')
74 | end
75 | end
76 |
77 | `;
78 |
--------------------------------------------------------------------------------
/tests/ast-nodes/if-statement/jsfmt.spec.js:
--------------------------------------------------------------------------------
1 | run_spec(__dirname, ["lua"]);
2 | run_spec(__dirname, ["lua"], { trailingComma: "all", singleQuote: true });
3 |
--------------------------------------------------------------------------------
/tests/ast-nodes/if-statement/main.lua:
--------------------------------------------------------------------------------
1 | if condition then
2 | print("condition")
3 | end
4 |
5 | if condition1 then
6 | print("condition1")
7 | elseif condition2 then
8 | print("condition2")
9 | end
10 |
11 | if condition_outer then
12 | print("condition_outer")
13 | else if condition2 then
14 | print("condition_inner")
15 | end
16 | end
17 |
--------------------------------------------------------------------------------
/tests/ast-nodes/index-expression/__snapshots__/jsfmt.spec.js.snap:
--------------------------------------------------------------------------------
1 | // Jest Snapshot v1, https://goo.gl/fbAQLP
2 |
3 | exports[`main.lua - lua-verify: main.lua 1`] = `
4 | tbl[a] = 5
5 | tbl["a"] = 5
6 | tbl[42.6] = 5
7 | tbl["loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"] = 6
8 | tbl[bcdefgh] = 7
9 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
10 | tbl[a] = 5
11 | tbl["a"] = 5
12 | tbl[42.6] = 5
13 | tbl["loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]
14 | = 6
15 | tbl[bcdefgh] = 7
16 |
17 | `;
18 |
19 | exports[`main.lua - lua-verify: main.lua 2`] = `
20 | tbl[a] = 5
21 | tbl["a"] = 5
22 | tbl[42.6] = 5
23 | tbl["loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"] = 6
24 | tbl[bcdefgh] = 7
25 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
26 | tbl[a] = 5
27 | tbl['a'] = 5
28 | tbl[42.6] = 5
29 | tbl['loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong']
30 | = 6
31 | tbl[bcdefgh] = 7
32 |
33 | `;
34 |
--------------------------------------------------------------------------------
/tests/ast-nodes/index-expression/jsfmt.spec.js:
--------------------------------------------------------------------------------
1 | run_spec(__dirname, ["lua"]);
2 | run_spec(__dirname, ["lua"], { trailingComma: "all", singleQuote: true });
3 |
--------------------------------------------------------------------------------
/tests/ast-nodes/index-expression/main.lua:
--------------------------------------------------------------------------------
1 | tbl[a] = 5
2 | tbl["a"] = 5
3 | tbl[42.6] = 5
4 | tbl["loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"] = 6
5 | tbl[bcdefgh] = 7
6 |
--------------------------------------------------------------------------------
/tests/ast-nodes/label-statement/__snapshots__/jsfmt.spec.js.snap:
--------------------------------------------------------------------------------
1 | // Jest Snapshot v1, https://goo.gl/fbAQLP
2 |
3 | exports[`main.lua - lua-verify: main.lua 1`] = `
4 | ::label::
5 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
6 | ::label::
7 |
8 | `;
9 |
10 | exports[`main.lua - lua-verify: main.lua 2`] = `
11 | ::label::
12 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
13 | ::label::
14 |
15 | `;
16 |
--------------------------------------------------------------------------------
/tests/ast-nodes/label-statement/jsfmt.spec.js:
--------------------------------------------------------------------------------
1 | run_spec(__dirname, ["lua"]);
2 | run_spec(__dirname, ["lua"], { trailingComma: "all", singleQuote: true });
3 |
--------------------------------------------------------------------------------
/tests/ast-nodes/label-statement/main.lua:
--------------------------------------------------------------------------------
1 | ::label::
2 |
--------------------------------------------------------------------------------
/tests/ast-nodes/literals/__snapshots__/jsfmt.spec.js.snap:
--------------------------------------------------------------------------------
1 | // Jest Snapshot v1, https://goo.gl/fbAQLP
2 |
3 | exports[`main.lua - lua-verify: main.lua 1`] = `
4 | single_quoted_string = 'single-quoted string literal'
5 | double_quoted_string = "string literal!"
6 |
7 | multi_line_string = [[
8 | multi-line string literal!!
9 | ]]
10 | single_line_multi_line = [[ one ]]
11 | weird_multi_line = [=====[
12 | one
13 | ]=====]
14 | weird_single_line_multi_line = [=====[
15 | stuff goes here y'all
16 | ]=====]
17 |
18 | weird_escapes = "'"
19 | weird_escapes = '"'
20 |
21 | weird_escapes = "\\""
22 | weird_escapes = '\\''
23 |
24 | weird_escapes = '\\"'
25 | weird_escapes = "\\'"
26 |
27 |
28 | hex_escapes = "\\x00 \\x02"
29 | octal_escapes = "\\777 \\650"
30 | ascii_escapes = "\\b\\n\\t\\\\"
31 |
32 | numeric_literal_int = 42
33 | numeric_literal_float = 42.0
34 | hex_number = 0x64
35 | hex_number_upper = 0XFF
36 | scientific_notation_lower = 1.6e50
37 | scientific_notation_upper = 6.23E-23
38 |
39 | truthy = true
40 | falsy = false
41 |
42 | nillish = nil
43 |
44 | vararg = ...
45 | vararg_parens = (...)
46 |
47 | function vararg_params(...)
48 | end
49 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
50 | single_quoted_string = "single-quoted string literal"
51 | double_quoted_string = "string literal!"
52 |
53 | multi_line_string = [[
54 | multi-line string literal!!
55 | ]]
56 | single_line_multi_line = [[ one ]]
57 | weird_multi_line = [=====[
58 | one
59 | ]=====]
60 | weird_single_line_multi_line = [=====[
61 | stuff goes here y'all
62 | ]=====]
63 |
64 | weird_escapes = "'"
65 | weird_escapes = '"'
66 |
67 | weird_escapes = '"'
68 | weird_escapes = "'"
69 |
70 | weird_escapes = '"'
71 | weird_escapes = "'"
72 |
73 | hex_escapes = "\\x00 \\x02"
74 | octal_escapes = "\\777 \\650"
75 | ascii_escapes = "\\b\\n\\t\\\\"
76 |
77 | numeric_literal_int = 42
78 | numeric_literal_float = 42.0
79 | hex_number = 0x64
80 | hex_number_upper = 0XFF
81 | scientific_notation_lower = 1.6e50
82 | scientific_notation_upper = 6.23E-23
83 |
84 | truthy = true
85 | falsy = false
86 |
87 | nillish = nil
88 |
89 | vararg = ...
90 | vararg_parens = ...
91 |
92 | function vararg_params(...)
93 | end
94 |
95 | `;
96 |
97 | exports[`main.lua - lua-verify: main.lua 2`] = `
98 | single_quoted_string = 'single-quoted string literal'
99 | double_quoted_string = "string literal!"
100 |
101 | multi_line_string = [[
102 | multi-line string literal!!
103 | ]]
104 | single_line_multi_line = [[ one ]]
105 | weird_multi_line = [=====[
106 | one
107 | ]=====]
108 | weird_single_line_multi_line = [=====[
109 | stuff goes here y'all
110 | ]=====]
111 |
112 | weird_escapes = "'"
113 | weird_escapes = '"'
114 |
115 | weird_escapes = "\\""
116 | weird_escapes = '\\''
117 |
118 | weird_escapes = '\\"'
119 | weird_escapes = "\\'"
120 |
121 |
122 | hex_escapes = "\\x00 \\x02"
123 | octal_escapes = "\\777 \\650"
124 | ascii_escapes = "\\b\\n\\t\\\\"
125 |
126 | numeric_literal_int = 42
127 | numeric_literal_float = 42.0
128 | hex_number = 0x64
129 | hex_number_upper = 0XFF
130 | scientific_notation_lower = 1.6e50
131 | scientific_notation_upper = 6.23E-23
132 |
133 | truthy = true
134 | falsy = false
135 |
136 | nillish = nil
137 |
138 | vararg = ...
139 | vararg_parens = (...)
140 |
141 | function vararg_params(...)
142 | end
143 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
144 | single_quoted_string = 'single-quoted string literal'
145 | double_quoted_string = 'string literal!'
146 |
147 | multi_line_string = [[
148 | multi-line string literal!!
149 | ]]
150 | single_line_multi_line = [[ one ]]
151 | weird_multi_line = [=====[
152 | one
153 | ]=====]
154 | weird_single_line_multi_line = [=====[
155 | stuff goes here y'all
156 | ]=====]
157 |
158 | weird_escapes = "'"
159 | weird_escapes = '"'
160 |
161 | weird_escapes = '"'
162 | weird_escapes = "'"
163 |
164 | weird_escapes = '"'
165 | weird_escapes = "'"
166 |
167 | hex_escapes = '\\x00 \\x02'
168 | octal_escapes = '\\777 \\650'
169 | ascii_escapes = '\\b\\n\\t\\\\'
170 |
171 | numeric_literal_int = 42
172 | numeric_literal_float = 42.0
173 | hex_number = 0x64
174 | hex_number_upper = 0XFF
175 | scientific_notation_lower = 1.6e50
176 | scientific_notation_upper = 6.23E-23
177 |
178 | truthy = true
179 | falsy = false
180 |
181 | nillish = nil
182 |
183 | vararg = ...
184 | vararg_parens = ...
185 |
186 | function vararg_params(...)
187 | end
188 |
189 | `;
190 |
--------------------------------------------------------------------------------
/tests/ast-nodes/literals/jsfmt.spec.js:
--------------------------------------------------------------------------------
1 | run_spec(__dirname, ["lua"]);
2 | run_spec(__dirname, ["lua"], { trailingComma: "all", singleQuote: true });
3 |
--------------------------------------------------------------------------------
/tests/ast-nodes/literals/main.lua:
--------------------------------------------------------------------------------
1 | single_quoted_string = 'single-quoted string literal'
2 | double_quoted_string = "string literal!"
3 |
4 | multi_line_string = [[
5 | multi-line string literal!!
6 | ]]
7 | single_line_multi_line = [[ one ]]
8 | weird_multi_line = [=====[
9 | one
10 | ]=====]
11 | weird_single_line_multi_line = [=====[
12 | stuff goes here y'all
13 | ]=====]
14 |
15 | weird_escapes = "'"
16 | weird_escapes = '"'
17 |
18 | weird_escapes = "\""
19 | weird_escapes = '\''
20 |
21 | weird_escapes = '\"'
22 | weird_escapes = "\'"
23 |
24 |
25 | hex_escapes = "\x00 \x02"
26 | octal_escapes = "\777 \650"
27 | ascii_escapes = "\b\n\t\\"
28 |
29 | numeric_literal_int = 42
30 | numeric_literal_float = 42.0
31 | hex_number = 0x64
32 | hex_number_upper = 0XFF
33 | scientific_notation_lower = 1.6e50
34 | scientific_notation_upper = 6.23E-23
35 |
36 | truthy = true
37 | falsy = false
38 |
39 | nillish = nil
40 |
41 | vararg = ...
42 | vararg_parens = (...)
43 |
44 | function vararg_params(...)
45 | end
46 |
--------------------------------------------------------------------------------
/tests/ast-nodes/local-statement/__snapshots__/jsfmt.spec.js.snap:
--------------------------------------------------------------------------------
1 | // Jest Snapshot v1, https://goo.gl/fbAQLP
2 |
3 | exports[`main.lua - lua-verify: main.lua 1`] = `
4 | local one = 1
5 |
6 | local one, two = 1, 2
7 |
8 | local one, two, three, four, five, size, seven, eight, nine, ten, eleven, twelve, thirteen = 6
9 |
10 | local numbers = one, two, three, four, five, size, seven, eight, nine, ten, eleven, twelve, thirteen
11 |
12 | local one, two, three, four, five, size, seven, eight, nine, ten, eleven, twelve, thirteen = one, two, three, four, five, size, seven, eight, nine, ten, eleven, twelve, thirteen
13 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
14 | local one = 1
15 |
16 | local one, two = 1, 2
17 |
18 | local one,
19 | two,
20 | three,
21 | four,
22 | five,
23 | size,
24 | seven,
25 | eight,
26 | nine,
27 | ten,
28 | eleven,
29 | twelve,
30 | thirteen
31 | = 6
32 |
33 | local numbers =
34 | one,
35 | two,
36 | three,
37 | four,
38 | five,
39 | size,
40 | seven,
41 | eight,
42 | nine,
43 | ten,
44 | eleven,
45 | twelve,
46 | thirteen
47 |
48 | local one,
49 | two,
50 | three,
51 | four,
52 | five,
53 | size,
54 | seven,
55 | eight,
56 | nine,
57 | ten,
58 | eleven,
59 | twelve,
60 | thirteen
61 | =
62 | one,
63 | two,
64 | three,
65 | four,
66 | five,
67 | size,
68 | seven,
69 | eight,
70 | nine,
71 | ten,
72 | eleven,
73 | twelve,
74 | thirteen
75 |
76 | `;
77 |
78 | exports[`main.lua - lua-verify: main.lua 2`] = `
79 | local one = 1
80 |
81 | local one, two = 1, 2
82 |
83 | local one, two, three, four, five, size, seven, eight, nine, ten, eleven, twelve, thirteen = 6
84 |
85 | local numbers = one, two, three, four, five, size, seven, eight, nine, ten, eleven, twelve, thirteen
86 |
87 | local one, two, three, four, five, size, seven, eight, nine, ten, eleven, twelve, thirteen = one, two, three, four, five, size, seven, eight, nine, ten, eleven, twelve, thirteen
88 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
89 | local one = 1
90 |
91 | local one, two = 1, 2
92 |
93 | local one,
94 | two,
95 | three,
96 | four,
97 | five,
98 | size,
99 | seven,
100 | eight,
101 | nine,
102 | ten,
103 | eleven,
104 | twelve,
105 | thirteen
106 | = 6
107 |
108 | local numbers =
109 | one,
110 | two,
111 | three,
112 | four,
113 | five,
114 | size,
115 | seven,
116 | eight,
117 | nine,
118 | ten,
119 | eleven,
120 | twelve,
121 | thirteen
122 |
123 | local one,
124 | two,
125 | three,
126 | four,
127 | five,
128 | size,
129 | seven,
130 | eight,
131 | nine,
132 | ten,
133 | eleven,
134 | twelve,
135 | thirteen
136 | =
137 | one,
138 | two,
139 | three,
140 | four,
141 | five,
142 | size,
143 | seven,
144 | eight,
145 | nine,
146 | ten,
147 | eleven,
148 | twelve,
149 | thirteen
150 |
151 | `;
152 |
--------------------------------------------------------------------------------
/tests/ast-nodes/local-statement/jsfmt.spec.js:
--------------------------------------------------------------------------------
1 | run_spec(__dirname, ["lua"]);
2 | run_spec(__dirname, ["lua"], { trailingComma: "all", singleQuote: true });
3 |
--------------------------------------------------------------------------------
/tests/ast-nodes/local-statement/main.lua:
--------------------------------------------------------------------------------
1 | local one = 1
2 |
3 | local one, two = 1, 2
4 |
5 | local one, two, three, four, five, size, seven, eight, nine, ten, eleven, twelve, thirteen = 6
6 |
7 | local numbers = one, two, three, four, five, size, seven, eight, nine, ten, eleven, twelve, thirteen
8 |
9 | local one, two, three, four, five, size, seven, eight, nine, ten, eleven, twelve, thirteen = one, two, three, four, five, size, seven, eight, nine, ten, eleven, twelve, thirteen
10 |
--------------------------------------------------------------------------------
/tests/ast-nodes/member-expression/__snapshots__/jsfmt.spec.js.snap:
--------------------------------------------------------------------------------
1 | // Jest Snapshot v1, https://goo.gl/fbAQLP
2 |
3 | exports[`main.lua - lua-verify: main.lua 1`] = `
4 | tbl.a = 5
5 | tbl.a().b().c().d().e()
6 | tbl.loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong = 6
7 |
8 | noParens = bar:call()
9 | yesParens = ("bar"):call()
10 | yesParens = ({}):call()
11 | yesParens = (1.9e1):call()
12 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
13 | tbl.a = 5
14 | tbl.a().b().c().d().e()
15 | tbl.loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong
16 | = 6
17 |
18 | noParens = bar:call()
19 | yesParens = ("bar"):call()
20 | yesParens = ({}):call()
21 | yesParens = (1.9e1):call()
22 |
23 | `;
24 |
25 | exports[`main.lua - lua-verify: main.lua 2`] = `
26 | tbl.a = 5
27 | tbl.a().b().c().d().e()
28 | tbl.loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong = 6
29 |
30 | noParens = bar:call()
31 | yesParens = ("bar"):call()
32 | yesParens = ({}):call()
33 | yesParens = (1.9e1):call()
34 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
35 | tbl.a = 5
36 | tbl.a().b().c().d().e()
37 | tbl.loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong
38 | = 6
39 |
40 | noParens = bar:call()
41 | yesParens = ('bar'):call()
42 | yesParens = ({}):call()
43 | yesParens = (1.9e1):call()
44 |
45 | `;
46 |
--------------------------------------------------------------------------------
/tests/ast-nodes/member-expression/jsfmt.spec.js:
--------------------------------------------------------------------------------
1 | run_spec(__dirname, ["lua"]);
2 | run_spec(__dirname, ["lua"], { trailingComma: "all", singleQuote: true });
3 |
--------------------------------------------------------------------------------
/tests/ast-nodes/member-expression/main.lua:
--------------------------------------------------------------------------------
1 | tbl.a = 5
2 | tbl.a().b().c().d().e()
3 | tbl.loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong = 6
4 |
5 | noParens = bar:call()
6 | yesParens = ("bar"):call()
7 | yesParens = ({}):call()
8 | yesParens = (1.9e1):call()
9 |
--------------------------------------------------------------------------------
/tests/ast-nodes/repeat-statement/__snapshots__/jsfmt.spec.js.snap:
--------------------------------------------------------------------------------
1 | // Jest Snapshot v1, https://goo.gl/fbAQLP
2 |
3 | exports[`main.lua - lua-verify: main.lua 1`] = `
4 | repeat until false
5 |
6 | repeat
7 | print("oh no!")
8 | until condition
9 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
10 | repeat
11 | until false
12 |
13 | repeat
14 | print("oh no!")
15 | until condition
16 |
17 | `;
18 |
19 | exports[`main.lua - lua-verify: main.lua 2`] = `
20 | repeat until false
21 |
22 | repeat
23 | print("oh no!")
24 | until condition
25 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
26 | repeat
27 | until false
28 |
29 | repeat
30 | print('oh no!')
31 | until condition
32 |
33 | `;
34 |
--------------------------------------------------------------------------------
/tests/ast-nodes/repeat-statement/jsfmt.spec.js:
--------------------------------------------------------------------------------
1 | run_spec(__dirname, ["lua"]);
2 | run_spec(__dirname, ["lua"], { trailingComma: "all", singleQuote: true });
3 |
--------------------------------------------------------------------------------
/tests/ast-nodes/repeat-statement/main.lua:
--------------------------------------------------------------------------------
1 | repeat until false
2 |
3 | repeat
4 | print("oh no!")
5 | until condition
6 |
--------------------------------------------------------------------------------
/tests/ast-nodes/return-statement/__snapshots__/jsfmt.spec.js.snap:
--------------------------------------------------------------------------------
1 | // Jest Snapshot v1, https://goo.gl/fbAQLP
2 |
3 | exports[`main.lua - lua-verify: main.lua 1`] = `
4 | function empty()
5 | return
6 | end
7 |
8 | function with_arg()
9 | return argument
10 | end
11 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
12 | function empty()
13 | return
14 | end
15 |
16 | function with_arg()
17 | return argument
18 | end
19 |
20 | `;
21 |
22 | exports[`main.lua - lua-verify: main.lua 2`] = `
23 | function empty()
24 | return
25 | end
26 |
27 | function with_arg()
28 | return argument
29 | end
30 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
31 | function empty()
32 | return
33 | end
34 |
35 | function with_arg()
36 | return argument
37 | end
38 |
39 | `;
40 |
--------------------------------------------------------------------------------
/tests/ast-nodes/return-statement/jsfmt.spec.js:
--------------------------------------------------------------------------------
1 | run_spec(__dirname, ["lua"]);
2 | run_spec(__dirname, ["lua"], { trailingComma: "all", singleQuote: true });
3 |
--------------------------------------------------------------------------------
/tests/ast-nodes/return-statement/main.lua:
--------------------------------------------------------------------------------
1 | function empty()
2 | return
3 | end
4 |
5 | function with_arg()
6 | return argument
7 | end
8 |
--------------------------------------------------------------------------------
/tests/ast-nodes/tables/jsfmt.spec.js:
--------------------------------------------------------------------------------
1 | run_spec(__dirname, ["lua"]);
2 | run_spec(__dirname, ["lua"], { trailingComma: "all", singleQuote: true });
3 | run_spec(__dirname, ["lua"], { bracketSpacing: false });
4 |
--------------------------------------------------------------------------------
/tests/ast-nodes/tables/main.lua:
--------------------------------------------------------------------------------
1 | empty = {}
2 |
3 | one_thing = { thing }
4 |
5 | one_keyed_thing = { keyed = thing }
6 |
7 | more_than_one_thing = { thing, thing }
8 |
9 | more_than_one_keyed_thing = {
10 | keyed = thing,
11 | keyed = thing
12 | }
13 |
14 | computed_keys = {
15 | [1.0] = "one!",
16 | [2.0] = "two!",
17 | ["string"] = "string",
18 | [2 + 2] = "minus one that's three quick maths",
19 | [L"Welcome to City 17"] = "You have chosen, or, been chosen...",
20 | [true] = false,
21 |
22 | __index = function(self, key)
23 | return rawget(self, key)
24 | end
25 | }
26 |
27 | crazy_nesting = {
28 | a = {
29 | b = {
30 | c = {
31 | d = {
32 | e = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, foo = bar, ["aaaaa!!!!"] = "aaaaa!!!!" }
33 | }
34 | }
35 | }
36 | },
37 | [{ please = "no" }] = { please = "yes" },
38 | [45.6] = { 45.6, 45.6, 45.6, 45.6 },
39 | [{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }] = { this_kills_the_crab }
40 | }
41 |
42 | local empty = {}
43 |
44 | local one_thing = { thing }
45 |
46 | local one_keyed_thing = { keyed = thing }
47 |
48 | local more_than_one_thing = { thing, thing }
49 |
50 | local more_than_one_keyed_thing = {
51 | keyed = thing,
52 | keyed = thing
53 | }
54 |
55 | local computed_keys = {
56 | [1.0] = "one!",
57 | [2.0] = "two!",
58 | ["string"] = "string",
59 | ["string with spaces"] = "string",
60 | [ [[oneword]] ] = 2,
61 | [ [[
62 | multi line string
63 | ]] ] = "aa",
64 | [2 + 2] = "minus one that's three quick maths",
65 | [L"Welcome to City 17"] = "You have chosen, or, been chosen...",
66 | [true] = false,
67 |
68 | __index = function(self, key)
69 | return rawget(self, key)
70 | end
71 | }
72 |
73 | local crazy_nesting = {
74 | a = {
75 | b = {
76 | c = {
77 | d = {
78 | e = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, foo = bar, ["aaaaa!!!!"] = "aaaaa!!!!" }
79 | }
80 | }
81 | }
82 | },
83 | [{ please = "no" }] = { please = "yes" },
84 | [45.6] = { 45.6, 45.6, 45.6, 45.6 },
85 | [{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }] = { this_kills_the_crab }
86 | }
87 |
--------------------------------------------------------------------------------
/tests/ast-nodes/unary-expression/__snapshots__/jsfmt.spec.js.snap:
--------------------------------------------------------------------------------
1 | // Jest Snapshot v1, https://goo.gl/fbAQLP
2 |
3 | exports[`main.lua - lua-verify: main.lua 1`] = `
4 | negative = -1
5 | opposite = not true
6 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
7 | negative = -1
8 | opposite = not true
9 |
10 | `;
11 |
12 | exports[`main.lua - lua-verify: main.lua 2`] = `
13 | negative = -1
14 | opposite = not true
15 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
16 | negative = -1
17 | opposite = not true
18 |
19 | `;
20 |
--------------------------------------------------------------------------------
/tests/ast-nodes/unary-expression/jsfmt.spec.js:
--------------------------------------------------------------------------------
1 | run_spec(__dirname, ["lua"]);
2 | run_spec(__dirname, ["lua"], { trailingComma: "all", singleQuote: true });
3 |
--------------------------------------------------------------------------------
/tests/ast-nodes/unary-expression/main.lua:
--------------------------------------------------------------------------------
1 | negative = -1
2 | opposite = not true
3 |
--------------------------------------------------------------------------------
/tests/ast-nodes/while-statement/__snapshots__/jsfmt.spec.js.snap:
--------------------------------------------------------------------------------
1 | // Jest Snapshot v1, https://goo.gl/fbAQLP
2 |
3 | exports[`main.lua - lua-verify: main.lua 1`] = `
4 | while empty do end
5 |
6 | while condition do
7 | print("while-loop")
8 | end
9 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
10 | while empty do
11 | end
12 |
13 | while condition do
14 | print("while-loop")
15 | end
16 |
17 | `;
18 |
19 | exports[`main.lua - lua-verify: main.lua 2`] = `
20 | while empty do end
21 |
22 | while condition do
23 | print("while-loop")
24 | end
25 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
26 | while empty do
27 | end
28 |
29 | while condition do
30 | print('while-loop')
31 | end
32 |
33 | `;
34 |
--------------------------------------------------------------------------------
/tests/ast-nodes/while-statement/jsfmt.spec.js:
--------------------------------------------------------------------------------
1 | run_spec(__dirname, ["lua"]);
2 | run_spec(__dirname, ["lua"], { trailingComma: "all", singleQuote: true });
3 |
--------------------------------------------------------------------------------
/tests/ast-nodes/while-statement/main.lua:
--------------------------------------------------------------------------------
1 | while empty do end
2 |
3 | while condition do
4 | print("while-loop")
5 | end
6 |
--------------------------------------------------------------------------------
/tests/comments/__snapshots__/jsfmt.spec.js.snap:
--------------------------------------------------------------------------------
1 | // Jest Snapshot v1, https://goo.gl/fbAQLP
2 |
3 | exports[`empty_with_comment.lua - lua-verify: empty_with_comment.lua 1`] = `
4 | -- comment alone in chunk
5 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
6 | -- comment alone in chunk
7 |
8 | `;
9 |
10 | exports[`main.lua - lua-verify: main.lua 1`] = `
11 | -- line comment in chunk
12 | dosomething()
13 | -- another line comment in chunk
14 |
15 | function Function()
16 | -- line comment in Function
17 | if --[[before if conditional]] --[[another before if conditional]] true --[[after if conditional]] then -- end of if line
18 | dooo() -- end of call in if
19 | end
20 | end
21 |
22 | function Foo()
23 | -- comment in empty function body
24 | end
25 |
26 | function --[[between function keyword and name]] Bar()
27 | end
28 |
29 | function --[==[ between function keyword and name ]==] Bar()
30 | end
31 |
32 | for k,v in pairs(t) do
33 | -- comment in empty for body
34 | end~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
35 | -- line comment in chunk
36 | dosomething()
37 | -- another line comment in chunk
38 |
39 | function Function()
40 | -- line comment in Function
41 | if --[[before if conditional]] --[[another before if conditional]] true --[[after if conditional]] then -- end of if line
42 | dooo() -- end of call in if
43 | end
44 | end
45 |
46 | function Foo()
47 | -- comment in empty function body
48 | end
49 |
50 | function --[[between function keyword and name]] Bar()
51 | end
52 |
53 | function --[==[ between function keyword and name ]==] Bar()
54 | end
55 |
56 | for k, v in pairs(t) do
57 | -- comment in empty for body
58 | end
59 |
60 | `;
61 |
62 | exports[`prettier-ignore.lua - lua-verify: prettier-ignore.lua 1`] = `
63 | weird_table_1 = {
64 | 1, 2
65 | , { a = 5 }
66 | }
67 |
68 | -- prettier-ignore
69 | weird_table_2 = {
70 | 1, 2
71 | , { a = 5 }
72 | }
73 |
74 | -- prettier-ignore for reasons
75 | weird_table_3 = {
76 | 1, 2
77 | , { a = 5 }
78 | }
79 |
80 | --[==[ prettier-ignore ]==]
81 | weird_table_4 = {
82 | 1, 2
83 | , { a =
84 |
85 | 5 }
86 | }
87 |
88 | --[==[
89 | prettier-ignore for reasons
90 | ]==]
91 | weird_table_5 = {
92 | 1, 2
93 | , { a = 5 }
94 | }
95 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
96 | weird_table_1 = { 1, 2, { a = 5 } }
97 |
98 | -- prettier-ignore
99 | weird_table_2 = {
100 | 1, 2
101 | , { a = 5 }
102 | }
103 |
104 | -- prettier-ignore for reasons
105 | weird_table_3 = {
106 | 1, 2
107 | , { a = 5 }
108 | }
109 |
110 | --[==[ prettier-ignore ]==]
111 | weird_table_4 = {
112 | 1, 2
113 | , { a =
114 |
115 | 5 }
116 | }
117 |
118 | --[==[
119 | prettier-ignore for reasons
120 | ]==]
121 | weird_table_5 = {
122 | 1, 2
123 | , { a = 5 }
124 | }
125 |
126 | `;
127 |
--------------------------------------------------------------------------------
/tests/comments/empty_with_comment.lua:
--------------------------------------------------------------------------------
1 | -- comment alone in chunk
2 |
--------------------------------------------------------------------------------
/tests/comments/jsfmt.spec.js:
--------------------------------------------------------------------------------
1 | run_spec(__dirname, ["lua"]);
2 |
--------------------------------------------------------------------------------
/tests/comments/main.lua:
--------------------------------------------------------------------------------
1 | -- line comment in chunk
2 | dosomething()
3 | -- another line comment in chunk
4 |
5 | function Function()
6 | -- line comment in Function
7 | if --[[before if conditional]] --[[another before if conditional]] true --[[after if conditional]] then -- end of if line
8 | dooo() -- end of call in if
9 | end
10 | end
11 |
12 | function Foo()
13 | -- comment in empty function body
14 | end
15 |
16 | function --[[between function keyword and name]] Bar()
17 | end
18 |
19 | function --[==[ between function keyword and name ]==] Bar()
20 | end
21 |
22 | for k,v in pairs(t) do
23 | -- comment in empty for body
24 | end
--------------------------------------------------------------------------------
/tests/comments/prettier-ignore.lua:
--------------------------------------------------------------------------------
1 | weird_table_1 = {
2 | 1, 2
3 | , { a = 5 }
4 | }
5 |
6 | -- prettier-ignore
7 | weird_table_2 = {
8 | 1, 2
9 | , { a = 5 }
10 | }
11 |
12 | -- prettier-ignore for reasons
13 | weird_table_3 = {
14 | 1, 2
15 | , { a = 5 }
16 | }
17 |
18 | --[==[ prettier-ignore ]==]
19 | weird_table_4 = {
20 | 1, 2
21 | , { a =
22 |
23 | 5 }
24 | }
25 |
26 | --[==[
27 | prettier-ignore for reasons
28 | ]==]
29 | weird_table_5 = {
30 | 1, 2
31 | , { a = 5 }
32 | }
33 |
--------------------------------------------------------------------------------
/tests/examples/BUSTED_LICENSE:
--------------------------------------------------------------------------------
1 | MIT License Terms
2 | =================
3 |
4 | Copyright (c) 2012 Olivine Labs, LLC.
5 |
6 | Permission is hereby granted, free of charge, to any person obtaining a copy of
7 | this software and associated documentation files (the "Software"), to deal in
8 | the Software without restriction, including without limitation the rights to
9 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
10 | of the Software, and to permit persons to whom the Software is furnished to do
11 | so, subject to the following conditions:
12 |
13 | The above copyright notice and this permission notice shall be included in all
14 | copies or substantial portions of the Software.
15 |
16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 | SOFTWARE.
23 |
--------------------------------------------------------------------------------
/tests/examples/busted/TAP.lua:
--------------------------------------------------------------------------------
1 | local pretty = require 'pl.pretty'
2 |
3 | return function(options)
4 | local busted = require 'busted'
5 | local handler = require 'busted.outputHandlers.base'()
6 |
7 | local success = 'ok %u - %s'
8 | local failure = 'not ' .. success
9 | local skip = 'ok %u - # SKIP %s'
10 | local counter = 0
11 |
12 | handler.suiteReset = function()
13 | counter = 0
14 | return nil, true
15 | end
16 |
17 | handler.suiteEnd = function()
18 | print('1..' .. counter)
19 | io.flush()
20 | return nil, true
21 | end
22 |
23 | local function showFailure(t)
24 | local message = t.message
25 | local trace = t.trace or {}
26 |
27 | if message == nil then
28 | message = 'Nil error'
29 | elseif type(message) ~= 'string' then
30 | message = pretty.write(message)
31 | end
32 |
33 | print(failure:format(counter, t.name))
34 | print('# ' .. t.element.trace.short_src .. ' @ ' .. t.element.trace.currentline)
35 | if t.randomseed then print('# Random seed: ' .. t.randomseed) end
36 | print('# Failure message: ' .. message:gsub('\n', '\n# '))
37 | if options.verbose and trace.traceback then
38 | print('# ' .. trace.traceback:gsub('^\n', '', 1):gsub('\n', '\n# '))
39 | end
40 | end
41 |
42 | handler.testStart = function(element, parent)
43 | local trace = element.trace
44 | if options.verbose and trace and trace.short_src then
45 | local fileline = trace.short_src .. ' @ ' .. trace.currentline .. ': '
46 | local testName = fileline .. handler.getFullName(element)
47 | print('# ' .. testName)
48 | end
49 | io.flush()
50 |
51 | return nil, true
52 | end
53 |
54 | handler.testEnd = function(element, parent, status, trace)
55 | counter = counter + 1
56 | if status == 'success' then
57 | local t = handler.successes[#handler.successes]
58 | print(success:format(counter, t.name))
59 | elseif status == 'pending' then
60 | local t = handler.pendings[#handler.pendings]
61 | print(skip:format(counter, (t.message or t.name)))
62 | elseif status == 'failure' then
63 | showFailure(handler.failures[#handler.failures])
64 | elseif status == 'error' then
65 | showFailure(handler.errors[#handler.errors])
66 | end
67 | io.flush()
68 |
69 | return nil, true
70 | end
71 |
72 | handler.error = function(element, parent, message, debug)
73 | if element.descriptor ~= 'it' then
74 | counter = counter + 1
75 | showFailure(handler.errors[#handler.errors])
76 | end
77 | io.flush()
78 |
79 | return nil, true
80 | end
81 |
82 | busted.subscribe({ 'suite', 'reset' }, handler.suiteReset)
83 | busted.subscribe({ 'suite', 'end' }, handler.suiteEnd)
84 | busted.subscribe({ 'test', 'start' }, handler.testStart, { predicate = handler.cancelOnPending })
85 | busted.subscribe({ 'test', 'end' }, handler.testEnd, { predicate = handler.cancelOnPending })
86 | busted.subscribe({ 'error' }, handler.error)
87 |
88 | return handler
89 | end
90 |
--------------------------------------------------------------------------------
/tests/examples/busted/ar.lua:
--------------------------------------------------------------------------------
1 | local s = require('say')
2 |
3 | s:set_namespace('ar')
4 |
5 | -- 'Pending: test.lua @ 12 \n description
6 | s:set('output.pending', 'عالِق')
7 | s:set('output.failure', 'فَشَل')
8 | s:set('output.failure', 'نَجاح')
9 |
10 | s:set('output.pending_plural', 'عالِق')
11 | s:set('output.failure_plural', 'إخْفاقات')
12 | s:set('output.success_plural', 'نَجاحات')
13 |
14 | s:set('output.pending_zero', 'عالِق')
15 | s:set('output.failure_zero', 'إخْفاقات')
16 | s:set('output.success_zero', 'نَجاحات')
17 |
18 | s:set('output.pending_single', 'عالِق')
19 | s:set('output.failure_single', 'فَشَل')
20 | s:set('output.success_single', 'نَجاح')
21 |
22 | s:set('output.seconds', 'ثَوانٍ')
23 |
24 | -- definitions following are not used within the 'say' namespace
25 | return {
26 | failure_messages = {
27 | 'فَشِلَت %d مِنْ الإِختِبارات',
28 | 'فَشِلَت إخْتِباراتُك',
29 | 'برمجيَّتُكَ ضَعيْفة، أنْصَحُكَ بالتَّقاعُد',
30 | 'تقع برمجيَّتُكَ في مَنطِقَةِ الخَطَر',
31 | 'أقترِحُ ألّا تَتَقَدَّم بالإختِبار، علَّ يبْقى الطابِقُ مَستوراَ',
32 | 'جَدَّتي، فِي أَثْناءِ نَومِها، تَكتبُ بَرمَجياتٍ أفْضلُ مِن هذه',
33 | 'يَوَدُّ ليْ مُساعَدَتُكْ، لَكِنّْ...'
34 | },
35 | success_messages = {
36 | 'رائِع! تَمَّ إجْتِيازُ جَميعُ الإختِباراتِ بِنَجاحٍ',
37 | 'قُل ما شِئت، لا أكتَرِث: busted شَهِدَ لي!',
38 | 'حَقَّ عَليْكَ الإفتِخار',
39 | 'نَجاحٌ مُبْهِر!',
40 | 'عَليكَ بالإحتِفال؛ نَجَحَت جَميعُ التَجارُب'
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/tests/examples/busted/async_spec.lua:
--------------------------------------------------------------------------------
1 | pending('testing the done callback with tokens', function()
2 |
3 | it('Tests done call back ordered', function()
4 | async()
5 | stub(done, 'done_cb') -- create a stub to prevent actually calling 'done'
6 | done:wait_ordered('1', '2', '3')
7 |
8 | assert.has_no_error(function() done('1') end)
9 | assert.has_error(function() done('1') end) -- was already done
10 | assert.has_error(function() done('3') end) -- bad order
11 | assert.has_no_error(function() done('2') end)
12 | assert.has_error(function() done('this is no valid token') end)
13 | assert.has_no_error(function() done('3') end)
14 | assert.has_error(function() done('3') end) -- tokenlist empty by now
15 | assert.stub(done.done_cb).was.called(1)
16 |
17 | done.done_cb:revert() -- revert so test can complete
18 | done()
19 | end)
20 |
21 | it('Tests done call back unordered', function()
22 | async()
23 | stub(done, 'done_cb') -- create a stub to prevent actually calling 'done'
24 | done:wait_unordered('1', '2', '3')
25 |
26 | assert.has_no_error(function() done('1') end)
27 | assert.has_error(function() done('1') end) -- was already done
28 | assert.has_no_error(function() done('3') end) -- different order
29 | assert.has_no_error(function() done('2') end)
30 | assert.has_error(function() done('this is no valid token') end)
31 | assert.has_error(function() done('3') end) -- tokenlist empty by now
32 | assert.stub(done.done_cb).was.called(1)
33 |
34 | done.done_cb:revert() -- revert so test can complete
35 | done()
36 | end)
37 |
38 | it('Tests done call back defaulting to ordered', function()
39 | async()
40 | stub(done, 'done_cb') -- create a stub to prevent actually calling 'done'
41 | done:wait('1', '2')
42 |
43 | assert.has_error(function() done('2') end) -- different order
44 | assert.has_no_error(function() done('1') end)
45 | assert.has_no_error(function() done('2') end)
46 |
47 | done.done_cb:revert() -- revert so test can complete
48 | done()
49 | end)
50 | end)
51 |
52 | pending('testing done callbacks being provided for async tests', function()
53 | setup(function()
54 | async()
55 | assert.is_table(done)
56 | assert.is_function(done.wait)
57 | done()
58 | end)
59 |
60 | before_each(function()
61 | async()
62 | assert.is_table(done)
63 | assert.is_function(done.wait)
64 | done()
65 | end)
66 |
67 | after_each(function()
68 | async()
69 | assert.is_table(done)
70 | assert.is_function(done.wait)
71 | done()
72 | end)
73 |
74 | teardown(function()
75 | async()
76 | assert.is_table(done)
77 | assert.is_function(done.wait)
78 | done()
79 | end)
80 |
81 | it('Tests done callbacks being provided for async tests', function()
82 | async()
83 | assert.is_table(done)
84 | assert.is_function(done.wait)
85 | done()
86 | end)
87 | end)
88 |
--------------------------------------------------------------------------------
/tests/examples/busted/block.lua:
--------------------------------------------------------------------------------
1 | local getfenv = require 'busted.compatibility'.getfenv
2 | local unpack = require 'busted.compatibility'.unpack
3 | local shuffle = require 'busted.utils'.shuffle
4 |
5 | local function sort(elements)
6 | table.sort(elements, function(t1, t2)
7 | if t1.name and t2.name then
8 | return t1.name < t2.name
9 | end
10 | return t2.name ~= nil
11 | end)
12 | return elements
13 | end
14 |
15 | return function(busted)
16 | local block = {}
17 | local root = busted.context.get()
18 |
19 | function block.reject(descriptor, element)
20 | element.env[descriptor] = function(...)
21 | error("'" .. descriptor .. "' not supported inside current context block", 2)
22 | end
23 | end
24 |
25 | function block.rejectAll(element)
26 | local env = getfenv(element.run)
27 | block.reject('randomize', element)
28 | for descriptor, _ in pairs(busted.executors) do
29 | if root.env[descriptor] and (env ~= _G and env[descriptor] or rawget(env, descriptor)) then
30 | block.reject(descriptor, element)
31 | end
32 | end
33 | end
34 |
35 | local function exec(descriptor, element)
36 | if not element.env then element.env = {} end
37 | block.rejectAll(element)
38 | local ret = { busted.safe(descriptor, element.run, element) }
39 | return unpack(ret)
40 | end
41 |
42 | function block.execAllOnce(descriptor, current, err)
43 | local parent = busted.context.parent(current)
44 |
45 | if parent then
46 | local success = block.execAllOnce(descriptor, parent)
47 | if not success then
48 | return success
49 | end
50 | end
51 |
52 | if not current[descriptor] then
53 | current[descriptor] = {}
54 | end
55 | local list = current[descriptor]
56 | if list.success ~= nil then
57 | return list.success
58 | end
59 |
60 | local success = true
61 | for _, v in ipairs(list) do
62 | if not exec(descriptor, v):success() then
63 | if err then err(descriptor) end
64 | success = false
65 | end
66 | end
67 |
68 | list.success = success
69 |
70 | return success
71 | end
72 |
73 | function block.execAll(descriptor, current, propagate, err)
74 | local parent = busted.context.parent(current)
75 |
76 | if propagate and parent then
77 | local success, ancestor = block.execAll(descriptor, parent, propagate)
78 | if not success then
79 | return success, ancestor
80 | end
81 | end
82 |
83 | local list = current[descriptor] or {}
84 |
85 | local success = true
86 | for _, v in ipairs(list) do
87 | if not exec(descriptor, v):success() then
88 | if err then err(descriptor) end
89 | success = nil
90 | end
91 | end
92 | return success, current
93 | end
94 |
95 | function block.dexecAll(descriptor, current, propagate, err)
96 | local parent = busted.context.parent(current)
97 | local list = current[descriptor] or {}
98 |
99 | local success = true
100 | for _, v in ipairs(list) do
101 | if not exec(descriptor, v):success() then
102 | if err then err(descriptor) end
103 | success = nil
104 | end
105 | end
106 |
107 | if propagate and parent then
108 | if not block.dexecAll(descriptor, parent, propagate) then
109 | success = nil
110 | end
111 | end
112 | return success
113 | end
114 |
115 | function block.lazySetup(element, err)
116 | return block.execAllOnce('lazy_setup', element, err)
117 | end
118 |
119 | function block.lazyTeardown(element, err)
120 | if element.lazy_setup and element.lazy_setup.success ~= nil then
121 | block.dexecAll('lazy_teardown', element, nil, err)
122 | element.lazy_setup.success = nil
123 | end
124 | end
125 |
126 | function block.setup(element, err)
127 | return block.execAll('strict_setup', element, nil, err)
128 | end
129 |
130 | function block.teardown(element, err)
131 | return block.dexecAll('strict_teardown', element, nil, err)
132 | end
133 |
134 | function block.execute(descriptor, element)
135 | if not element.env then element.env = {} end
136 |
137 | local randomize = busted.randomize
138 | local randomseed = busted.randomseed
139 | element.env.randomize = function(...)
140 | randomize = (select('#', ...) == 0 or ...)
141 | if randomize then
142 | randomseed = tonumber(({...})[1]) or tonumber(({...})[2]) or randomseed
143 | end
144 | end
145 |
146 | if busted.safe(descriptor, element.run, element):success() then
147 | if busted.sort then
148 | sort(busted.context.children(element))
149 | elseif randomize then
150 | element.randomseed = randomseed
151 | shuffle(busted.context.children(element), randomseed)
152 | end
153 |
154 | if block.setup(element) then
155 | busted.execute(element)
156 | end
157 |
158 | block.lazyTeardown(element)
159 | block.teardown(element)
160 | end
161 | end
162 |
163 | return block
164 | end
165 |
--------------------------------------------------------------------------------
/tests/examples/busted/cl_error_messages.lua:
--------------------------------------------------------------------------------
1 | -- supporting testfile; belongs to 'cl_spec.lua'
2 |
3 | describe('Test error messages show file and line for', function()
4 | it('table errors #table', function()
5 | error({})
6 | end)
7 |
8 | it('nil errors #nil', function()
9 | error()
10 | end)
11 |
12 | it('string errors #string', function()
13 | error('error message')
14 | end)
15 |
16 | it('table errors #tostring', function()
17 | error(setmetatable({}, { __tostring = function() return '{}' end}))
18 | end)
19 |
20 | it('table errors #pcall', function()
21 | pcall(error, 'error inside pcall')
22 | error('error after pcall')
23 | end)
24 | end)
25 |
--------------------------------------------------------------------------------
/tests/examples/busted/cl_errors.lua:
--------------------------------------------------------------------------------
1 | -- supporting testfile; belongs to 'cl_spec.lua'
2 |
3 | describe('Tests the busted error detection through the commandline', function()
4 |
5 | it('is a test that throws an error #testerr', function()
6 | error('force an error')
7 | end)
8 |
9 | it('is a test with a Lua error #luaerr', function()
10 | local foo
11 | foo.bar = nil
12 | end)
13 | end)
14 |
15 |
--------------------------------------------------------------------------------
/tests/examples/busted/cl_execute_fail.lua:
--------------------------------------------------------------------------------
1 | -- supporting testfile; belongs to 'cl_spec.lua'
2 |
3 |
4 | error('This compiles fine, but throws an error when being run')
5 |
--------------------------------------------------------------------------------
/tests/examples/busted/cl_failing_support.lua:
--------------------------------------------------------------------------------
1 |
2 | describe('bad support functions should fail, sync test', function()
3 | describe('bad setup should properly fail a test', function()
4 | setup(function()
5 | error('failing a setup method')
6 | end)
7 |
8 | before_each(function() end)
9 |
10 | after_each(function() end)
11 |
12 | teardown(function() end)
13 |
14 | it('Tests nothing, should always fail due to failing support functions', function()
15 | assert(false)
16 | end)
17 |
18 | it('Tests nothing, should always fail due to failing support functions', function()
19 | assert(false)
20 | end)
21 | end)
22 |
23 |
24 | describe('bad before_each should properly fail a test', function()
25 | setup(function() end)
26 |
27 | before_each(function()
28 | error('failing a before_each method')
29 | end)
30 |
31 | after_each(function() end)
32 |
33 | teardown(function() end)
34 |
35 | it('Tests nothing, should always fail due to failing support functions', function()
36 | end)
37 |
38 | it('Tests nothing, should always fail due to failing support functions', function()
39 | end)
40 | end)
41 |
42 |
43 | describe('bad after_each should properly fail a test', function()
44 | setup(function() end)
45 |
46 | before_each(function() end)
47 |
48 | after_each(function()
49 | error('failing an after_each method')
50 | end)
51 |
52 | teardown(function() end)
53 |
54 | it('Tests nothing, should always fail due to failing support functions', function()
55 | end)
56 |
57 | it('Tests nothing, should always fail due to failing support functions', function()
58 | end)
59 | end)
60 |
61 | describe('bad teardown should properly fail a test', function()
62 | setup(function() end)
63 |
64 | before_each(function() end)
65 |
66 | after_each(function() end)
67 |
68 | teardown(function()
69 | error('failing a teardown method')
70 | end)
71 |
72 | it('Tests nothing, should always fail due to failing support functions', function()
73 | end)
74 |
75 | it('Tests nothing, should always fail due to failing support functions', function()
76 | end)
77 | end)
78 |
79 | describe('bad setup/teardown should properly fail a test', function()
80 | setup(function()
81 | error('failing a setup method')
82 | end)
83 |
84 | before_each(function() end)
85 |
86 | after_each(function() end)
87 |
88 | teardown(function()
89 | error('failing a teardown method')
90 | end)
91 |
92 | it('Tests nothing, should always fail due to failing support functions', function()
93 | assert(false)
94 | end)
95 | end)
96 | end)
97 |
98 | describe('bad support functions should fail, async test', function()
99 | describe('bad setup should properly fail a test, async', function()
100 | setup(function()
101 | async()
102 | error('failing a setup method')
103 | end)
104 |
105 | before_each(function() end)
106 |
107 | after_each(function() end)
108 |
109 | teardown(function() end)
110 |
111 | it('Tests nothing, should always fail due to failing support functions', function()
112 | end)
113 |
114 | it('Tests nothing, should always fail due to failing support functions', function()
115 | end)
116 | end)
117 |
118 | describe('bad before_each should properly fail a test, async', function()
119 | setup(function() end)
120 |
121 | before_each(function()
122 | async()
123 | error('failing a before_each method')
124 | end)
125 |
126 | after_each(function() end)
127 |
128 | teardown(function() end)
129 |
130 | it('Tests nothing, should always fail due to failing support functions', function()
131 | end)
132 |
133 | it('Tests nothing, should always fail due to failing support functions', function()
134 | end)
135 | end)
136 |
137 | describe('bad after_each should properly fail a test, async', function()
138 | setup(function() end)
139 |
140 | before_each(function() end)
141 |
142 | after_each(function()
143 | async()
144 | error('failing an after_each method')
145 | end)
146 |
147 | teardown(function() end)
148 |
149 | it('Tests nothing, should always fail due to failing support functions', function()
150 | end)
151 |
152 | it('Tests nothing, should always fail due to failing support functions', function()
153 | end)
154 | end)
155 |
156 | describe('bad teardown should properly fail a test, async', function()
157 | setup(function() end)
158 |
159 | before_each(function() end)
160 |
161 | after_each(function() end)
162 |
163 | teardown(function()
164 | async()
165 | error('failing a teardown method')
166 | end)
167 |
168 | it('Tests nothing, should always fail due to failing support functions', function()
169 | end)
170 |
171 | it('Tests nothing, should always fail due to failing support functions', function()
172 | end)
173 | end)
174 |
175 | describe('bad setup/teardown should properly fail a test, async', function()
176 | setup(function()
177 | async()
178 | error('failing a setup method')
179 | end)
180 |
181 | before_each(function() end)
182 |
183 | after_each(function() end)
184 |
185 | teardown(function()
186 | async()
187 | error('failing a teardown method')
188 | end)
189 |
190 | it('Tests nothing, should always fail due to failing support functions', function()
191 | assert(false)
192 | end)
193 |
194 | it('Tests nothing, should always fail due to failing support functions', function()
195 | assert(false)
196 | end)
197 | end)
198 |
199 | end)
200 |
201 |
--------------------------------------------------------------------------------
/tests/examples/busted/cl_filter.lua:
--------------------------------------------------------------------------------
1 | -- supporting testfile; belongs to 'cl_spec.lua'
2 |
3 | describe('Tests the busted command-line options', function()
4 |
5 | it('is a test with pattern1', function()
6 | -- works by counting failure
7 | error('error 1 on pattern1')
8 | end)
9 |
10 | it('is another test with pattern1', function()
11 | -- works by counting failure
12 | error('error 2 on pattern1')
13 | end)
14 |
15 | it('is a test with pattern2', function()
16 | -- works by counting failure
17 | error('error on pattern2')
18 | end)
19 |
20 | it('is a test with pattern3', function()
21 | -- nothing here, makes it succeed
22 | end)
23 |
24 | it('is a test with two pattern3 and pattern4', function ()
25 | -- Always succeed
26 | end)
27 | end)
28 |
29 | describe('Tests describe with patt1', function()
30 | before_each(function()
31 | error('error in before_each on patt1')
32 | end)
33 |
34 | after_each(function()
35 | error('error in after_each on patt1')
36 | end)
37 |
38 | it('is a test inside describe', function()
39 | end)
40 |
41 | it('is another test inside describe', function()
42 | end)
43 | end)
44 |
45 | context('Tests context with patt2', function()
46 | setup(function()
47 | error('error in setup on patt2')
48 | end)
49 | end)
50 |
--------------------------------------------------------------------------------
/tests/examples/busted/cl_gc_error.lua:
--------------------------------------------------------------------------------
1 | -- supporting testfile; belongs to 'cl_spec.lua'
2 |
3 | describe('Runs test with garbage collection failure', function()
4 | it('throws error in __gc metamethod', function()
5 | setmetatable({}, { __gc = function() error('gc error') end})
6 | collectgarbage()
7 | collectgarbage()
8 | end)
9 | end)
10 |
--------------------------------------------------------------------------------
/tests/examples/busted/cl_helper_script.lua:
--------------------------------------------------------------------------------
1 | -- supporting testfile; belongs to 'cl_spec.lua'
2 |
3 | local setup = require 'busted'.setup
4 | local teardown = require 'busted'.teardown
5 | local before_each = require 'busted'.before_each
6 | local after_each = require 'busted'.after_each
7 | local subscribe = require 'busted'.subscribe
8 | local assert = require 'busted'.assert
9 | local cli = require 'cliargs'
10 |
11 | cli:set_name('cl_helper_script')
12 | cli:flag('--fail-setup', 'force setup to fail')
13 | cli:flag('--fail-teardown', 'force teardown to fail')
14 | cli:flag('--fail-before-each', 'force before each to fail')
15 | cli:flag('--fail-after-each', 'force after each to fail')
16 | cli:flag('--fail-suite-reset', 'force suite reset handler to fail')
17 | cli:flag('--fail-suite-start', 'force suite start handler to fail')
18 | cli:flag('--fail-suite-end', 'force suite end handler to fail')
19 | cli:flag('--fail-file-start', 'force file start handler to fail')
20 | cli:flag('--fail-file-end', 'force file end handler to fail')
21 | cli:flag('--fail-describe-start', 'force describe start handler to fail')
22 | cli:flag('--fail-describe-end', 'force describe end handler to fail')
23 | cli:flag('--fail-test-start', 'force test start handler to fail')
24 | cli:flag('--fail-test-end', 'force test end handler to fail')
25 |
26 | local cliArgs = cli:parse(arg)
27 |
28 | setup(function()
29 | assert(not cliArgs['fail-setup'])
30 | end)
31 |
32 | teardown(function()
33 | assert(not cliArgs['fail-teardown'])
34 | end)
35 |
36 | before_each(function()
37 | assert(not cliArgs['fail-before-each'])
38 | end)
39 |
40 | after_each(function()
41 | assert(not cliArgs['fail-after-each'])
42 | end)
43 |
44 | subscribe({'suite', 'reset'}, function()
45 | assert(not cliArgs['fail-suite-reset'])
46 | return nil, true
47 | end)
48 |
49 | subscribe({'suite', 'start'}, function()
50 | assert(not cliArgs['fail-suite-start'])
51 | return nil, true
52 | end)
53 |
54 | subscribe({'suite', 'end'}, function()
55 | assert(not cliArgs['fail-suite-end'])
56 | return nil, true
57 | end)
58 |
59 | subscribe({'file', 'start'}, function()
60 | assert(not cliArgs['fail-file-start'])
61 | return nil, true
62 | end)
63 |
64 | subscribe({'file', 'end'}, function()
65 | assert(not cliArgs['fail-file-end'])
66 | return nil, true
67 | end)
68 |
69 | subscribe({'describe', 'start'}, function()
70 | assert(not cliArgs['fail-describe-start'])
71 | return nil, true
72 | end)
73 |
74 | subscribe({'describe', 'end'}, function()
75 | assert(not cliArgs['fail-describe-end'])
76 | return nil, true
77 | end)
78 |
79 | subscribe({'test', 'start'}, function()
80 | assert(not cliArgs['fail-test-start'])
81 | return nil, true
82 | end)
83 |
84 | subscribe({'test', 'end'}, function()
85 | assert(not cliArgs['fail-test-end'])
86 | return nil, true
87 | end)
88 |
--------------------------------------------------------------------------------
/tests/examples/busted/cl_list.lua:
--------------------------------------------------------------------------------
1 | -- supporting testfile; belongs to 'cl_spec.lua'
2 |
3 | describe('Tests list', function()
4 | it('test 1', function()
5 | end)
6 |
7 | it('test 2', function()
8 | end)
9 |
10 | it('test 3', function()
11 | end)
12 | end)
13 |
--------------------------------------------------------------------------------
/tests/examples/busted/cl_lua_path.lua:
--------------------------------------------------------------------------------
1 | -- supporting testfile; belongs to 'cl_spec.lua'
2 |
3 | describe('Tests --lpath prepends to package.path', function()
4 | it('require test module', function()
5 | local mod = require('cl_test_module')
6 | assert.is_equal('test module', mod)
7 | end)
8 | end)
9 |
--------------------------------------------------------------------------------
/tests/examples/busted/cl_output_handler.lua:
--------------------------------------------------------------------------------
1 | -- supporting testfile; belongs to 'cl_spec.lua'
2 |
3 | return function(options)
4 | local busted = require 'busted'
5 | local handler = require 'busted.outputHandlers.base'()
6 | local cli = require 'cliargs'
7 | local args = options.arguments
8 |
9 | cli:set_name('cl_output_handler')
10 | cli:flag('--time', 'show timestamps')
11 | cli:option('--time-format=FORMAT', 'format string according to strftime', '!%a %b %d %H:%M:%S %Y')
12 |
13 | local cliArgs = cli:parse(args)
14 |
15 | handler.testEnd = function(element, parent, status, debug)
16 | local showTime = cliArgs.time
17 | local timeFormat = cliArgs['time-format']
18 | local timestamp = showTime and ('[' .. os.date(timeFormat, 123456) .. '] ') or ''
19 |
20 | print(string.format("%s[%8s] %s", timestamp, status, handler.getFullName(element)))
21 | end
22 |
23 | busted.subscribe({ 'test', 'end' }, handler.testEnd, { predicate = handler.cancelOnPending })
24 |
25 | return handler
26 | end
27 |
--------------------------------------------------------------------------------
/tests/examples/busted/cl_pending.lua:
--------------------------------------------------------------------------------
1 | -- supporting testfile; belongs to 'cl_spec.lua'
2 |
3 | describe('Tests the busted pending functions through the commandline', function()
4 |
5 | it('is a test with a pending', function()
6 | pending('finish this test later')
7 | error('should never get here')
8 | end)
9 |
10 | pending('is a pending inside a describe', function()
11 | it('this test does not run', function()
12 | error('this should not run')
13 | end)
14 | end)
15 | end)
16 |
17 |
--------------------------------------------------------------------------------
/tests/examples/busted/cl_random_seed.lua:
--------------------------------------------------------------------------------
1 | -- supporting testfile; belongs to 'cl_spec.lua'
2 | -- executed with --seed=12345
3 | local order = {}
4 |
5 | describe('Randomizing test order with pre-defined seed', function()
6 | randomize()
7 |
8 | for i = 1, 10 do
9 | it('does 10 its', function()
10 | table.insert(order, i)
11 | end)
12 | end
13 | end)
14 |
15 | describe('Order of tests ran', function()
16 | randomize()
17 |
18 | it('randomized with known random seed', function()
19 | math.randomseed(12345)
20 | local t = {}
21 | for i = 1, 10 do
22 | table.insert(t, i)
23 | end
24 | local n = #t
25 | while n >= 1 do
26 | local k = math.random(n)
27 | t[n], t[k] = t[k], t[n]
28 | n = n - 1
29 | end
30 | local expected = t
31 | assert.are.same(expected, order)
32 | end)
33 | end)
34 |
--------------------------------------------------------------------------------
/tests/examples/busted/cl_randomize.lua:
--------------------------------------------------------------------------------
1 | -- supporting testfile; belongs to 'cl_spec.lua'
2 | local unexpected = {}
3 | local order = {}
4 |
5 | describe('Randomizing test order with --shuffle flag', function()
6 | for i = 1, 100 do
7 | table.insert(unexpected, i)
8 |
9 | it('does 100 its', function()
10 | table.insert(order, i)
11 | end)
12 | end
13 |
14 | teardown('runs tests in randomized order', function()
15 | assert.are_not.same(unexpected, order)
16 | end)
17 | end)
18 |
19 |
--------------------------------------------------------------------------------
/tests/examples/busted/cl_sort.lua:
--------------------------------------------------------------------------------
1 | -- supporting testfile; belongs to 'cl_spec.lua'
2 |
3 | describe('Randomizing test order with --sort flag', function()
4 | local expected = {}
5 | local scratch = {}
6 | local order = {}
7 |
8 | for i = 1, 100 do
9 | table.insert(expected, i)
10 | table.insert(scratch, i)
11 | end
12 |
13 | while #scratch > 0 do
14 | local n = #scratch
15 | local k = math.random(n)
16 | local num = scratch[k]
17 |
18 | it(string.format('test number %03d', num), function()
19 | table.insert(order, num)
20 | end)
21 |
22 | scratch[k], scratch[n] = scratch[n], scratch[k]
23 | table.remove(scratch)
24 | end
25 |
26 | teardown('runs tests in sorted order', function()
27 | assert.are.same(expected, order)
28 | end)
29 | end)
30 |
--------------------------------------------------------------------------------
/tests/examples/busted/cl_standalone.lua:
--------------------------------------------------------------------------------
1 | -- supporting testfile; belongs to 'cl_spec.lua'
2 |
3 | require 'busted.runner'()
4 |
5 | describe('Tests busted standalone with command-line options', function()
6 |
7 | it('is a test with a tag #tag1', function()
8 | -- works by counting failure
9 | error('error 1 on tag1')
10 | end)
11 |
12 | it('is a test with a tag #tag1', function()
13 | -- works by counting failure
14 | error('error 2 on tag1')
15 | end)
16 |
17 | it('is a test with a tag #tag2', function()
18 | -- works by counting failure
19 | error('error on tag2')
20 | end)
21 |
22 | it('is a test with a tag #tag3', function()
23 | -- nothing here, makes it succeed
24 | end)
25 |
26 | it('is a test with two tags #tag3 #tag4', function ()
27 | -- Always succeed
28 | end)
29 | end)
30 |
--------------------------------------------------------------------------------
/tests/examples/busted/cl_success.lua:
--------------------------------------------------------------------------------
1 | -- supporting testfile; belongs to 'cl_spec.lua'
2 |
3 | describe('runs a single successful test', function()
4 |
5 | it('is a succesful test', function()
6 | -- nothing here, makes it succeed
7 | end)
8 |
9 | end)
10 |
--------------------------------------------------------------------------------
/tests/examples/busted/cl_tags.lua:
--------------------------------------------------------------------------------
1 | -- supporting testfile; belongs to 'cl_spec.lua'
2 |
3 | describe('Tests the busted command-line options', function()
4 |
5 | it('is a test with a tag #tag1', function()
6 | -- works by counting failure
7 | error('error 1 on tag1')
8 | end)
9 |
10 | spec('is a test with a tag #tag1', function()
11 | -- works by counting failure
12 | error('error 2 on tag1')
13 | end)
14 |
15 | test('is a test with a tag #tag2', function()
16 | -- works by counting failure
17 | error('error on tag2')
18 | end)
19 |
20 | it('is a test with a tag #tag3', function()
21 | -- nothing here, makes it succeed
22 | end)
23 |
24 | it('is a test with two tags #tag3 #tag4', function ()
25 | -- Always succeed
26 | end)
27 | end)
28 |
29 | describe('Tests describe with a tag #dtag1', function()
30 | before_each(function()
31 | error('error in before_each on dtag1')
32 | end)
33 |
34 | after_each(function()
35 | error('error in after_each on dtag1')
36 | end)
37 |
38 | it('is a test inside describe', function()
39 | end)
40 |
41 | it('is another test inside describe', function()
42 | end)
43 | end)
44 |
45 | context('Tests context with a tag #dtag2', function()
46 | setup(function()
47 | error('error in setup on dtag2')
48 | end)
49 | end)
50 |
--------------------------------------------------------------------------------
/tests/examples/busted/cl_test_module.lua:
--------------------------------------------------------------------------------
1 | return 'test module'
2 |
--------------------------------------------------------------------------------
/tests/examples/busted/cl_two_failures.lua:
--------------------------------------------------------------------------------
1 | -- supporting testfile; belongs to 'cl_spec.lua'
2 |
3 | describe('Runs 2 failing tests', function()
4 |
5 | it('is failing test 1 #err1', function()
6 | assert(false, 'failed on test 1')
7 | end)
8 |
9 | it('is failing test 2 #err2', function()
10 | assert(false, 'failed on test 2')
11 | end)
12 | end)
13 |
14 |
--------------------------------------------------------------------------------
/tests/examples/busted/compatibility.lua:
--------------------------------------------------------------------------------
1 | return {
2 | getfenv = getfenv or function(f)
3 | f = (type(f) == 'function' and f or debug.getinfo(f + 1, 'f').func)
4 | local name, value
5 | local up = 0
6 |
7 | repeat
8 | up = up + 1
9 | name, value = debug.getupvalue(f, up)
10 | until name == '_ENV' or name == nil
11 |
12 | return name and value or _G
13 | end,
14 |
15 | setfenv = setfenv or function(f, t)
16 | f = (type(f) == 'function' and f or debug.getinfo(f + 1, 'f').func)
17 | local name
18 | local up = 0
19 |
20 | repeat
21 | up = up + 1
22 | name = debug.getupvalue(f, up)
23 | until name == '_ENV' or name == nil
24 |
25 | if name then
26 | debug.upvaluejoin(f, up, function() return name end, 1)
27 | debug.setupvalue(f, up, t)
28 | end
29 |
30 | if f ~= 0 then return f end
31 | end,
32 |
33 | loadstring = loadstring or load,
34 | unpack = table.unpack or unpack,
35 |
36 | exit = function(code, force)
37 | if not force and code ~= 0 and _VERSION:match('^Lua 5%.[12]$') then
38 | error()
39 | elseif code ~= 0 then
40 | code = 1
41 | end
42 | if _VERSION == 'Lua 5.1' and
43 | (type(jit) ~= 'table' or not jit.version or jit.version_num < 20000) then
44 | -- From Lua 5.1 manual:
45 | -- > The userdata itself is freed only in the next
46 | -- > garbage-collection cycle.
47 | -- Call collectgarbage() while collectgarbage('count')
48 | -- changes + 3 times, at least 3 times,
49 | -- at max 100 times (to prevent infinite loop).
50 | local times_const = 0
51 | for i = 1, 100 do
52 | local count_before = collectgarbage("count")
53 | collectgarbage()
54 | local count_after = collectgarbage("count")
55 | if count_after == count_before then
56 | times_const = times_const + 1
57 | if times_const > 3 then
58 | break
59 | end
60 | else
61 | times_const = 0
62 | end
63 | end
64 | end
65 | os.exit(code, true)
66 | end,
67 |
68 | execute = require 'pl.utils'.execute,
69 | }
70 |
--------------------------------------------------------------------------------
/tests/examples/busted/configuration_loader.lua:
--------------------------------------------------------------------------------
1 | local tablex = require 'pl.tablex'
2 |
3 | return function()
4 | -- Function to load the .busted configuration file if available
5 | local loadBustedConfigurationFile = function(configFile, config, defaults)
6 | if type(configFile) ~= 'table' then
7 | return nil, '.busted file does not return a table.'
8 | end
9 |
10 | defaults = defaults or {}
11 | local run = config.run or defaults.run
12 |
13 | if run and run ~= '' then
14 | local runConfig = configFile[run]
15 |
16 | if type(runConfig) == 'table' then
17 | config = tablex.merge(runConfig, config, true)
18 | else
19 | return nil, 'Task `' .. run .. '` not found, or not a table.'
20 | end
21 | elseif type(configFile.default) == 'table' then
22 | config = tablex.merge(configFile.default, config, true)
23 | end
24 |
25 | if type(configFile._all) == 'table' then
26 | config = tablex.merge(configFile._all, config, true)
27 | end
28 |
29 | config = tablex.merge(defaults, config, true)
30 |
31 | return config
32 | end
33 |
34 | return loadBustedConfigurationFile
35 | end
36 |
--------------------------------------------------------------------------------
/tests/examples/busted/configuration_loader_spec.lua:
--------------------------------------------------------------------------------
1 | describe('Config Loader', function()
2 | local configLoader = require 'busted.modules.configuration_loader'()
3 | local testConfig, cliArgs, defaults
4 |
5 | before_each(function()
6 | testConfig = {
7 | _all = {
8 | other = 'stuff',
9 | },
10 | default = {
11 | output = 'utfTerminal'
12 | },
13 | windows = {
14 | output = 'plainTerminal'
15 | }
16 | }
17 |
18 | cliArgs = { }
19 | defaults = { }
20 | end)
21 |
22 | it('returns a valid config with no config file', function()
23 | local testConfig = { }
24 | local config, err = configLoader(testConfig, cliArgs)
25 |
26 | assert.are.same({}, config)
27 | assert.are.equal(nil, err)
28 | end)
29 |
30 | it('returns a valid config with default config', function()
31 | local config, err = configLoader(testConfig, cliArgs)
32 |
33 | assert.are.same(testConfig.default.output, config.output)
34 | assert.are.same(testConfig._all.other, config.other)
35 | assert.are.equal(nil, err)
36 | end)
37 |
38 | it('returns a valid config with specified config', function()
39 | cliArgs.run = 'windows'
40 | local config, err = configLoader(testConfig, cliArgs)
41 |
42 | assert.are.same(testConfig.windows.output, config.output)
43 | assert.are.same(testConfig._all.other, config.other)
44 | assert.are.equal(nil, err)
45 | end)
46 |
47 | it('returns a valid config with specified config and defaults specified', function()
48 | defaults = { output = 'TAP' }
49 | cliArgs.run = 'windows'
50 | local config, err = configLoader(testConfig, cliArgs, defaults)
51 |
52 | assert.are.same(testConfig.windows.output, config.output)
53 | assert.are.same(testConfig._all.other, config.other)
54 | assert.are.equal(nil, err)
55 | end)
56 |
57 | it('returns a valid config with cliArgs and defaults specified', function()
58 | cliArgs = { output = 'TAP' }
59 | local config, err = configLoader(testConfig, cliArgs, defaults)
60 |
61 | assert.are.same(cliArgs.output, config.output)
62 | assert.are.same(testConfig._all.other, config.other)
63 | assert.are.equal(nil, err)
64 | end)
65 |
66 | it('returns a valid config with defaults if no configs present', function()
67 | defaults = { output = 'TAP' }
68 | local config, err = configLoader({}, {}, defaults)
69 |
70 | assert.are.same(defaults, config)
71 | assert.are.equal(nil, err)
72 | end)
73 |
74 | it('returns an error with an invalid config', function()
75 | local config, err = configLoader('invalid', cliArgs)
76 | assert.is_nil(config)
77 | assert.are.equal('.busted file does not return a table.', err)
78 | end)
79 |
80 | it('returns an error with an invalid run', function()
81 | cliArgs.run = 'invalid'
82 | local config, err = configLoader(testConfig, cliArgs)
83 | assert.is_nil(config)
84 | assert.are.equal('Task `invalid` not found, or not a table.', err)
85 | end)
86 | end)
87 |
--------------------------------------------------------------------------------
/tests/examples/busted/context.lua:
--------------------------------------------------------------------------------
1 | local tablex = require 'pl.tablex'
2 |
3 | local function save()
4 | local g = {}
5 | for k,_ in next, _G, nil do
6 | g[k] = rawget(_G, k)
7 | end
8 | return {
9 | gmt = debug.getmetatable(_G),
10 | g = g,
11 | loaded = tablex.copy(package.loaded)
12 | }
13 | end
14 |
15 | local function restore(state)
16 | setmetatable(_G, state.gmt)
17 | for k,_ in next, _G, nil do
18 | rawset(_G, k, state.g[k])
19 | end
20 | for k,_ in pairs(package.loaded) do
21 | package.loaded[k] = state.loaded[k]
22 | end
23 | end
24 |
25 | return function()
26 | local context = {}
27 |
28 | local data = { descriptor = 'suite', attributes = {} }
29 | local parents = {}
30 | local children = {}
31 | local stack = {}
32 | local states = {}
33 |
34 | function context.ref()
35 | local ref = {}
36 | local ctx = data
37 |
38 | local function unwrap(element, levels)
39 | local levels = levels or 1
40 | local parent = element
41 | for i = 1, levels do
42 | parent = ref.parent(parent)
43 | if not parent then break end
44 | end
45 | if not element.env then element.env = {} end
46 | setmetatable(element.env, {
47 | __newindex = function(self, key, value)
48 | if not parent then
49 | _G[key] = value
50 | else
51 | if not parent.env then parent.env = {} end
52 | parent.env[key] = value
53 | end
54 | end
55 | })
56 | end
57 |
58 | local function push_state(current)
59 | local state = false
60 | if current.attributes.envmode == 'insulate' then
61 | state = save()
62 | elseif current.attributes.envmode == 'unwrap' then
63 | unwrap(current)
64 | elseif current.attributes.envmode == 'expose' then
65 | unwrap(current, 2)
66 | end
67 | table.insert(states, state)
68 | end
69 |
70 | local function pop_state(current)
71 | local state = table.remove(states)
72 | if current.attributes.envmode == 'expose' then
73 | states[#states] = states[#states] and save()
74 | end
75 | if state then
76 | restore(state)
77 | end
78 | end
79 |
80 | function ref.get(key)
81 | if not key then return ctx end
82 | return ctx[key]
83 | end
84 |
85 | function ref.set(key, value)
86 | ctx[key] = value
87 | end
88 |
89 | function ref.clear()
90 | data = { descriptor = 'suite', attributes = {} }
91 | parents = {}
92 | children = {}
93 | stack = {}
94 | states = {}
95 | ctx = data
96 | end
97 |
98 | function ref.attach(child)
99 | if not children[ctx] then children[ctx] = {} end
100 | parents[child] = ctx
101 | table.insert(children[ctx], child)
102 | end
103 |
104 | function ref.children(parent)
105 | return children[parent] or {}
106 | end
107 |
108 | function ref.parent(child)
109 | return parents[child]
110 | end
111 |
112 | function ref.push(current)
113 | if not parents[current] and current ~= data then error('Detached child. Cannot push.') end
114 | if ctx ~= current then push_state(current) end
115 | table.insert(stack, ctx)
116 | ctx = current
117 | end
118 |
119 | function ref.pop()
120 | local current = ctx
121 | ctx = table.remove(stack)
122 | if ctx ~= current then pop_state(current) end
123 | if not ctx then error('Context stack empty. Cannot pop.') end
124 | end
125 |
126 | return ref
127 | end
128 |
129 | return context
130 | end
131 |
--------------------------------------------------------------------------------
/tests/examples/busted/de.lua:
--------------------------------------------------------------------------------
1 | local s = require('say')
2 |
3 | s:set_namespace('de')
4 |
5 | -- 'Pending: test.lua @ 12 \n description
6 | s:set('output.pending', 'Noch nicht erledigt')
7 | s:set('output.failure', 'Fehlgeschlagen')
8 | s:set('output.success', 'Erfolgreich')
9 |
10 | s:set('output.pending_plural', 'übersprungen')
11 | s:set('output.failure_plural', 'fehlgeschlagen')
12 | s:set('output.success_plural', 'erfolgreich')
13 |
14 | s:set('output.pending_zero', 'übersprungen')
15 | s:set('output.failure_zero', 'fehlgeschlagen')
16 | s:set('output.success_zero', 'erfolgreich')
17 |
18 | s:set('output.pending_single', 'übersprungen')
19 | s:set('output.failure_single', 'fehlgeschlagen')
20 | s:set('output.success_single', 'erfolgreich')
21 |
22 | s:set('output.seconds', 'Sekunden')
23 |
24 | -- definitions following are not used within the 'say' namespace
25 | return {
26 | failure_messages = {
27 | 'Du hast %d kaputte Tests.',
28 | 'Deine Tests sind kaputt.',
29 | 'Dein Code ist schlecht; du solltest dich schlecht fühlen.',
30 | 'Dein Code befindet sich in der Gefahrenzone.',
31 | 'Ein seltsames Spiel. Der einzig gewinnbringende Zug ist nicht zu testen.',
32 | 'Meine Großmutter hat auf einem 386er bessere Tests geschrieben.',
33 | 'Immer wenn ein Test fehlschlägt, stirbt ein kleines Kätzchen.',
34 | 'Das fühlt sich schlecht an, oder?'
35 | },
36 | success_messages = {
37 | 'Yeah, die Tests laufen durch.',
38 | 'Fühlt sich gut an, oder?',
39 | 'Großartig!',
40 | 'Tests sind durchgelaufen, Zeit für ein Bier.',
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/tests/examples/busted/done.lua:
--------------------------------------------------------------------------------
1 | local M = {}
2 |
3 | -- adds tokens to the current wait list, does not change order/unordered
4 | M.wait = function(self, ...)
5 | local tlist = { ... }
6 |
7 | for _, token in ipairs(tlist) do
8 | if type(token) ~= 'string' then
9 | error('Wait tokens must be strings. Got '..type(token), 2)
10 | end
11 | table.insert(self.tokens, token)
12 | end
13 | end
14 |
15 | -- set list as unordered, adds tokens to current wait list
16 | M.wait_unordered = function(self, ...)
17 | self.ordered = false
18 | self:wait(...)
19 | end
20 |
21 | -- set list as ordered, adds tokens to current wait list
22 | M.wait_ordered = function(self, ...)
23 | self.ordered = true
24 | self:wait(...)
25 | end
26 |
27 | -- generates a message listing tokens received/open
28 | M.tokenlist = function(self)
29 | local list
30 |
31 | if #self.tokens_done == 0 then
32 | list = 'No tokens received.'
33 | else
34 | list = 'Tokens received ('..tostring(#self.tokens_done)..')'
35 | local s = ': '
36 |
37 | for _,t in ipairs(self.tokens_done) do
38 | list = list .. s .. '\''..t..'\''
39 | s = ', '
40 | end
41 |
42 | list = list .. '.'
43 | end
44 |
45 | if #self.tokens == 0 then
46 | list = list .. ' No more tokens expected.'
47 | else
48 | list = list .. ' Tokens not received ('..tostring(#self.tokens)..')'
49 | local s = ': '
50 |
51 | for _, t in ipairs(self.tokens) do
52 | list = list .. s .. '\''..t..'\''
53 | s = ', '
54 | end
55 |
56 | list = list .. '.'
57 | end
58 |
59 | return list
60 | end
61 |
62 | -- marks a token as completed, checks for ordered/unordered, checks for completeness
63 | M.done = function(self, ...) self:_done(...) end -- extra wrapper for same error level constant as __call method
64 | M._done = function(self, token)
65 | if token then
66 | if type(token) ~= 'string' then
67 | error('Wait tokens must be strings. Got '..type(token), 3)
68 | end
69 |
70 | if self.ordered then
71 | if self.tokens[1] == token then
72 | table.remove(self.tokens, 1)
73 | table.insert(self.tokens_done, token)
74 | else
75 | if self.tokens[1] then
76 | error(('Bad token, expected \'%s\' got \'%s\'. %s'):format(self.tokens[1], token, self:tokenlist()), 3)
77 | else
78 | error(('Bad token (no more tokens expected) got \'%s\'. %s'):format(token, self:tokenlist()), 3)
79 | end
80 | end
81 | else
82 | -- unordered
83 | for i, t in ipairs(self.tokens) do
84 | if t == token then
85 | table.remove(self.tokens, i)
86 | table.insert(self.tokens_done, token)
87 | token = nil
88 | break
89 | end
90 | end
91 |
92 | if token then
93 | error(('Unknown token \'%s\'. %s'):format(token, self:tokenlist()), 3)
94 | end
95 | end
96 | end
97 | if not next(self.tokens) then
98 | -- no more tokens, so we're really done...
99 | self.done_cb()
100 | end
101 | end
102 |
103 |
104 | -- wraps a done callback into a done-object supporting tokens to sign-off
105 | M.new = function(done_callback)
106 | local obj = {
107 | tokens = {},
108 | tokens_done = {},
109 | done_cb = done_callback,
110 | ordered = true, -- default for sign off of tokens
111 | }
112 |
113 | return setmetatable( obj, {
114 | __call = function(self, ...)
115 | self:_done(...)
116 | end,
117 | __index = M,
118 | })
119 | end
120 |
121 | return M
122 |
--------------------------------------------------------------------------------
/tests/examples/busted/en.lua:
--------------------------------------------------------------------------------
1 | local s = require('say')
2 |
3 | s:set_namespace('en')
4 |
5 | -- 'Pending: test.lua @ 12 \n description
6 | s:set('output.pending', 'Pending')
7 | s:set('output.failure', 'Failure')
8 | s:set('output.error', 'Error')
9 | s:set('output.success', 'Success')
10 |
11 | s:set('output.pending_plural', 'pending')
12 | s:set('output.failure_plural', 'failures')
13 | s:set('output.error_plural', 'errors')
14 | s:set('output.success_plural', 'successes')
15 |
16 | s:set('output.pending_zero', 'pending')
17 | s:set('output.failure_zero', 'failures')
18 | s:set('output.error_zero', 'errors')
19 | s:set('output.success_zero', 'successes')
20 |
21 | s:set('output.pending_single', 'pending')
22 | s:set('output.failure_single', 'failure')
23 | s:set('output.error_single', 'error')
24 | s:set('output.success_single', 'success')
25 |
26 | s:set('output.seconds', 'seconds')
27 |
28 | s:set('output.no_test_files_match', 'No test files found matching Lua pattern: %s')
29 | s:set('output.file_not_found', 'Cannot find file or directory: %s')
30 |
31 | -- definitions following are not used within the 'say' namespace
32 | return {
33 | failure_messages = {
34 | 'You have %d busted specs',
35 | 'Your specs are busted',
36 | 'Your code is bad and you should feel bad',
37 | 'Your code is in the Danger Zone',
38 | 'Strange game. The only way to win is not to test',
39 | 'My grandmother wrote better specs on a 3 86',
40 | 'Every time there\'s a failure, drink another beer',
41 | 'Feels bad man'
42 | },
43 | success_messages = {
44 | 'Aww yeah, passing specs',
45 | 'Doesn\'t matter, had specs',
46 | 'Feels good, man',
47 | 'Great success',
48 | 'Tests pass, drink another beer',
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/tests/examples/busted/environment.lua:
--------------------------------------------------------------------------------
1 | local setfenv = require 'busted.compatibility'.setfenv
2 |
3 | return function(context)
4 |
5 | local environment = {}
6 |
7 | local function getEnv(self, key)
8 | if not self then return nil end
9 | return
10 | self.env and self.env[key] or
11 | getEnv(context.parent(self), key) or
12 | _G[key]
13 | end
14 |
15 | local function setEnv(self, key, value)
16 | if not self.env then self.env = {} end
17 | self.env[key] = value
18 | end
19 |
20 | local function __index(self, key)
21 | return getEnv(context.get(), key)
22 | end
23 |
24 | local function __newindex(self, key, value)
25 | setEnv(context.get(), key, value)
26 | end
27 |
28 | local env = setmetatable({}, { __index=__index, __newindex=__newindex })
29 |
30 | function environment.wrap(fn)
31 | return setfenv(fn, env)
32 | end
33 |
34 | function environment.set(key, value)
35 | local env = context.get('env')
36 |
37 | if not env then
38 | env = {}
39 | context.set('env', env)
40 | end
41 |
42 | env[key] = value
43 | end
44 | return environment
45 | end
46 |
--------------------------------------------------------------------------------
/tests/examples/busted/es.lua:
--------------------------------------------------------------------------------
1 | local s = require('say')
2 |
3 | s:set_namespace('es')
4 |
5 | -- 'Pending: test.lua @ 12 \n description
6 | s:set('output.pending', 'Pendiente')
7 | s:set('output.failure', 'Fallo')
8 | s:set('output.error', 'Error')
9 | s:set('output.success', 'Éxito')
10 |
11 | s:set('output.pending_plural', 'pendientes')
12 | s:set('output.failure_plural', 'fallos')
13 | s:set('output.error_plural', 'errores')
14 | s:set('output.success_plural', 'éxitos')
15 |
16 | s:set('output.pending_zero', 'pendientes')
17 | s:set('output.failure_zero', 'fallos')
18 | s:set('output.error_zero', 'errores')
19 | s:set('output.success_zero', 'éxitos')
20 |
21 | s:set('output.pending_single', 'pendiente')
22 | s:set('output.failure_single', 'fallo')
23 | s:set('output.error_single', 'error')
24 | s:set('output.success_single', 'éxito')
25 |
26 | s:set('output.seconds', 'segundos')
27 |
28 | s:set('output.no_test_files_match', 'Ningún fichero de prueba fue encontrado para el patrón de Lua: %s')
29 |
30 | -- definitions following are not used within the 'say' namespace
31 | return {
32 | failure_messages = {
33 | 'Tienes %d especificaciones o pruebas con errores',
34 | 'Tus especificaciones o pruebas están dañadas',
35 | 'Tu código es malo y deberías sentirte mal',
36 | 'Tu código está en la Zona de Peligro',
37 | 'Juego extraño. La única forma de ganar es omitiendo las pruebas',
38 | 'Mi abuela escribió mejores especificaciones en una 386',
39 | 'Cada vez que encuentres un fallo, tómate otra cerveza',
40 | 'Esto no está del todo bien amigo'
41 | },
42 | success_messages = {
43 | 'Ohhh si! Pasando todas las pruebas',
44 | 'No importa, tenía especificaciones',
45 | 'Esto está bien amigo',
46 | 'Un exitazo',
47 | 'Pasaron las pruebas, tómate otra cerveza',
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/tests/examples/busted/execute.lua:
--------------------------------------------------------------------------------
1 | local shuffle = require 'busted.utils'.shuffle
2 | local urandom = require 'busted.utils'.urandom
3 | local tablex = require 'pl.tablex'
4 |
5 | local function sort(elements)
6 | table.sort(elements, function(t1, t2)
7 | if t1.name and t2.name then
8 | return t1.name < t2.name
9 | end
10 | return t2.name ~= nil
11 | end)
12 | return elements
13 | end
14 |
15 | return function(busted)
16 | local block = require 'busted.block'(busted)
17 |
18 | local function execute(runs, options)
19 | local root = busted.context.get()
20 | local children = tablex.copy(busted.context.children(root))
21 |
22 | local function suite_reset()
23 | local oldctx = busted.context.get()
24 |
25 | busted.context.clear()
26 | local ctx = busted.context.get()
27 | for k, v in pairs(oldctx) do
28 | ctx[k] = v
29 | end
30 |
31 | for _, child in ipairs(children) do
32 | for descriptor, _ in pairs(busted.executors) do
33 | child[descriptor] = nil
34 | end
35 | busted.context.attach(child)
36 | end
37 |
38 | busted.randomseed = tonumber(options.seed) or urandom() or os.time()
39 | end
40 |
41 | for i = 1, runs do
42 | if i > 1 then
43 | suite_reset()
44 | root = busted.context.get()
45 | busted.safe_publish('suite', { 'suite', 'reset' }, root, i, runs)
46 | end
47 |
48 | if options.sort then
49 | sort(busted.context.children(root))
50 | elseif options.shuffle then
51 | root.randomseed = busted.randomseed
52 | shuffle(busted.context.children(root), busted.randomseed)
53 | end
54 |
55 | local seed = (busted.randomize and busted.randomseed or nil)
56 | if busted.safe_publish('suite', { 'suite', 'start' }, root, i, runs, seed) then
57 | if block.setup(root) then
58 | busted.execute()
59 | end
60 | block.lazyTeardown(root)
61 | block.teardown(root)
62 | end
63 | busted.safe_publish('suite', { 'suite', 'end' }, root, i, runs)
64 |
65 | if busted.skipAll then
66 | break
67 | end
68 | end
69 | end
70 |
71 | return execute
72 | end
73 |
--------------------------------------------------------------------------------
/tests/examples/busted/execution_order_sync_spec.lua:
--------------------------------------------------------------------------------
1 | local egg = ''
2 |
3 | describe('before_each after_each egg test', function()
4 | setup(function()
5 | egg = egg..'S'
6 | end)
7 |
8 | teardown(function()
9 | egg = egg..'T'
10 | end)
11 |
12 | before_each(function()
13 | egg = egg..'b'
14 | end)
15 |
16 | after_each(function()
17 | egg = egg..'a'
18 | end)
19 |
20 | describe('asd', function()
21 | before_each(function()
22 | egg = egg..'B'
23 | end)
24 |
25 | after_each(function()
26 | egg = egg..'A'
27 | end)
28 |
29 | it('1', function()
30 | assert.equal(egg,'SbB')
31 | egg = egg..'1'
32 | end)
33 |
34 | it('2', function()
35 | assert.equal(egg,'SbB1AabB')
36 | egg = egg..'2'
37 | end)
38 |
39 | describe('jkl', function()
40 | setup(function()
41 | egg = egg..'s'
42 | end)
43 |
44 | teardown(function()
45 | egg = egg..'t'
46 | end)
47 |
48 | before_each(function()
49 | egg = egg..'E'
50 | end)
51 |
52 | after_each(function()
53 | egg = egg..'F'
54 | end)
55 |
56 | it('3', function()
57 | assert.equal(egg,'SbB1AabB2AasbBE')
58 | egg = egg..'3'
59 | end)
60 | end)
61 | end)
62 |
63 | it('4', function()
64 | assert.equal(egg,'SbB1AabB2AasbBE3FAatb')
65 | egg = egg..'4'
66 | end)
67 | end)
68 |
69 | it('5', function()
70 | assert.equal(egg,'SbB1AabB2AasbBE3FAatb4aT')
71 | end)
72 |
73 |
--------------------------------------------------------------------------------
/tests/examples/busted/export_spec.lua:
--------------------------------------------------------------------------------
1 |
2 | describe('tests require "busted"', function()
3 | local describe = describe
4 | local context = context
5 | local insulate = insulate
6 | local expose = expose
7 | local it = it
8 | local pending = pending
9 | local spec = spec
10 | local test = test
11 | local setup = setup
12 | local teardown = teardown
13 | local before_each = before_each
14 | local after_each = after_each
15 | local lazy_setup = lazy_setup
16 | local lazy_teardown = lazy_teardown
17 | local strict_setup = strict_setup
18 | local strict_teardown = strict_teardown
19 |
20 | it('does not export init', function()
21 | assert.is_nil(require 'busted'.init)
22 | end)
23 |
24 | it('does not export file executor', function()
25 | assert.is_nil(require 'busted'.file)
26 | end)
27 |
28 | it('exports describe/it/pending', function()
29 | assert.is_equal(describe, require 'busted'.describe)
30 | assert.is_equal(it, require 'busted'.it)
31 | assert.is_equal(pending, require 'busted'.pending)
32 | end)
33 |
34 | it('exports aliases', function()
35 | assert.is_equal(context, require 'busted'.context)
36 | assert.is_equal(insulate, require 'busted'.insulate)
37 | assert.is_equal(expose, require 'busted'.expose)
38 | assert.is_equal(spec, require 'busted'.spec)
39 | assert.is_equal(test, require 'busted'.test)
40 | end)
41 |
42 | it('exports support functions', function()
43 | assert.is_equal(setup, require 'busted'.setup)
44 | assert.is_equal(teardown, require 'busted'.teardown)
45 | assert.is_equal(lazy_setup, require 'busted'.lazy_setup)
46 | assert.is_equal(lazy_teardown, require 'busted'.lazy_teardown)
47 | assert.is_equal(strict_setup, require 'busted'.strict_setup)
48 | assert.is_equal(strict_teardown, require 'busted'.strict_teardown)
49 | assert.is_equal(before_each, require 'busted'.before_each)
50 | assert.is_equal(after_each, require 'busted'.after_each)
51 | end)
52 |
53 | it('exports assert, mocks, and matchers', function()
54 | assert.is_equal(assert, require 'busted'.assert)
55 | assert.is_equal(spy, require 'busted'.spy)
56 | assert.is_equal(mock, require 'busted'.mock)
57 | assert.is_equal(stub, require 'busted'.stub)
58 | assert.is_equal(match, require 'busted'.match)
59 | end)
60 |
61 | it('exports publish/subscribe', function()
62 | local foo
63 | local publish = require 'busted'.publish
64 | local subscribe = require 'busted'.subscribe
65 | local unsubscribe = require 'busted'.unsubscribe
66 | local sub = subscribe({'export_test'}, function(...) foo = {...} end)
67 | publish({'export_test'}, 'value1', 'value2' )
68 | local unsub = unsubscribe(sub.id, {'export_test'})
69 | publish({'export_test'}, 'new_value1', 'new_value2')
70 | assert.is_same({'value1', 'value2'}, foo)
71 | assert.is_equal(sub, unsub)
72 | end)
73 |
74 | it('exports other functions/variables', function()
75 | assert.is_function(require 'busted'.bindfenv)
76 | assert.is_function(require 'busted'.fail)
77 | assert.is_function(require 'busted'.gettime)
78 | assert.is_function(require 'busted'.monotime)
79 | assert.is_function(require 'busted'.sleep)
80 | assert.is_function(require 'busted'.parent)
81 | assert.is_function(require 'busted'.children)
82 | assert.is_string(require 'busted'.version)
83 | end)
84 |
85 | it('functions cannot be overwritten', function()
86 | local foo = function() assert(false) end
87 | assert.has_error(function() require 'busted'.it = foo end)
88 | assert.is_equal(it, require 'busted'.it)
89 | end)
90 |
91 | it('cannot add new fields', function()
92 | local bar = function() assert(false) end
93 | assert.has_error(function() require 'busted'.foo = bar end)
94 | end)
95 | end)
96 |
--------------------------------------------------------------------------------
/tests/examples/busted/expose_file1.lua:
--------------------------------------------------------------------------------
1 | expose('Tests expose from file root', function()
2 | pl = require 'pl'
3 | _G.global_var = 'this global is in _G'
4 |
5 | it('loads global environment with "List"', function()
6 | assert.is_not_nil(pl)
7 | assert.is_not_nil(List)
8 | end)
9 | end)
10 |
--------------------------------------------------------------------------------
/tests/examples/busted/expose_file2.lua:
--------------------------------------------------------------------------------
1 | describe('Tests environment exposed from previous file', function()
2 | it('global environment still has "List"', function()
3 | assert.is_nil(_G.pl)
4 | assert.is_not_nil(pl)
5 | assert.is_equal('this global is in _G', _G.global_var)
6 | assert.is_not_nil(List)
7 | end)
8 |
9 | it('global environment still has "pl" packages loaded', function()
10 | assert.is_not_nil(package.loaded['pl'])
11 | assert.is_not_nil(package.loaded['pl.List'])
12 | end)
13 | end)
14 |
--------------------------------------------------------------------------------
/tests/examples/busted/file_context_support_spec.lua:
--------------------------------------------------------------------------------
1 | local egg = ''
2 |
3 | setup(function()
4 | egg = egg..'S'
5 | end)
6 |
7 | teardown(function()
8 | egg = egg..'T'
9 | assert.equal('Sb1ab2aT', egg)
10 | end)
11 |
12 | before_each(function()
13 | egg = egg..'b'
14 | end)
15 |
16 | after_each(function()
17 | egg = egg..'a'
18 | end)
19 |
20 | it('file context before_each after_each egg test 1', function()
21 | assert.equal('Sb', egg)
22 | egg = egg..'1'
23 | end)
24 |
25 | it('file context before_each after_each egg test 2', function()
26 | assert.equal('Sb1ab', egg)
27 | egg = egg..'2'
28 | end)
29 |
--------------------------------------------------------------------------------
/tests/examples/busted/file_loader_spec.lua:
--------------------------------------------------------------------------------
1 | local testFileLoader = require 'busted.modules.test_file_loader'(busted, {'lua'})
2 |
3 |
--------------------------------------------------------------------------------
/tests/examples/busted/file_randomize_spec.lua:
--------------------------------------------------------------------------------
1 | local unexpected = {}
2 | local order = {}
3 |
4 | randomize()
5 |
6 | for i = 1, 100 do
7 | table.insert(unexpected, i)
8 |
9 | it('does 100 its', function()
10 | table.insert(order, i)
11 | end)
12 | end
13 |
14 | teardown(function()
15 | assert.are_not.same(unexpected, order)
16 | end)
17 |
--------------------------------------------------------------------------------
/tests/examples/busted/filter_loader.lua:
--------------------------------------------------------------------------------
1 | return function()
2 | local function filter(busted, options)
3 | local getFullName = function(name)
4 | local parent = busted.context.get()
5 | local names = { name }
6 |
7 | while parent and (parent.name or parent.descriptor) and
8 | parent.descriptor ~= 'file' do
9 | table.insert(names, 1, parent.name or parent.descriptor)
10 | parent = busted.context.parent(parent)
11 | end
12 |
13 | return table.concat(names, ' ')
14 | end
15 |
16 | local hasTag = function(name, tag)
17 | local found = name:find('#' .. tag)
18 | return (found ~= nil)
19 | end
20 |
21 | local filterExcludeTags = function(name)
22 | for i, tag in pairs(options.excludeTags) do
23 | if hasTag(name, tag) then
24 | return nil, false
25 | end
26 | end
27 | return nil, true
28 | end
29 |
30 | local filterTags = function(name)
31 | local fullname = getFullName(name)
32 | for i, tag in pairs(options.tags) do
33 | if hasTag(fullname, tag) then
34 | return nil, true
35 | end
36 | end
37 | return nil, (#options.tags == 0)
38 | end
39 |
40 | local filterOutNames = function(name)
41 | for _, filter in pairs(options.filterOut) do
42 | if getFullName(name):find(filter) ~= nil then
43 | return nil, false
44 | end
45 | end
46 | return nil, true
47 | end
48 |
49 | local filterNames = function(name)
50 | for _, filter in pairs(options.filter) do
51 | if getFullName(name):find(filter) ~= nil then
52 | return nil, true
53 | end
54 | end
55 | return nil, (#options.filter == 0)
56 | end
57 |
58 | local printTestName = function(element, parent, status)
59 | if not (options.suppressPending and status == 'pending') then
60 | local fullname = getFullName()
61 | local trace = element.trace
62 | if trace and trace.what == 'Lua' then
63 | fullname = trace.short_src .. ':' .. trace.currentline .. ': ' .. fullname
64 | end
65 | print(fullname)
66 | end
67 | return nil, false
68 | end
69 |
70 | local ignoreAll = function()
71 | return nil, false
72 | end
73 |
74 | local noop = function() end
75 | local stubOut = function(descriptor, name, fn, ...)
76 | if fn == noop then
77 | return nil, true
78 | end
79 | busted.publish({ 'register', descriptor }, name, noop, ...)
80 | return nil, false
81 | end
82 |
83 | local skipOnError = function()
84 | return nil, not busted.skipAll
85 | end
86 |
87 | local applyFilter = function(descriptors, name, fn)
88 | if options[name] and options[name] ~= '' then
89 | for _, descriptor in ipairs(descriptors) do
90 | busted.subscribe({ 'register', descriptor }, fn, { priority = 1 })
91 | end
92 | end
93 | end
94 |
95 | local applyDescFilter = function(descriptors, name, fn)
96 | if options[name] and options[name] ~= '' then
97 | for _, descriptor in ipairs(descriptors) do
98 | local f = function(...) return fn(descriptor, ...) end
99 | busted.subscribe({ 'register', descriptor }, f, { priority = 1 })
100 | end
101 | end
102 | end
103 |
104 | if options.list then
105 | busted.subscribe({ 'suite', 'start' }, ignoreAll, { priority = 1 })
106 | busted.subscribe({ 'suite', 'end' }, ignoreAll, { priority = 1 })
107 | busted.subscribe({ 'file', 'start' }, ignoreAll, { priority = 1 })
108 | busted.subscribe({ 'file', 'end' }, ignoreAll, { priority = 1 })
109 | busted.subscribe({ 'describe', 'start' }, ignoreAll, { priority = 1 })
110 | busted.subscribe({ 'describe', 'end' }, ignoreAll, { priority = 1 })
111 | busted.subscribe({ 'test', 'start' }, ignoreAll, { priority = 1 })
112 | busted.subscribe({ 'test', 'end' }, printTestName, { priority = 1 })
113 | applyDescFilter({ 'setup', 'teardown', 'before_each', 'after_each' }, 'list', stubOut)
114 | applyDescFilter({ 'lazy_setup', 'lazy_teardown' }, 'list', stubOut)
115 | applyDescFilter({ 'strict_setup', 'strict_teardown' }, 'list', stubOut)
116 | applyDescFilter({ 'it', 'pending' }, 'list', stubOut)
117 | end
118 |
119 | applyFilter({ 'lazy_setup', 'lazy_teardown' }, 'nokeepgoing', skipOnError)
120 | applyFilter({ 'strict_setup', 'strict_teardown' }, 'nokeepgoing', skipOnError)
121 | applyFilter({ 'setup', 'teardown', 'before_each', 'after_each' }, 'nokeepgoing', skipOnError)
122 | applyFilter({ 'file', 'describe', 'it', 'pending' }, 'nokeepgoing', skipOnError)
123 |
124 | -- The following filters are applied in reverse order
125 | applyFilter({ 'it', 'pending' } , 'filter' , filterNames )
126 | applyFilter({ 'describe', 'it', 'pending' }, 'filterOut' , filterOutNames )
127 | applyFilter({ 'it', 'pending' } , 'tags' , filterTags )
128 | applyFilter({ 'describe', 'it', 'pending' }, 'excludeTags', filterExcludeTags)
129 | end
130 |
131 | return filter
132 | end
133 |
--------------------------------------------------------------------------------
/tests/examples/busted/fr.lua:
--------------------------------------------------------------------------------
1 | local s = require('say')
2 |
3 | s:set_namespace('fr')
4 |
5 | -- 'Pending: test.lua @ 12 \n description
6 | s:set('output.pending', 'En attente')
7 | s:set('output.failure', 'Echec')
8 | s:set('output.success', 'Reussite')
9 |
10 | s:set('output.pending_plural', 'en attente')
11 | s:set('output.failure_plural', 'echecs')
12 | s:set('output.success_plural', 'reussites')
13 |
14 | s:set('output.pending_zero', 'en attente')
15 | s:set('output.failure_zero', 'echec')
16 | s:set('output.success_zero', 'reussite')
17 |
18 | s:set('output.pending_single', 'en attente')
19 | s:set('output.failure_single', 'echec')
20 | s:set('output.success_single', 'reussite')
21 |
22 | s:set('output.seconds', 'secondes')
23 |
24 | s:set('output.no_test_files_match', 'Aucun test n\'est pourrait trouvé qui corresponde au motif de Lua: %s')
25 |
26 | -- definitions following are not used within the 'say' namespace
27 | return {
28 | failure_messages = {
29 | 'Vous avez %d test(s) qui a/ont echoue(s)',
30 | 'Vos tests ont echoue.',
31 | 'Votre code source est mauvais et vous devrez vous sentir mal',
32 | 'Vous avez un code source de Destruction Massive',
33 | 'Jeu plutot etrange game. Le seul moyen de gagner est de ne pas l\'essayer',
34 | 'Meme ma grand-mere ecrivait de meilleurs tests sur un PIII x86',
35 | 'A chaque erreur, prenez une biere',
36 | 'Ca craint, mon pote'
37 | },
38 | success_messages = {
39 | 'Oh yeah, tests reussis',
40 | 'Pas grave, y\'a eu du succes',
41 | 'C\'est du bon, mon pote. Que du bon!',
42 | 'Reussi, haut la main!',
43 | 'Test reussi. Un de plus. Offre toi une biere, sur mon compte!',
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/tests/examples/busted/helper_loader.lua:
--------------------------------------------------------------------------------
1 | local path = require 'pl.path'
2 | local hasMoon, moonscript = pcall(require, 'moonscript')
3 | local utils = require 'busted.utils'
4 |
5 | return function()
6 | local loadHelper = function(busted, helper, options)
7 | local old_arg = _G.arg
8 | local success, err = pcall(function()
9 | utils.copy_interpreter_args(options.arguments)
10 | _G.arg = options.arguments
11 | if helper:match('%.lua$') then
12 | dofile(path.normpath(helper))
13 | elseif hasMoon and helper:match('%.moon$') then
14 | moonscript.dofile(path.normpath(helper))
15 | else
16 | require(helper)
17 | end
18 | end)
19 |
20 | arg = old_arg
21 |
22 | if not success then
23 | busted.publish({ 'error', 'helper' }, { descriptor = 'helper', name = helper }, nil, err, {})
24 | end
25 | end
26 |
27 | return loadHelper
28 | end
29 |
--------------------------------------------------------------------------------
/tests/examples/busted/init.lua:
--------------------------------------------------------------------------------
1 | local function init(busted)
2 | local block = require 'busted.block'(busted)
3 |
4 | local file = function(file)
5 | busted.wrap(file.run)
6 | if busted.safe_publish('file', { 'file', 'start' }, file) then
7 | block.execute('file', file)
8 | end
9 | busted.safe_publish('file', { 'file', 'end' }, file)
10 | end
11 |
12 | local describe = function(describe)
13 | local parent = busted.context.parent(describe)
14 | if busted.safe_publish('describe', { 'describe', 'start' }, describe, parent) then
15 | block.execute('describe', describe)
16 | end
17 | busted.safe_publish('describe', { 'describe', 'end' }, describe, parent)
18 | end
19 |
20 | local it = function(element)
21 | local parent = busted.context.parent(element)
22 | local finally
23 |
24 | if not block.lazySetup(parent) then
25 | -- skip test if any setup failed
26 | return
27 | end
28 |
29 | if not element.env then element.env = {} end
30 |
31 | block.rejectAll(element)
32 | element.env.finally = function(fn) finally = fn end
33 | element.env.pending = busted.pending
34 |
35 | local pass, ancestor = block.execAll('before_each', parent, true)
36 |
37 | if pass then
38 | local status = busted.status('success')
39 | if busted.safe_publish('test', { 'test', 'start' }, element, parent) then
40 | status:update(busted.safe('it', element.run, element))
41 | if finally then
42 | block.reject('pending', element)
43 | status:update(busted.safe('finally', finally, element))
44 | end
45 | else
46 | status = busted.status('error')
47 | end
48 | busted.safe_publish('test', { 'test', 'end' }, element, parent, tostring(status))
49 | end
50 |
51 | block.dexecAll('after_each', ancestor, true)
52 | end
53 |
54 | local pending = function(element)
55 | local parent = busted.context.parent(element)
56 | local status = 'pending'
57 | if not busted.safe_publish('it', { 'test', 'start' }, element, parent) then
58 | status = 'error'
59 | end
60 | busted.safe_publish('it', { 'test', 'end' }, element, parent, status)
61 | end
62 |
63 | busted.register('file', file, { envmode = 'insulate' })
64 |
65 | busted.register('describe', describe)
66 | busted.register('insulate', 'describe', { envmode = 'insulate' })
67 | busted.register('expose', 'describe', { envmode = 'expose' })
68 |
69 | busted.register('it', it)
70 |
71 | busted.register('pending', pending)
72 |
73 | busted.register('before_each', { envmode = 'unwrap' })
74 | busted.register('after_each', { envmode = 'unwrap' })
75 |
76 | busted.register('lazy_setup', { envmode = 'unwrap' })
77 | busted.register('lazy_teardown', { envmode = 'unwrap' })
78 | busted.register('strict_setup', { envmode = 'unwrap' })
79 | busted.register('strict_teardown', { envmode = 'unwrap' })
80 |
81 | busted.register('setup', 'strict_setup')
82 | busted.register('teardown', 'strict_teardown')
83 |
84 | busted.register('context', 'describe')
85 | busted.register('spec', 'it')
86 | busted.register('test', 'it')
87 |
88 | busted.hide('file')
89 |
90 | local assert = require 'luassert'
91 | local spy = require 'luassert.spy'
92 | local mock = require 'luassert.mock'
93 | local stub = require 'luassert.stub'
94 | local match = require 'luassert.match'
95 |
96 | busted.export('assert', assert)
97 | busted.export('spy', spy)
98 | busted.export('mock', mock)
99 | busted.export('stub', stub)
100 | busted.export('match', match)
101 |
102 | busted.exportApi('publish', busted.publish)
103 | busted.exportApi('subscribe', busted.subscribe)
104 | busted.exportApi('unsubscribe', busted.unsubscribe)
105 |
106 | busted.exportApi('bindfenv', busted.bindfenv)
107 | busted.exportApi('fail', busted.fail)
108 | busted.exportApi('gettime', busted.gettime)
109 | busted.exportApi('monotime', busted.monotime)
110 | busted.exportApi('sleep', busted.sleep)
111 | busted.exportApi('parent', busted.context.parent)
112 | busted.exportApi('children', busted.context.children)
113 | busted.exportApi('version', busted.version)
114 |
115 | busted.bindfenv(assert, 'error', busted.fail)
116 | busted.bindfenv(assert.is_true, 'error', busted.fail)
117 |
118 | return busted
119 | end
120 |
121 | return setmetatable({}, {
122 | __call = function(self, busted)
123 | init(busted)
124 |
125 | return setmetatable(self, {
126 | __index = function(self, key)
127 | return busted.api[key]
128 | end,
129 |
130 | __newindex = function(self, key, value)
131 | error('Attempt to modify busted')
132 | end
133 | })
134 | end
135 | })
136 |
--------------------------------------------------------------------------------
/tests/examples/busted/insulate-expose_spec.lua:
--------------------------------------------------------------------------------
1 | assert.is_nil(package.loaded.pl)
2 | assert.is_nil(package.loaded['pl.file'])
3 |
4 | describe('Tests insulation', function()
5 | insulate('environment inside insulate', function()
6 | pl = require 'pl'
7 | _G.insuated_global = true
8 |
9 | it('updates insuated global table _G', function()
10 | assert.is_not_nil(insuated_global)
11 | assert.is_not_nil(_G.insuated_global)
12 | end)
13 |
14 | it('updates package.loaded', function()
15 | assert.is_not_nil(pl)
16 | assert.is_not_nil(Date)
17 | assert.is_not_nil(package.loaded.pl)
18 | assert.is_not_nil(package.loaded['pl.Date'])
19 | end)
20 | end)
21 |
22 | describe('environment after insulate', function()
23 | it('restores insuated global table _G', function()
24 | assert.is_nil(insuated_global)
25 | assert.is_nil(_G.insuated_global)
26 | end)
27 |
28 | it('restores package.loaded', function()
29 | assert.is_nil(pl)
30 | assert.is_nil(Date)
31 | assert.is_nil(package.loaded.pl)
32 | assert.is_nil(package.loaded['pl.Date'])
33 | end)
34 | end)
35 | end)
36 |
37 | insulate('', function()
38 | describe('Tests expose', function()
39 | insulate('inside insulate block', function()
40 | expose('tests environment inside expose block', function()
41 | pl = require 'pl'
42 | exposed_global = true
43 | _G.global = true
44 |
45 | it('creates exposed global', function()
46 | assert.is_not_nil(exposed_global)
47 | assert.is_nil(_G.exposed_global)
48 | end)
49 |
50 | it('updates global table _G', function()
51 | assert.is_not_nil(global)
52 | assert.is_not_nil(_G.global)
53 | end)
54 |
55 | it('updates package.loaded', function()
56 | assert.is_not_nil(pl)
57 | assert.is_not_nil(Date)
58 | assert.is_not_nil(package.loaded.pl)
59 | assert.is_not_nil(package.loaded['pl.Date'])
60 | end)
61 | end)
62 | end)
63 |
64 | describe('neutralizes insulation', function()
65 | it('creates exposed global in outer block', function()
66 | assert.is_not_nil(exposed_global)
67 | assert.is_nil(_G.exposed_global)
68 | end)
69 |
70 | it('does not restore global table _G', function()
71 | assert.is_not_nil(global)
72 | assert.is_not_nil(_G.global)
73 | end)
74 |
75 | it('does not restore package.loaded', function()
76 | assert.is_not_nil(pl)
77 | assert.is_not_nil(Date)
78 | assert.is_not_nil(package.loaded.pl)
79 | assert.is_not_nil(package.loaded['pl.Date'])
80 | end)
81 | end)
82 | end)
83 |
84 | it('Tests exposed globals does not exist in outer most block', function()
85 | assert.is_nil(pl)
86 | assert.is_nil(exposed_global)
87 | assert.is_nil(_G.exposed_global)
88 | end)
89 |
90 | it('Tests global table _G persists without insulate', function()
91 | assert.is_not_nil(global)
92 | assert.is_not_nil(_G.global)
93 | end)
94 |
95 | it('Tests package.loaded persists without insulate', function()
96 | assert.is_not_nil(Date)
97 | assert.is_not_nil(package.loaded.pl)
98 | assert.is_not_nil(package.loaded['pl.Date'])
99 | end)
100 | end)
101 |
102 | describe('Tests after insulating an expose block', function()
103 | it('restores global table _G', function()
104 | assert.is_nil(global)
105 | assert.is_nil(_G.global)
106 | end)
107 |
108 | it('restores package.loaded', function()
109 | assert.is_nil(pl)
110 | assert.is_nil(Date)
111 | assert.is_nil(package.loaded.pl)
112 | assert.is_nil(package.loaded['pl.Date'])
113 | end)
114 | end)
115 |
116 | describe('Tests insulate/expose', function()
117 | local path = require 'pl.path'
118 | local utils = require 'pl.utils'
119 | local busted_cmd = path.is_windows and 'lua bin/busted' or 'bin/busted'
120 |
121 | local executeBusted = function(args)
122 | local success, exitcode, out, err = utils.executeex(busted_cmd .. ' ' .. args)
123 | if exitcode > 255 then
124 | exitcode = math.floor(exitcode/256), exitcode - math.floor(exitcode/256)*256
125 | end
126 | return not not success, exitcode, out, err
127 | end
128 |
129 | describe('file insulation', function()
130 | it('works between files', function()
131 | local success, exitcode = executeBusted('spec/insulate_file1.lua spec/insulate_file2.lua')
132 | assert.is_true(success)
133 | assert.is_equal(0, exitcode)
134 | end)
135 |
136 | it('works between files independent of order', function()
137 | local success, exitcode = executeBusted('spec/insulate_file2.lua spec/insulate_file1.lua')
138 | assert.is_true(success)
139 | assert.is_equal(0, exitcode)
140 | end)
141 | end)
142 |
143 | describe('expose from file context', function()
144 | it('works between files', function()
145 | local success, exitcode = executeBusted('spec/expose_file1.lua spec/expose_file2.lua')
146 | assert.is_true(success)
147 | assert.is_equal(0, exitcode)
148 | end)
149 | end)
150 | end)
151 |
--------------------------------------------------------------------------------
/tests/examples/busted/insulate_file1.lua:
--------------------------------------------------------------------------------
1 | require 'pl'
2 |
3 | describe('Tests require "pl" in this file', function()
4 | it('loads global environment with "List"', function()
5 | assert.is_not_nil(List)
6 | end)
7 | end)
8 |
9 | describe('Tests require "cl_test_module" in another file', function()
10 | it('does not keep test_module in environment', function()
11 | assert.is_nil(test_module)
12 | assert.is_nil(package.loaded['spec.cl_test_module'])
13 | end)
14 | end)
15 |
--------------------------------------------------------------------------------
/tests/examples/busted/insulate_file2.lua:
--------------------------------------------------------------------------------
1 | test_module = require 'spec.cl_test_module'
2 |
3 | describe('Tests require "cl_test_module" in this file', function()
4 | it('loads environment with "cl_test_module"', function()
5 | assert.is_not_nil(test_module)
6 | assert.is_not_nil(package.loaded['spec.cl_test_module'])
7 | end)
8 | end)
9 |
10 | describe('Tests require "pl" in another file', function()
11 | it('does not keep "List" in environment', function()
12 | assert.is_nil(List)
13 | assert.is_nil(package.loaded['pl.List'])
14 | end)
15 | end)
16 |
--------------------------------------------------------------------------------
/tests/examples/busted/interface_spec.lua:
--------------------------------------------------------------------------------
1 | describe('does a describe', function()
2 | for i = 1, 1000 do
3 | it('does 1000 its', function()
4 | assert(true)
5 | end)
6 | end
7 | end)
8 |
--------------------------------------------------------------------------------
/tests/examples/busted/it.lua:
--------------------------------------------------------------------------------
1 | local s = require('say')
2 |
3 | s:set_namespace('it')
4 |
5 | -- 'Pending: test.lua @ 12 \n description
6 | s:set('output.pending', 'In attesa')
7 | s:set('output.failure', 'Fallimento')
8 | s:set('output.error', 'Errore')
9 | s:set('output.success', 'Successo')
10 |
11 | s:set('output.pending_plural', 'in attesa')
12 | s:set('output.failure_plural', 'fallimenti')
13 | s:set('output.error_plural', 'errori')
14 | s:set('output.success_plural', 'successi')
15 |
16 | s:set('output.pending_zero', 'in attesa')
17 | s:set('output.failure_zero', 'fallimenti')
18 | s:set('output.error_zero', 'errori')
19 | s:set('output.success_zero', 'successi')
20 |
21 | s:set('output.pending_single', 'in attesa')
22 | s:set('output.failure_single', 'fallimento')
23 | s:set('output.error_single', 'errore')
24 | s:set('output.success_single', 'successo')
25 |
26 | s:set('output.seconds', 'secondi')
27 |
28 | s:set('output.no_test_files_match', 'Nessun file di test trovat che corrisponde al pattern Lua: %s')
29 | s:set('output.file_not_found', 'Nessun file o cartella trovato: %s')
30 |
31 | -- definitions following are not used within the 'say' namespace
32 | return {
33 | failure_messages = {
34 | "Hai %d specifiche non conformi",
35 | "Le tue specifiche non sono conformi",
36 | "Il tuo codice fa schifo e dovresti sentirti male per questo",
37 | "Il tuo codice è in pericolo",
38 | "Strano. Il solo modo per terminare con successo i tuoi test è fare nessun test",
39 | "Mia nonna ha scritto migliori specifiche su un 3 86",
40 | "Ogni volta che trovi un errore, bevi un'altra birra",
41 | "I fallimenti fanno male alla salute"
42 | },
43 | success_messages = {
44 | "Ma andiamo! Specifiche Ok!",
45 | "Non importa, avevi le specifiche",
46 | "Bella zio",
47 | "Gran successo",
48 | "Test passato, hai vinto una birra"
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/tests/examples/busted/ja.lua:
--------------------------------------------------------------------------------
1 | local s = require('say')
2 |
3 | s:set_namespace('ja')
4 |
5 | -- 'Pending: test.lua @ 12 \n description
6 | s:set('output.pending', '保留')
7 | s:set('output.failure', '失敗')
8 | s:set('output.success', '成功')
9 |
10 | s:set('output.pending_plural', '保留')
11 | s:set('output.failure_plural', '失敗')
12 | s:set('output.success_plural', '成功')
13 |
14 | s:set('output.pending_zero', '保留')
15 | s:set('output.failure_zero', '失敗')
16 | s:set('output.success_zero', '成功')
17 |
18 | s:set('output.pending_single', '保留')
19 | s:set('output.failure_single', '失敗')
20 | s:set('output.success_single', '成功')
21 |
22 | s:set('output.seconds', '秒')
23 |
24 | -- definitions following are not used within the 'say' namespace
25 | return {
26 | failure_messages = {
27 | '%d個の仕様が破綻しています',
28 | '仕様が破綻しています',
29 | 'あなたの書くコードは良くないので反省するべきです',
30 | 'あなたの書くコードは危険地帯にあります',
31 | 'おかしなゲームです。勝利する唯一の方法はテストをしないことです',
32 | '私の祖母でもPentium Pentium III x86の上でもっといいコードを書いていましたよ',
33 | 'いつも失敗しているのでビールでも飲みましょう',
34 | '罪悪感を持ちましょう',
35 | },
36 | success_messages = {
37 | 'オォーイェー、テストが通った',
38 | '問題ない、テストがある',
39 | '順調ですね',
40 | '大成功',
41 | 'テストが通ったし、ビールでも飲もう',
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/tests/examples/busted/jsfmt.spec.js:
--------------------------------------------------------------------------------
1 | run_spec(__dirname, ["lua"]);
2 | run_spec(__dirname, ["lua"], {
3 | trailingComma: "all",
4 | singleQuote: true,
5 | bracketSpacing: false,
6 | });
7 |
--------------------------------------------------------------------------------
/tests/examples/busted/json.lua:
--------------------------------------------------------------------------------
1 | local json = require 'dkjson'
2 |
3 | return function(options)
4 | local busted = require 'busted'
5 | local handler = require 'busted.outputHandlers.base'()
6 |
7 | handler.suiteEnd = function()
8 | print(json.encode({
9 | pendings = handler.pendings,
10 | successes = handler.successes,
11 | failures = handler.failures,
12 | errors = handler.errors,
13 | duration = handler.getDuration()
14 | }))
15 |
16 | return nil, true
17 | end
18 |
19 | busted.subscribe({ 'suite', 'end' }, handler.suiteEnd)
20 |
21 | return handler
22 | end
23 |
--------------------------------------------------------------------------------
/tests/examples/busted/junit.lua:
--------------------------------------------------------------------------------
1 | local xml = require 'pl.xml'
2 | local string = require("string")
3 |
4 | return function(options)
5 | local busted = require 'busted'
6 | local handler = require 'busted.outputHandlers.base'()
7 | local top = {
8 | start_tick = busted.monotime(),
9 | xml_doc = xml.new('testsuites', {
10 | tests = 0,
11 | errors = 0,
12 | failures = 0,
13 | skip = 0,
14 | })
15 | }
16 | local stack = {}
17 | local testcase_node
18 | if 'table' == type(options.arguments) then
19 | --the first argument should be the name of the xml file.
20 | output_file_name = options.arguments[1]
21 | end
22 |
23 | handler.suiteStart = function(suite, count, total)
24 | local suite_xml = {
25 | start_tick = suite.starttick,
26 | xml_doc = xml.new('testsuite', {
27 | name = 'Run ' .. count .. ' of ' .. total,
28 | tests = 0,
29 | errors = 0,
30 | failures = 0,
31 | skip = 0,
32 | timestamp = os.date('!%Y-%m-%dT%H:%M:%S'),
33 | })
34 | }
35 | top.xml_doc:add_direct_child(suite_xml.xml_doc)
36 | table.insert(stack, top)
37 | top = suite_xml
38 |
39 | return nil, true
40 | end
41 |
42 | local function formatDuration(duration)
43 | return string.format("%.2f", duration)
44 | end
45 |
46 | local function elapsed(start_time)
47 | return formatDuration(busted.monotime() - start_time)
48 | end
49 |
50 | handler.suiteEnd = function(suite, count, total)
51 | local suite_xml = top
52 | suite_xml.xml_doc.attr.time = formatDuration(suite.duration)
53 |
54 | top = table.remove(stack)
55 | top.xml_doc.attr.tests = top.xml_doc.attr.tests + suite_xml.xml_doc.attr.tests
56 | top.xml_doc.attr.errors = top.xml_doc.attr.errors + suite_xml.xml_doc.attr.errors
57 | top.xml_doc.attr.failures = top.xml_doc.attr.failures + suite_xml.xml_doc.attr.failures
58 | top.xml_doc.attr.skip = top.xml_doc.attr.skip + suite_xml.xml_doc.attr.skip
59 |
60 | return nil, true
61 | end
62 |
63 | handler.exit = function()
64 | top.xml_doc.attr.time = elapsed(top.start_tick)
65 | local output_string = xml.tostring(top.xml_doc, '', '\t', nil, false)
66 | local file
67 | if 'string' == type(output_file_name) then
68 | file = io.open(output_file_name, 'w+b' )
69 | end
70 | if file then
71 | file:write(output_string)
72 | file:write('\n')
73 | file:close()
74 | else
75 | print(output_string)
76 | end
77 | return nil, true
78 | end
79 |
80 | local function testStatus(element, parent, message, status, trace)
81 | if status ~= 'success' then
82 | testcase_node:addtag(status)
83 | if status ~= 'pending' and parent and parent.randomseed then
84 | testcase_node:text('Random seed: ' .. parent.randomseed .. '\n')
85 | end
86 | if message then testcase_node:text(message) end
87 | if trace and trace.traceback then testcase_node:text(trace.traceback) end
88 | testcase_node:up()
89 | end
90 | end
91 |
92 | handler.testStart = function(element, parent)
93 | testcase_node = xml.new('testcase', {
94 | classname = element.trace.short_src .. ':' .. element.trace.currentline,
95 | name = handler.getFullName(element),
96 | })
97 | top.xml_doc:add_direct_child(testcase_node)
98 |
99 | return nil, true
100 | end
101 |
102 | handler.testEnd = function(element, parent, status)
103 | top.xml_doc.attr.tests = top.xml_doc.attr.tests + 1
104 | testcase_node:set_attrib("time", formatDuration(element.duration))
105 |
106 | if status == 'success' then
107 | testStatus(element, parent, nil, 'success')
108 | elseif status == 'pending' then
109 | top.xml_doc.attr.skip = top.xml_doc.attr.skip + 1
110 | local formatted = handler.pendings[#handler.pendings]
111 | local trace = element.trace ~= formatted.trace and formatted.trace
112 | testStatus(element, parent, formatted.message, 'skipped', trace)
113 | end
114 |
115 | return nil, true
116 | end
117 |
118 | handler.failureTest = function(element, parent, message, trace)
119 | top.xml_doc.attr.failures = top.xml_doc.attr.failures + 1
120 | testStatus(element, parent, message, 'failure', trace)
121 | return nil, true
122 | end
123 |
124 | handler.errorTest = function(element, parent, message, trace)
125 | top.xml_doc.attr.errors = top.xml_doc.attr.errors + 1
126 | testStatus(element, parent, message, 'error', trace)
127 | return nil, true
128 | end
129 |
130 | handler.error = function(element, parent, message, trace)
131 | if element.descriptor ~= 'it' then
132 | top.xml_doc.attr.errors = top.xml_doc.attr.errors + 1
133 | top.xml_doc:addtag('error')
134 | top.xml_doc:text(message)
135 | if trace and trace.traceback then
136 | top.xml_doc:text(trace.traceback)
137 | end
138 | top.xml_doc:up()
139 | end
140 |
141 | return nil, true
142 | end
143 |
144 | busted.subscribe({ 'exit' }, handler.exit)
145 | busted.subscribe({ 'suite', 'start' }, handler.suiteStart)
146 | busted.subscribe({ 'suite', 'end' }, handler.suiteEnd)
147 | busted.subscribe({ 'test', 'start' }, handler.testStart, { predicate = handler.cancelOnPending })
148 | busted.subscribe({ 'test', 'end' }, handler.testEnd, { predicate = handler.cancelOnPending })
149 | busted.subscribe({ 'error', 'it' }, handler.errorTest)
150 | busted.subscribe({ 'failure', 'it' }, handler.failureTest)
151 | busted.subscribe({ 'error' }, handler.error)
152 | busted.subscribe({ 'failure' }, handler.error)
153 |
154 | return handler
155 | end
156 |
--------------------------------------------------------------------------------
/tests/examples/busted/lua.lua:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env lua
2 | local exit = require 'busted.compatibility'.exit
3 | print(table.concat(arg, ' '))
4 | exit(0)
5 |
--------------------------------------------------------------------------------
/tests/examples/busted/luacov.lua:
--------------------------------------------------------------------------------
1 | return function()
2 | -- Function to initialize luacov if available
3 | local loadLuaCov = function()
4 | local result, luacov = pcall(require, 'luacov.runner')
5 |
6 | if not result then
7 | return print('LuaCov not found on the system, try running without --coverage option, or install LuaCov first')
8 | end
9 |
10 | -- call it to start
11 | luacov()
12 |
13 | -- exclude busted files
14 | table.insert(luacov.configuration.exclude, 'busted_bootstrap$')
15 | table.insert(luacov.configuration.exclude, 'busted%.')
16 | table.insert(luacov.configuration.exclude, 'luassert%.')
17 | table.insert(luacov.configuration.exclude, 'say%.')
18 | table.insert(luacov.configuration.exclude, 'pl%.')
19 | end
20 |
21 | return loadLuaCov
22 | end
23 |
--------------------------------------------------------------------------------
/tests/examples/busted/luacov_spec.lua:
--------------------------------------------------------------------------------
1 | local luacov = require 'busted.modules.luacov'()
2 |
3 |
--------------------------------------------------------------------------------
/tests/examples/busted/moonscript.lua:
--------------------------------------------------------------------------------
1 | local path = require 'pl.path'
2 |
3 | local ok, moonscript, line_tables, util = pcall(function()
4 | return require 'moonscript', require 'moonscript.line_tables', require 'moonscript.util'
5 | end)
6 |
7 | local _cache = {}
8 |
9 | -- find the line number of `pos` chars into fname
10 | local lookup_line = function(fname, pos)
11 | if not _cache[fname] then
12 | local f = io.open(fname)
13 | _cache[fname] = f:read('*a')
14 | f:close()
15 | end
16 |
17 | return util.pos_to_line(_cache[fname], pos)
18 | end
19 |
20 | local rewrite_linenumber = function(fname, lineno)
21 | local tbl = line_tables['@' .. fname]
22 | if fname and tbl then
23 | for i = lineno, 0 ,-1 do
24 | if tbl[i] then
25 | return lookup_line(fname, tbl[i])
26 | end
27 | end
28 | end
29 |
30 | return lineno
31 | end
32 |
33 | local rewrite_filename = function(filename)
34 | -- sometimes moonscript gives files like [string "./filename.moon"], so
35 | -- we'll chop it up to only get the filename.
36 | return filename:match('string "(.+)"') or filename
37 | end
38 |
39 | local rewrite_traceback = function(fname, trace)
40 | local rewrite_one = function(line, pattern, sub)
41 | if line == nil then return '' end
42 |
43 | local fname, lineno = line:match(pattern)
44 |
45 | if fname and lineno then
46 | fname = rewrite_filename(fname)
47 | local new_lineno = rewrite_linenumber(fname, tonumber(lineno))
48 | if new_lineno then
49 | line = line:gsub(sub:format(tonumber(lineno)), sub:format(tonumber(new_lineno)))
50 | end
51 | end
52 |
53 | return line
54 | end
55 |
56 | local lines = {}
57 | local j = 0
58 |
59 | for line in trace:gmatch('[^\r\n]+') do
60 | j = j + 1
61 | line = rewrite_one(line, '%s*(.-):(%d+): ', ':%d:')
62 | line = rewrite_one(line, '<(.*):(%d+)>', ':%d>')
63 | lines[j] = line
64 | end
65 |
66 | return '\n' .. table.concat(lines, trace:match('[\r\n]+')) .. '\n'
67 | end
68 |
69 | local ret = {}
70 |
71 | local getTrace = function(filename, info)
72 | local index = info.traceback:find('\n%s*%[C]')
73 | info.traceback = info.traceback:sub(1, index)
74 |
75 | info.short_src = rewrite_filename(info.short_src)
76 | info.traceback = rewrite_traceback(filename, info.traceback)
77 | info.linedefined = rewrite_linenumber(filename, info.linedefined)
78 | info.currentline = rewrite_linenumber(filename, info.currentline)
79 |
80 | return info
81 | end
82 |
83 | local rewriteMessage = function(filename, message)
84 | local fname, line, msg = message:match('^([^\n]-):(%d+): (.*)')
85 | if not fname then
86 | return message
87 | end
88 |
89 | fname = rewrite_filename(fname)
90 | line = rewrite_linenumber(fname, tonumber(line))
91 |
92 | return fname .. ':' .. tostring(line) .. ': ' .. msg
93 | end
94 |
95 | ret.match = function(busted, filename)
96 | return ok and path.extension(filename) == '.moon'
97 | end
98 |
99 | ret.load = function(busted, filename)
100 | local file, err = moonscript.loadfile(filename)
101 | if not file then
102 | busted.publish({ 'error', 'file' }, { descriptor = 'file', name = filename }, nil, err, {})
103 | end
104 | return file, getTrace, rewriteMessage
105 | end
106 |
107 | return ret
108 |
--------------------------------------------------------------------------------
/tests/examples/busted/nl.lua:
--------------------------------------------------------------------------------
1 | local s = require('say')
2 |
3 | s:set_namespace('nl')
4 |
5 | -- 'Pending: test.lua @ 12 \n description
6 | s:set('output.pending', 'Hangend')
7 | s:set('output.failure', 'Mislukt')
8 | s:set('output.success', 'Succes')
9 |
10 | s:set('output.pending_plural', 'hangenden')
11 | s:set('output.failure_plural', 'mislukkingen')
12 | s:set('output.success_plural', 'successen')
13 |
14 | s:set('output.pending_zero', 'hangend')
15 | s:set('output.failure_zero', 'mislukt')
16 | s:set('output.success_zero', 'successen')
17 |
18 | s:set('output.pending_single', 'hangt')
19 | s:set('output.failure_single', 'mislukt')
20 | s:set('output.success_single', 'succes')
21 |
22 | s:set('output.seconds', 'seconden')
23 |
24 | -- definitions following are not used within the 'say' namespace
25 | return {
26 | failure_messages = {
27 | 'Je hebt %d busted specs',
28 | 'Je specs zijn busted',
29 | 'Je code is slecht en zo zou jij je ook moeten voelen',
30 | 'Je code zit in de Gevaren Zone',
31 | 'Vreemd spelletje. The enige manier om te winnen is door niet te testen',
32 | 'Mijn oma schreef betere specs op een 3 86',
33 | 'Elke keer dat iets mislukt, nog een biertje drinken',
34 | 'Voelt klote man'
35 | },
36 | success_messages = {
37 | 'Joeperdepoep, de specs zijn er door',
38 | 'Doet er niet toe, had specs',
39 | 'Voelt goed, man',
40 | 'Fantastisch success',
41 | 'Testen geslaagd, neem nog een biertje',
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/tests/examples/busted/options.lua:
--------------------------------------------------------------------------------
1 | return {
2 | standalone = true,
3 | output = nil,
4 | }
5 |
--------------------------------------------------------------------------------
/tests/examples/busted/output_handler_loader.lua:
--------------------------------------------------------------------------------
1 | local path = require 'pl.path'
2 | local hasMoon, moonscript = pcall(require, 'moonscript')
3 | local utils = require 'busted.utils'
4 |
5 | return function()
6 | local loadOutputHandler = function(busted, output, options)
7 | local handler
8 |
9 | utils.copy_interpreter_args(options.arguments)
10 | local success, err = pcall(function()
11 | if output:match('%.lua$') then
12 | handler = dofile(path.normpath(output))
13 | elseif hasMoon and output:match('%.moon$') then
14 | handler = moonscript.dofile(path.normpath(output))
15 | else
16 | handler = require('busted.outputHandlers.' .. output)
17 | end
18 | end)
19 |
20 | if not success and err:match("module '.-' not found:") then
21 | success, err = pcall(function() handler = require(output) end)
22 | end
23 |
24 | if not success then
25 | busted.publish({ 'error', 'output' }, { descriptor = 'output', name = output }, nil, err, {})
26 | handler = require('busted.outputHandlers.' .. options.defaultOutput)
27 | end
28 |
29 | if options.enableSound then
30 | require 'busted.outputHandlers.sound'(options)
31 | end
32 |
33 | handler(options):subscribe(options)
34 | end
35 |
36 | return loadOutputHandler
37 | end
38 |
--------------------------------------------------------------------------------
/tests/examples/busted/output_handler_loader_spec.lua:
--------------------------------------------------------------------------------
1 | local outputHandlerLoader = require 'busted.modules.output_handler_loader'()
2 |
3 |
--------------------------------------------------------------------------------
/tests/examples/busted/pt-BR.lua:
--------------------------------------------------------------------------------
1 | local s = require('say')
2 |
3 | s:set_namespace('pt-BR')
4 |
5 | -- 'Pending: test.lua @ 12 \n description
6 | s:set('output.pending', 'Pendente')
7 | s:set('output.failure', 'Falha')
8 | s:set('output.error', 'Erro')
9 | s:set('output.success', 'Sucesso')
10 |
11 | s:set('output.pending_plural', 'pendentes')
12 | s:set('output.failure_plural', 'falhas')
13 | s:set('output.error_plural', 'erros')
14 | s:set('output.success_plural', 'sucessos')
15 |
16 | s:set('output.pending_zero', 'pendentes')
17 | s:set('output.failure_zero', 'falhas')
18 | s:set('output.error_zero', 'erros')
19 | s:set('output.success_zero', 'sucessos')
20 |
21 | s:set('output.pending_single', 'pendente')
22 | s:set('output.failure_single', 'falha')
23 | s:set('output.error_single', 'erro')
24 | s:set('output.success_single', 'sucesso')
25 |
26 | s:set('output.seconds', 'segundos')
27 |
28 | s:set('output.no_test_files_match', 'Nenhum arquivo de teste encontrado com o padrão do Lua: %s')
29 |
30 | -- definitions following are not used within the 'say' namespace
31 | return {
32 | failure_messages = {
33 | 'Você tem %d testes quebrados',
34 | 'Seus testes estão quebrados',
35 | 'Seu código está mal e você deveria sentir-se mal',
36 | 'Seu código está na zona de perigo',
37 | 'Jogo estranho. A única forma de ganhar é não testar',
38 | 'Minha avó escreveu testes melhores em um 386',
39 | 'Cada vez que encontrar uma falha, beba outra cerveja',
40 | 'Isso não está poético'
41 | },
42 | success_messages = {
43 | 'Perfeito! Todos os testes estão passando',
44 | 'Não se preocupe, tem testes',
45 | 'Isso está poético',
46 | 'Excelente',
47 | 'Os testes passaram, beba outra cerveja',
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/tests/examples/busted/randomize_spec.lua:
--------------------------------------------------------------------------------
1 | local unexpected = {}
2 | local order = {}
3 | local orderfixed1 = {}
4 | local orderfixed2 = {}
5 |
6 | describe('Randomizing test order', function()
7 | randomize()
8 |
9 | for i = 1, 100 do
10 | table.insert(unexpected, i)
11 |
12 | it('does 100 its', function()
13 | table.insert(order, i)
14 | end)
15 | end
16 | end)
17 |
18 | describe('Randomizing test order with fixed seed as first arg', function()
19 | randomize(3210)
20 |
21 | for i = 1, 10 do
22 | it('does 10 its', function()
23 | table.insert(orderfixed1, i)
24 | end)
25 | end
26 | end)
27 |
28 | describe('Randomizing test order with fixed seed as second arg', function()
29 | randomize(true, 56789)
30 |
31 | for i = 1, 10 do
32 | it('does 10 its', function()
33 | table.insert(orderfixed2, i)
34 | end)
35 | end
36 | end)
37 |
38 | describe('Order of tests ran', function()
39 | local function shuffle(t, seed)
40 | math.randomseed(seed)
41 | local n = #t
42 | while n >= 1 do
43 | local k = math.random(n)
44 | t[n], t[k] = t[k], t[n]
45 | n = n - 1
46 | end
47 | return t
48 | end
49 |
50 | it('randomized', function()
51 | assert.are_not.same(unexpected, order)
52 | end)
53 |
54 | it('randomized with known random seed: 3210', function()
55 | local t = {1,2,3,4,5,6,7,8,9,10}
56 | assert.are.same(shuffle(t, 3210), orderfixed1)
57 | end)
58 |
59 | it('randomized with known random seed: 56789', function()
60 | local t = {1,2,3,4,5,6,7,8,9,10}
61 | assert.are.same(shuffle(t, 56789), orderfixed2)
62 | end)
63 | end)
64 |
65 | describe('Disabling randomized test order with randomize(false)', function()
66 | randomize()
67 | randomize(false)
68 |
69 | local expected = {}
70 | local order = {}
71 |
72 | for i = 1, 100 do
73 | table.insert(expected, i)
74 |
75 | it('does 100 its', function()
76 | table.insert(order, i)
77 | end)
78 | end
79 |
80 | it('does not randomize tests', function()
81 | assert.are.same(expected, order)
82 | end)
83 | end)
84 |
85 | describe('Disabling randomized test order with randomize(nil)', function()
86 | randomize()
87 | randomize(nil)
88 |
89 | local expected = {}
90 | local order = {}
91 |
92 | for i = 1, 100 do
93 | table.insert(expected, i)
94 |
95 | it('does 100 its', function()
96 | table.insert(order, i)
97 | end)
98 | end
99 |
100 | it('does not randomize tests', function()
101 | assert.are.same(expected, order)
102 | end)
103 | end)
104 |
--------------------------------------------------------------------------------
/tests/examples/busted/ru.lua:
--------------------------------------------------------------------------------
1 | local s = require('say')
2 |
3 | s:set_namespace('ru')
4 |
5 | -- 'Pending: test.lua @ 12 \n description
6 | s:set('output.pending', 'Ожидает')
7 | s:set('output.failure', 'Поломалcя')
8 | s:set('output.success', 'Прошeл')
9 |
10 | s:set('output.pending_plural', 'ожидают')
11 | s:set('output.failure_plural', 'поломалиcь')
12 | s:set('output.success_plural', 'прошли')
13 |
14 | s:set('output.pending_zero', 'ожидающих')
15 | s:set('output.failure_zero', 'поломанных')
16 | s:set('output.success_zero', 'прошедших')
17 |
18 | s:set('output.pending_single', 'ожидает')
19 | s:set('output.failure_single', 'поломался')
20 | s:set('output.success_single', 'прошел')
21 |
22 | s:set('output.seconds', 'секунд')
23 |
24 | ---- definitions following are not used within the 'say' namespace
25 | return {
26 | failure_messages = {
27 | 'У тебя %d просратых тестов',
28 | 'Твои тесты поломаны',
29 | 'Твой код говеный - пойди напейся!'
30 | },
31 | success_messages = {
32 | 'Поехали!',
33 | 'Жизнь - хороша!',
34 | 'Ффух в этот раз пронесло!',
35 | 'Ура!'
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/tests/examples/busted/sound.lua:
--------------------------------------------------------------------------------
1 | local app = require 'pl.app'
2 | return function(options)
3 | local busted = require 'busted'
4 | local handler = require 'busted.outputHandlers.base'()
5 | local language = require('busted.languages.' .. options.language)
6 |
7 | handler.suiteEnd = function()
8 | local system = app.platform()
9 | local sayer_pre, sayer_post
10 | local messages
11 |
12 | if system == 'Linux' then
13 | sayer_pre = 'espeak -s 160 '
14 | sayer_post = ' > /dev/null 2>&1'
15 | elseif system and system:match('^Windows') then
16 | sayer_pre = 'echo '
17 | sayer_post = ' | ptts'
18 | else
19 | sayer_pre = 'say '
20 | sayer_post = ''
21 | end
22 |
23 | if handler.failuresCount > 0 then
24 | messages = language.failure_messages
25 | else
26 | messages = language.success_messages
27 | end
28 |
29 | io.popen(sayer_pre .. '"' .. messages[math.random(1, #messages)] .. '"' .. sayer_post)
30 |
31 | return nil, true
32 | end
33 |
34 | busted.subscribe({ 'suite', 'end' }, handler.suiteEnd)
35 |
36 | return handler
37 | end
38 |
--------------------------------------------------------------------------------
/tests/examples/busted/standalone_loader.lua:
--------------------------------------------------------------------------------
1 | local getTrace = function(filename, info)
2 | local index = info.traceback:find('\n%s*%[C]')
3 | info.traceback = info.traceback:sub(1, index)
4 | return info
5 | end
6 |
7 | return function(busted)
8 | local loadCurrentFile = function(info, options)
9 | local filename = 'string'
10 | if info.source:sub(1,1) == '@' or info.source:sub(1,1) == '=' then
11 | filename = info.source:sub(2)
12 | end
13 |
14 | -- Setup test file to be compatible with live coding
15 | if info.func then
16 | local file = setmetatable({
17 | getTrace = getTrace,
18 | rewriteMessage = nil
19 | }, {
20 | __call = info.func
21 | })
22 |
23 | busted.executors.file(filename, file)
24 | end
25 | end
26 |
27 | return loadCurrentFile
28 | end
29 |
--------------------------------------------------------------------------------
/tests/examples/busted/status.lua:
--------------------------------------------------------------------------------
1 | local function get_status(status)
2 | local smap = {
3 | ['success'] = 'success',
4 | ['pending'] = 'pending',
5 | ['failure'] = 'failure',
6 | ['error'] = 'error',
7 | ['true'] = 'success',
8 | ['false'] = 'failure',
9 | ['nil'] = 'error',
10 | }
11 | return smap[tostring(status)] or 'error'
12 | end
13 |
14 | return function(inital_status)
15 | local objstat = get_status(inital_status)
16 | local obj = {
17 | success = function(self) return (objstat == 'success') end,
18 | pending = function(self) return (objstat == 'pending') end,
19 | failure = function(self) return (objstat == 'failure') end,
20 | error = function(self) return (objstat == 'error') end,
21 |
22 | get = function(self)
23 | return objstat
24 | end,
25 |
26 | set = function(self, status)
27 | objstat = get_status(status)
28 | end,
29 |
30 | update = function(self, status)
31 | -- prefer current failure/error status over new status
32 | status = get_status(status)
33 | if objstat == 'success' or (objstat == 'pending' and status ~= 'success') then
34 | objstat = status
35 | end
36 | end
37 | }
38 |
39 | return setmetatable(obj, {
40 | __index = {},
41 | __tostring = function(self) return objstat end
42 | })
43 | end
44 |
--------------------------------------------------------------------------------
/tests/examples/busted/strict.lua:
--------------------------------------------------------------------------------
1 | -- strict.lua
2 | -- checks uses of undeclared global variables
3 | -- All global variables must be 'declared' through a regular assignment
4 | -- (even assigning nil will do) in a main chunk before being used
5 | -- anywhere or assigned to inside a function.
6 | -- distributed under the Lua license: http://www.lua.org/license.html
7 |
8 | local getinfo, error, rawset, rawget = debug.getinfo, error, rawset, rawget
9 |
10 | local mt = getmetatable(_G)
11 | if mt == nil then
12 | mt = {}
13 | setmetatable(_G, mt)
14 | end
15 |
16 | mt.__declared = {}
17 |
18 | local function what ()
19 | local d = getinfo(3, "S")
20 | return d and d.what or "C"
21 | end
22 |
23 | mt.__newindex = function (t, n, v)
24 | if not mt.__declared[n] then
25 | local w = what()
26 | if w ~= "main" and w ~= "C" then
27 | error("assign to undeclared variable '"..n.."'", 2)
28 | end
29 | mt.__declared[n] = true
30 | end
31 | rawset(t, n, v)
32 | end
33 |
34 | mt.__index = function (t, n)
35 | if not mt.__declared[n] and what() ~= "C" then
36 | error("variable '"..n.."' is not declared", 2)
37 | end
38 | return rawget(t, n)
39 | end
40 |
--------------------------------------------------------------------------------
/tests/examples/busted/strict_spec.lua:
--------------------------------------------------------------------------------
1 | require 'spec.strict'
2 |
3 | describe('runs a single successful test with strict', function()
4 |
5 | it('is a succesful test with strict', function()
6 | -- nothing here, makes it succeed
7 | end)
8 |
9 | end)
10 |
--------------------------------------------------------------------------------
/tests/examples/busted/terra.lua:
--------------------------------------------------------------------------------
1 | local path = require 'pl.path'
2 |
3 | local ret = {}
4 | local ok, terralib = pcall(function() return require 'terralib' end)
5 |
6 | local getTrace = function(filename, info)
7 | local index = info.traceback:find('\n%s*%[C]')
8 | info.traceback = info.traceback:sub(1, index)
9 | return info
10 | end
11 |
12 | ret.match = function(busted, filename)
13 | return ok and path.extension(filename) == '.t'
14 | end
15 |
16 | ret.load = function(busted, filename)
17 | local file, err = terralib.loadfile(filename)
18 | if not file then
19 | busted.publish({ 'error', 'file' }, { descriptor = 'file', name = filename }, nil, err, {})
20 | end
21 | return file, getTrace
22 | end
23 |
24 | return ret
25 |
--------------------------------------------------------------------------------
/tests/examples/busted/test_file_loader.lua:
--------------------------------------------------------------------------------
1 | local s = require 'say'
2 |
3 | return function(busted, loaders)
4 | local path = require 'pl.path'
5 | local dir = require 'pl.dir'
6 | local tablex = require 'pl.tablex'
7 | local fileLoaders = {}
8 |
9 | for _, v in pairs(loaders) do
10 | local loader = require('busted.modules.files.'..v)
11 | fileLoaders[#fileLoaders+1] = loader
12 | end
13 |
14 | local getTestFiles = function(rootFile, patterns, options)
15 | local fileList
16 |
17 | if path.isfile(rootFile) then
18 | fileList = { rootFile }
19 | elseif path.isdir(rootFile) then
20 | local getfiles = options.recursive and dir.getallfiles or dir.getfiles
21 | fileList = getfiles(rootFile)
22 |
23 | fileList = tablex.filter(fileList, function(filename)
24 | local basename = path.basename(filename)
25 | for _, patt in ipairs(options.excludes) do
26 | if patt ~= '' and basename:find(patt) then
27 | return nil
28 | end
29 | end
30 | for _, patt in ipairs(patterns) do
31 | if basename:find(patt) then
32 | return true
33 | end
34 | end
35 | return #patterns == 0
36 | end)
37 |
38 | fileList = tablex.filter(fileList, function(filename)
39 | if path.is_windows then
40 | return not filename:find('%\\%.%w+.%w+')
41 | else
42 | return not filename:find('/%.%w+.%w+')
43 | end
44 | end)
45 | else
46 | busted.publish({ 'error' }, {}, nil, s('output.file_not_found'):format(rootFile), {})
47 | fileList = {}
48 | end
49 |
50 | table.sort(fileList)
51 | return fileList
52 | end
53 |
54 | local getAllTestFiles = function(rootFiles, patterns, options)
55 | local fileList = {}
56 | for _, root in ipairs(rootFiles) do
57 | tablex.insertvalues(fileList, getTestFiles(root, patterns, options))
58 | end
59 | return fileList
60 | end
61 |
62 | -- runs a testfile, loading its tests
63 | local loadTestFile = function(busted, filename)
64 | for _, v in pairs(fileLoaders) do
65 | if v.match(busted, filename) then
66 | return v.load(busted, filename)
67 | end
68 | end
69 | end
70 |
71 | local loadTestFiles = function(rootFiles, patterns, options)
72 | local fileList = getAllTestFiles(rootFiles, patterns, options)
73 |
74 | for i, fileName in ipairs(fileList) do
75 | local testFile, getTrace, rewriteMessage = loadTestFile(busted, fileName)
76 |
77 | if testFile then
78 | local file = setmetatable({
79 | getTrace = getTrace,
80 | rewriteMessage = rewriteMessage
81 | }, {
82 | __call = testFile
83 | })
84 |
85 | busted.executors.file(fileName, file)
86 | end
87 | end
88 |
89 | if #fileList == 0 then
90 | local pattern = patterns[1]
91 | if #patterns > 1 then
92 | pattern = '\n\t' .. table.concat(patterns, '\n\t')
93 | end
94 | busted.publish({ 'error' }, {}, nil, s('output.no_test_files_match'):format(pattern), {})
95 | end
96 |
97 | return fileList
98 | end
99 |
100 | return loadTestFiles, loadTestFile, getAllTestFiles
101 | end
102 |
103 |
--------------------------------------------------------------------------------
/tests/examples/busted/th.lua:
--------------------------------------------------------------------------------
1 | local s = require('say')
2 |
3 | s:set_namespace('th')
4 |
5 | -- 'Pending: test.lua @ 12 \n description
6 | s:set('output.pending', 'อยู่ระหว่างดำเนินการ')
7 | s:set('output.failure', 'ล้มเหลว')
8 | s:set('output.success', 'สำเร็จ')
9 |
10 | s:set('output.pending_plural', 'อยู่ระหว่างดำเนินการ')
11 | s:set('output.failure_plural', 'ล้มเหลว')
12 | s:set('output.success_plural', 'สำเร็จ')
13 |
14 | s:set('output.pending_zero', 'อยู่ระหว่างดำเนินการ')
15 | s:set('output.failure_zero', 'ล้มเหลว')
16 | s:set('output.success_zero', 'สำเร็จ')
17 |
18 | s:set('output.pending_single', 'อยู่ระหว่างดำเนินการ')
19 | s:set('output.failure_single', 'ล้มเหลว')
20 | s:set('output.success_single', 'สำเร็จ')
21 |
22 | s:set('output.seconds', 'วินาที')
23 |
24 | -- definitions following are not used within the 'say' namespace
25 | return {
26 | failure_messages = {
27 | 'คุณมี %d บัสเต็ดสเปค',
28 | 'สเปคของคุณคือ บัสเต็ด',
29 | 'โค้ดของคุณไม่ดีเลย คุณควรรู้สึกแย่น่ะ',
30 | 'โค้ดของคุณอยู่ในเขตอันตราย!',
31 | 'มันแปลกๆน่ะ วิธีที่จะชนะไม่ได้มีแค่เทสอย่างเดียว',
32 | 'ยายผมเขียนสเปคดีกว่านี้อีก บนเครื่อง 386',
33 | 'ทุกๆครั้งที่ล้มเหลว, ดื่มเบียร์แก้วใหม่',
34 | 'แย่จัง นายท่าน'
35 | },
36 | success_messages = {
37 | 'อุ๊ตะ!!!, สเปคผ่าน!',
38 | 'ไม่สำคัญ, มีสเปค',
39 | 'ฟินเลยดิ นายท่าน',
40 | 'สำเร็จ ยอดเยี่ยม',
41 | 'เทสผ่าน, ดื่มเบียร์ๆๆๆ',
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/tests/examples/busted/ua.lua:
--------------------------------------------------------------------------------
1 | local s = require('say')
2 |
3 | s:set_namespace('ua')
4 |
5 | -- 'Pending: test.lua @ 12 \n description
6 | s:set('output.pending', 'Очікує')
7 | s:set('output.failure', 'Зламався')
8 | s:set('output.success', 'Пройшов')
9 |
10 | s:set('output.pending_plural', 'очікують')
11 | s:set('output.failure_plural', 'зламались')
12 | s:set('output.success_plural', 'пройшли')
13 |
14 | s:set('output.pending_zero', 'очікуючих')
15 | s:set('output.failure_zero', 'зламаних')
16 | s:set('output.success_zero', 'пройдених')
17 |
18 | s:set('output.pending_single', 'очікує')
19 | s:set('output.failure_single', 'зламався')
20 | s:set('output.success_single', 'пройшов')
21 |
22 | s:set('output.seconds', 'секунд')
23 |
24 |
25 | ---- definitions following are not used within the 'say' namespace
26 | return {
27 | failure_messages = {
28 | 'Ти зрадив %d тестів!',
29 | 'Ой йо..',
30 | 'Вороги поламали наші тести!'
31 | },
32 | success_messages = {
33 | 'Слава Україні! Героям Слава!',
34 | 'Тестування успішно пройдено!',
35 | 'Всі баги знищено!'
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/tests/examples/busted/utils.lua:
--------------------------------------------------------------------------------
1 | return {
2 | copy_interpreter_args = function(arguments)
3 | -- copy non-positive command-line args auto-inserted by Lua interpreter
4 | if arguments and _G.arg then
5 | local i = 0
6 | while _G.arg[i] do
7 | arguments[i] = _G.arg[i]
8 | i = i - 1
9 | end
10 | end
11 | end,
12 |
13 | split = require 'pl.utils'.split,
14 |
15 | shuffle = function(t, seed)
16 | if seed then math.randomseed(seed) end
17 | local n = #t
18 | while n >= 2 do
19 | local k = math.random(n)
20 | t[n], t[k] = t[k], t[n]
21 | n = n - 1
22 | end
23 | return t
24 | end,
25 |
26 | urandom = function()
27 | local f = io.open('/dev/urandom', 'rb')
28 | if not f then return nil end
29 | local s = f:read(4) f:close()
30 | local bytes = {s:byte(1, 4)}
31 | local value = 0
32 | for _, v in ipairs(bytes) do
33 | value = value * 256 + v
34 | end
35 | return value
36 | end,
37 | }
38 |
--------------------------------------------------------------------------------
/tests/examples/busted/zh.lua:
--------------------------------------------------------------------------------
1 | local s = require('say')
2 |
3 | s:set_namespace('zh')
4 |
5 | -- 'Pending: test.lua @ 12 \n description
6 | s:set('output.pending', '开发中')
7 | s:set('output.failure', '失败')
8 | s:set('output.success', '成功')
9 |
10 | s:set('output.pending_plural', '开发中')
11 | s:set('output.failure_plural', '失败')
12 | s:set('output.success_plural', '成功')
13 |
14 | s:set('output.pending_zero', '开发中')
15 | s:set('output.failure_zero', '失败')
16 | s:set('output.success_zero', '成功')
17 |
18 | s:set('output.pending_single', '开发中')
19 | s:set('output.failure_single', '失败')
20 | s:set('output.success_single', '成功')
21 |
22 | s:set('output.seconds', '秒')
23 |
24 | -- definitions following are not used within the 'say' namespace
25 | return {
26 | failure_messages = {
27 | '你一共提交了[%d]个测试用例',
28 | '又出错了!',
29 | '到底哪里不对呢?',
30 | '出错了,又要加班了!',
31 | '囧,出Bug了!',
32 | '据说比尔盖兹也写了一堆Bug,别灰心!',
33 | '又出错了,休息一下吧',
34 | 'Bug好多,心情好坏!'
35 | },
36 | success_messages = {
37 | '牛X,测试通过了!',
38 | '测试通过了,感觉不错吧,兄弟!',
39 | '哥们,干得漂亮!',
40 | '终于通过了!干一杯先!',
41 | '阿弥陀佛~,菩萨显灵了!',
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/tests/examples/misc/__snapshots__/jsfmt.spec.js.snap:
--------------------------------------------------------------------------------
1 | // Jest Snapshot v1, https://goo.gl/fbAQLP
2 |
3 | exports[`hook.lua - lua-verify: hook.lua 1`] = `
4 |
5 | hook.Add("hello", "okay", function(some, arguments)
6 | doSomething()
7 | return false
8 | end)
9 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
10 | hook.Add("hello", "okay", function(some, arguments)
11 | doSomething()
12 | return false
13 | end)
14 |
15 | `;
16 |
17 | exports[`local_with_call_near_print_width.lua - lua-verify: local_with_call_near_print_width.lua 1`] = `
18 | do
19 | do
20 | local one, two, three, four, five, six, seven, eight, nine, ten = callSomething("Hello it is me")
21 | local success, errcnt = executeBusted("--pattern=_tags.lua$ --tags=dtag1")
22 | end
23 | end
24 |
25 | describe(function()
26 | it("bla", function()
27 | local one, two, three, four, five, six, seven, eight, nine, ten = callSomething("Hello it is me")
28 | local success, errcnt = executeBusted("--pattern=_tags.lua$ --tags=dtag1")
29 | end)
30 | end)
31 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
32 | do
33 | do
34 | local one, two, three, four, five, six, seven, eight, nine, ten =
35 | callSomething("Hello it is me")
36 | local success, errcnt =
37 | executeBusted("--pattern=_tags.lua$ --tags=dtag1")
38 | end
39 | end
40 |
41 | describe(function()
42 | it("bla", function()
43 | local one, two, three, four, five, six, seven, eight, nine, ten =
44 | callSomething("Hello it is me")
45 | local success, errcnt =
46 | executeBusted("--pattern=_tags.lua$ --tags=dtag1")
47 | end)
48 | end)
49 |
50 | `;
51 |
52 | exports[`simple_return.lua - lua-verify: simple_return.lua 1`] = `
53 | if true then return end
54 |
55 | if true then
56 | -- don't break me
57 | return
58 | end
59 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
60 | if true then return end
61 |
62 | if true then
63 | -- don't break me
64 | return
65 | end
66 |
67 | `;
68 |
--------------------------------------------------------------------------------
/tests/examples/misc/hook.lua:
--------------------------------------------------------------------------------
1 |
2 | hook.Add("hello", "okay", function(some, arguments)
3 | doSomething()
4 | return false
5 | end)
6 |
--------------------------------------------------------------------------------
/tests/examples/misc/jsfmt.spec.js:
--------------------------------------------------------------------------------
1 | run_spec(__dirname, ["lua"]);
2 |
--------------------------------------------------------------------------------
/tests/examples/misc/local_with_call_near_print_width.lua:
--------------------------------------------------------------------------------
1 | do
2 | do
3 | local one, two, three, four, five, six, seven, eight, nine, ten = callSomething("Hello it is me")
4 | local success, errcnt = executeBusted("--pattern=_tags.lua$ --tags=dtag1")
5 | end
6 | end
7 |
8 | describe(function()
9 | it("bla", function()
10 | local one, two, three, four, five, six, seven, eight, nine, ten = callSomething("Hello it is me")
11 | local success, errcnt = executeBusted("--pattern=_tags.lua$ --tags=dtag1")
12 | end)
13 | end)
14 |
--------------------------------------------------------------------------------
/tests/examples/misc/simple_return.lua:
--------------------------------------------------------------------------------
1 | if true then return end
2 |
3 | if true then
4 | -- don't break me
5 | return
6 | end
7 |
--------------------------------------------------------------------------------
/tests/examples/using-busted/__snapshots__/jsfmt.spec.js.snap:
--------------------------------------------------------------------------------
1 | // Jest Snapshot v1, https://goo.gl/fbAQLP
2 |
3 | exports[`main.lua - lua-verify: main.lua 1`] = `
4 | describe("Busted unit testing framework", function()
5 | describe("should be awesome", function()
6 | it("should be easy to use", function()
7 | assert.truthy("Yup.")
8 | end)
9 |
10 | it("should have lots of features", function()
11 | -- deep check comparisons!
12 | assert.are.same({ table = "great"}, { table = "great" })
13 |
14 | -- or check by reference!
15 | assert.are_not.equal({ table = "great"}, { table = "great"})
16 |
17 | assert.truthy("this is a string") -- truthy: not false or nil
18 |
19 | assert.True(1 == 1)
20 | assert.is_true(1 == 1)
21 |
22 | assert.falsy(nil)
23 | assert.has_error(function() error("Wat") end, "Wat")
24 | end)
25 |
26 | it("should provide some shortcuts to common functions", function()
27 | assert.are.unique({{ thing = 1 }, { thing = 2 }, { thing = 3 }})
28 | end)
29 |
30 | it("should have mocks and spies for functional tests", function()
31 | local thing = require("thing_module")
32 | spy.on(thing, "greet")
33 | thing.greet("Hi!")
34 |
35 | assert.spy(thing.greet).was.called()
36 | assert.spy(thing.greet).was.called_with("Hi!")
37 | end)
38 | end)
39 | end)
40 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
41 | describe("Busted unit testing framework", function()
42 | describe("should be awesome", function()
43 | it("should be easy to use", function()
44 | assert.truthy("Yup.")
45 | end)
46 |
47 | it("should have lots of features", function()
48 | -- deep check comparisons!
49 | assert.are.same({ table = "great" }, { table = "great" })
50 |
51 | -- or check by reference!
52 | assert.are_not.equal({ table = "great" }, { table = "great" })
53 |
54 | assert.truthy("this is a string") -- truthy: not false or nil
55 | assert.True(1 == 1)
56 | assert.is_true(1 == 1)
57 |
58 | assert.falsy(nil)
59 | assert.has_error(function()
60 | error("Wat")
61 | end, "Wat")
62 | end)
63 |
64 | it("should provide some shortcuts to common functions", function()
65 | assert.are.unique({ { thing = 1 }, { thing = 2 }, { thing = 3 } })
66 | end)
67 |
68 | it("should have mocks and spies for functional tests", function()
69 | local thing = require("thing_module")
70 | spy.on(thing, "greet")
71 | thing.greet("Hi!")
72 |
73 | assert.spy(thing.greet).was.called()
74 | assert.spy(thing.greet).was.called_with("Hi!")
75 | end)
76 | end)
77 | end)
78 |
79 | `;
80 |
--------------------------------------------------------------------------------
/tests/examples/using-busted/jsfmt.spec.js:
--------------------------------------------------------------------------------
1 | run_spec(__dirname, ["lua"]);
2 |
--------------------------------------------------------------------------------
/tests/examples/using-busted/main.lua:
--------------------------------------------------------------------------------
1 | describe("Busted unit testing framework", function()
2 | describe("should be awesome", function()
3 | it("should be easy to use", function()
4 | assert.truthy("Yup.")
5 | end)
6 |
7 | it("should have lots of features", function()
8 | -- deep check comparisons!
9 | assert.are.same({ table = "great"}, { table = "great" })
10 |
11 | -- or check by reference!
12 | assert.are_not.equal({ table = "great"}, { table = "great"})
13 |
14 | assert.truthy("this is a string") -- truthy: not false or nil
15 |
16 | assert.True(1 == 1)
17 | assert.is_true(1 == 1)
18 |
19 | assert.falsy(nil)
20 | assert.has_error(function() error("Wat") end, "Wat")
21 | end)
22 |
23 | it("should provide some shortcuts to common functions", function()
24 | assert.are.unique({{ thing = 1 }, { thing = 2 }, { thing = 3 }})
25 | end)
26 |
27 | it("should have mocks and spies for functional tests", function()
28 | local thing = require("thing_module")
29 | spy.on(thing, "greet")
30 | thing.greet("Hi!")
31 |
32 | assert.spy(thing.greet).was.called()
33 | assert.spy(thing.greet).was.called_with("Hi!")
34 | end)
35 | end)
36 | end)
37 |
--------------------------------------------------------------------------------
/tests/semicolons/__snapshots__/jsfmt.spec.js.snap:
--------------------------------------------------------------------------------
1 | // Jest Snapshot v1, https://goo.gl/fbAQLP
2 |
3 | exports[`main.lua - lua-verify: main.lua 1`] = `
4 | (function()
5 | print("first")
6 | end)();
7 |
8 | (function()
9 | print("second")
10 | end)()
11 |
12 | local a = (1);
13 |
14 | (function()
15 | print("first")
16 | end)()
17 |
18 | a = (1);
19 |
20 | (function()
21 | print("first")
22 | end)()
23 |
24 | local a = a or (1);
25 |
26 | (function()
27 | print("first")
28 | end)()
29 |
30 | local a = a or a or a or a and (1);
31 |
32 | (function()
33 | print("first")
34 | end)()
35 |
36 | local a = a or (a and b);
37 |
38 | (function()
39 | print("first")
40 | end)()
41 |
42 | local a = a + (1);
43 |
44 | (function()
45 | print("first")
46 | end)()
47 |
48 | local a = a + 2 + 4 + (5 + 6 - 1);
49 |
50 | (function()
51 | print("first")
52 | end)()
53 |
54 | local a = a or (not b);
55 |
56 | (function()
57 | print("first")
58 | end)()
59 |
60 |
61 | local identifier_semi = (a);
62 | (function()
63 | end)()
64 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
65 | (function()
66 | print("first")
67 | end)();
68 |
69 | (function()
70 | print("second")
71 | end)()
72 |
73 | local a = 1;
74 |
75 | (function()
76 | print("first")
77 | end)()
78 |
79 | a = 1;
80 |
81 | (function()
82 | print("first")
83 | end)()
84 |
85 | local a = a or 1;
86 |
87 | (function()
88 | print("first")
89 | end)()
90 |
91 | local a = a or a or a or a and 1;
92 |
93 | (function()
94 | print("first")
95 | end)()
96 |
97 | local a = a or (a and b);
98 |
99 | (function()
100 | print("first")
101 | end)()
102 |
103 | local a = a + 1;
104 |
105 | (function()
106 | print("first")
107 | end)()
108 |
109 | local a = a + 2 + 4 + (5 + 6 - 1);
110 |
111 | (function()
112 | print("first")
113 | end)()
114 |
115 | local a = a or not b;
116 |
117 | (function()
118 | print("first")
119 | end)()
120 |
121 | local identifier_semi = a;
122 | (function() end)()
123 |
124 | `;
125 |
126 | exports[`main.lua - lua-verify: main.lua 2`] = `
127 | (function()
128 | print("first")
129 | end)();
130 |
131 | (function()
132 | print("second")
133 | end)()
134 |
135 | local a = (1);
136 |
137 | (function()
138 | print("first")
139 | end)()
140 |
141 | a = (1);
142 |
143 | (function()
144 | print("first")
145 | end)()
146 |
147 | local a = a or (1);
148 |
149 | (function()
150 | print("first")
151 | end)()
152 |
153 | local a = a or a or a or a and (1);
154 |
155 | (function()
156 | print("first")
157 | end)()
158 |
159 | local a = a or (a and b);
160 |
161 | (function()
162 | print("first")
163 | end)()
164 |
165 | local a = a + (1);
166 |
167 | (function()
168 | print("first")
169 | end)()
170 |
171 | local a = a + 2 + 4 + (5 + 6 - 1);
172 |
173 | (function()
174 | print("first")
175 | end)()
176 |
177 | local a = a or (not b);
178 |
179 | (function()
180 | print("first")
181 | end)()
182 |
183 |
184 | local identifier_semi = (a);
185 | (function()
186 | end)()
187 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
188 | (function()
189 | print('first')
190 | end)();
191 |
192 | (function()
193 | print('second')
194 | end)()
195 |
196 | local a = 1;
197 |
198 | (function()
199 | print('first')
200 | end)()
201 |
202 | a = 1;
203 |
204 | (function()
205 | print('first')
206 | end)()
207 |
208 | local a = a or 1;
209 |
210 | (function()
211 | print('first')
212 | end)()
213 |
214 | local a = a or a or a or a and 1;
215 |
216 | (function()
217 | print('first')
218 | end)()
219 |
220 | local a = a or (a and b);
221 |
222 | (function()
223 | print('first')
224 | end)()
225 |
226 | local a = a + 1;
227 |
228 | (function()
229 | print('first')
230 | end)()
231 |
232 | local a = a + 2 + 4 + (5 + 6 - 1);
233 |
234 | (function()
235 | print('first')
236 | end)()
237 |
238 | local a = a or not b;
239 |
240 | (function()
241 | print('first')
242 | end)()
243 |
244 | local identifier_semi = a;
245 | (function() end)()
246 |
247 | `;
248 |
--------------------------------------------------------------------------------
/tests/semicolons/jsfmt.spec.js:
--------------------------------------------------------------------------------
1 | run_spec(__dirname, ["lua"]);
2 | run_spec(__dirname, ["lua"], { trailingComma: "all", singleQuote: true });
3 |
--------------------------------------------------------------------------------
/tests/semicolons/main.lua:
--------------------------------------------------------------------------------
1 | (function()
2 | print("first")
3 | end)();
4 |
5 | (function()
6 | print("second")
7 | end)()
8 |
9 | local a = (1);
10 |
11 | (function()
12 | print("first")
13 | end)()
14 |
15 | a = (1);
16 |
17 | (function()
18 | print("first")
19 | end)()
20 |
21 | local a = a or (1);
22 |
23 | (function()
24 | print("first")
25 | end)()
26 |
27 | local a = a or a or a or a and (1);
28 |
29 | (function()
30 | print("first")
31 | end)()
32 |
33 | local a = a or (a and b);
34 |
35 | (function()
36 | print("first")
37 | end)()
38 |
39 | local a = a + (1);
40 |
41 | (function()
42 | print("first")
43 | end)()
44 |
45 | local a = a + 2 + 4 + (5 + 6 - 1);
46 |
47 | (function()
48 | print("first")
49 | end)()
50 |
51 | local a = a or (not b);
52 |
53 | (function()
54 | print("first")
55 | end)()
56 |
57 |
58 | local identifier_semi = (a);
59 | (function()
60 | end)()
61 |
--------------------------------------------------------------------------------
/tests/unnecessary-parens/jsfmt.spec.js:
--------------------------------------------------------------------------------
1 | run_spec(__dirname, ["lua"]);
2 | run_spec(__dirname, ["lua"], { trailingComma: "all", singleQuote: true });
3 |
--------------------------------------------------------------------------------
/tests/unnecessary-parens/main.lua:
--------------------------------------------------------------------------------
1 | remove = (a)
2 | remove = (2e16)
3 | remove = (true)
4 | remove = (nil)
5 | remove = ("a")
6 | remove = ([[ a ]])
7 | remove = (a.b)
8 | remove = (a["a"])
9 | remove = (a())
10 | remove = (not a)
11 | remove = (-1)
12 |
13 | a, b, c = (a())
14 | a, b, c = (a()), (b())
15 | a, b, c = (a()), (b()), (c())
16 | a, b, c = ...
17 | a, b, c = (...)
18 | a, b, c = (...), (b())
19 | a, b, c = (...), (b()), (c())
20 |
21 | local a, b, c = (a())
22 | local a, b, c = (a()), (b())
23 | local a, b, c = (a()), (b()), (c())
24 | local a, b, c = ...
25 | local a, b, c = (...)
26 | local a, b, c = (...), (b())
27 | local a, b, c = (...), (b()), (c())
28 |
29 | a = (a())
30 | a = (a()), (b())
31 | a = (a()), (b()), (c())
32 | a = ...
33 | a = (...)
34 | a = (...), (b())
35 | a = (...), (b()), (c())
36 |
37 | local a = (a())
38 | local a = (a()), (b())
39 | local a = (a()), (b()), (c())
40 | local a = ...
41 | local a = (...)
42 | local a = (...), (b())
43 | local a = (...), (b()), (c())
44 |
45 | a, b, c, d, e, f = (a())
46 | a, b, c, d, e, f = (a()), (b())
47 | a, b, c, d, e, f = (a()), (b()), (c())
48 | a, b, c, d, e, f = ...
49 | a, b, c, d, e, f = (...)
50 | a, b, c, d, e, f = (...), (b())
51 | a, b, c, d, e, f = (...), (b()), (c())
52 |
53 | local a, b, c, d, e, f = (a())
54 | local a, b, c, d, e, f = (a()), (b())
55 | local a, b, c, d, e, f = (a()), (b()), (c())
56 | local a, b, c, d, e, f = ...
57 | local a, b, c, d, e, f = (...)
58 | local a, b, c, d, e, f = (...), (b())
59 | local a, b, c, d, e, f = (...), (b()), (c())
60 |
61 | local a = {
62 | a = (a()), (b())
63 | }
64 |
65 | function you_need_me_1()
66 | return (a())
67 | end
68 |
69 | function you_need_me_2()
70 | return (a()), (b())
71 | end
72 |
73 | function you_need_me_3()
74 | return (a()), (b()), (c())
75 | end
76 |
77 | function you_need_me_1()
78 | return (a"")
79 | end
80 |
81 | function you_need_me_2()
82 | return (a""), (b"")
83 | end
84 |
85 | function you_need_me_3()
86 | return (a""), (b""), (c"")
87 | end
88 |
89 | function you_need_me_1()
90 | return (a{})
91 | end
92 |
93 | function you_need_me_2()
94 | return (a{}), (b{})
95 | end
96 |
97 | function you_need_me_3()
98 | return (a{}), (b{}), (c{})
99 | end
100 |
101 | function you_need_me_1(...)
102 | return ...
103 | end
104 |
105 | function you_need_me_1(...)
106 | return (...)
107 | end
108 |
109 | function you_need_me_2(...)
110 | return (...), (b())
111 | end
112 |
113 | function you_need_me_3()
114 | return (...), (b()), (c())
115 | end
116 |
117 |
118 |
119 | local please = (((((a)))))
120 |
121 | local dont_touch_math = (2 + 2) + (2 - 2)
122 | local dont_touch_logic = (2 and 2) or (2 and 2)
123 |
124 | keep = (2e16)()
125 | keep = (true)()
126 | keep = (nil)()
127 | keep = ("a")()
128 | keep = ([[ a ]])()
129 | keep = (not a)()
130 | keep = (-1)()
131 |
132 | remove = (a)()
133 | remove = (a.b)()
134 | remove = (a["a"])()
135 | remove = (a())()
136 |
--------------------------------------------------------------------------------
/tests_config/raw-serializer.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 |
3 | const RAW = Symbol.for("raw");
4 |
5 | module.exports = {
6 | print(val) {
7 | return val[RAW];
8 | },
9 | test(val) {
10 | return (
11 | val &&
12 | Object.prototype.hasOwnProperty.call(val, RAW) &&
13 | typeof val[RAW] === "string"
14 | );
15 | }
16 | };
17 |
--------------------------------------------------------------------------------
/tests_config/run_spec.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 |
3 | const fs = require("fs");
4 | const { extname } = require("path");
5 | const prettier = require("prettier");
6 |
7 | const { AST_COMPARE } = process.env;
8 |
9 | function run_spec(dirname, parsers, options) {
10 | options = Object.assign(
11 | {
12 | plugins: ["."],
13 | },
14 | options
15 | );
16 |
17 | /* istanbul ignore if */
18 | if (!parsers || !parsers.length) {
19 | throw new Error(`No parsers were specified for ${dirname}`);
20 | }
21 |
22 | fs.readdirSync(dirname).forEach((filename) => {
23 | const path = `${dirname}/${filename}`;
24 | if (
25 | extname(filename) !== ".snap" &&
26 | fs.lstatSync(path).isFile() &&
27 | filename[0] !== "." &&
28 | filename !== "jsfmt.spec.js"
29 | ) {
30 | let source = read(path);
31 |
32 | if (!options.keepEOL) {
33 | source = source.replace(/\r\n/g, "\n");
34 | }
35 |
36 | const mergedOptions = Object.assign(mergeDefaultOptions(options || {}), {
37 | parser: parsers[0],
38 | });
39 | const output = prettyprint(source, path, mergedOptions);
40 | test(`${filename} - ${mergedOptions.parser}-verify`, () => {
41 | expect(
42 | raw(`${source + "~".repeat(mergedOptions.printWidth)}\n${output}`)
43 | ).toMatchSnapshot(filename);
44 | });
45 |
46 | parsers.slice(1).forEach((parserName) => {
47 | test(`${filename} - ${parserName}-verify`, () => {
48 | const verifyOptions = Object.assign(mergedOptions, {
49 | parser: parserName,
50 | });
51 | const verifyOutput = prettyprint(source, path, verifyOptions);
52 | expect(output).toEqual(verifyOutput);
53 | });
54 | });
55 |
56 | if (AST_COMPARE && parsers.slice(0) === "lua") {
57 | const compareOptions = Object.assign({}, mergedOptions);
58 | const astMassaged = parse(source, compareOptions);
59 | let ppastMassaged;
60 | let pperr = null;
61 | expect(() => {
62 | ppastMassaged = parse(
63 | prettyprint(source, path, compareOptions),
64 | compareOptions
65 | );
66 | }).not.toThrow();
67 |
68 | expect(ppastMassaged).toBeDefined();
69 | test(`${path} parse`, () => {
70 | expect(pperr).toBe(null);
71 | expect(ppastMassaged).toBeDefined();
72 | if (!astMassaged.errors || astMassaged.errors.length === 0) {
73 | expect(astMassaged).toEqual(ppastMassaged);
74 | }
75 | });
76 | }
77 | }
78 | });
79 | }
80 | global.run_spec = run_spec;
81 |
82 | function parse(string, opts) {
83 | return prettier.__debug.parse(string, opts, /* massage */ true).ast;
84 | }
85 |
86 | function prettyprint(src, filename, options) {
87 | return prettier.format(
88 | src,
89 | Object.assign(
90 | {
91 | filepath: filename,
92 | },
93 | options
94 | )
95 | );
96 | }
97 |
98 | function read(filename) {
99 | return fs.readFileSync(filename, "utf8");
100 | }
101 |
102 | /**
103 | * Wraps a string in a marker object that is used by `./raw-serializer.js` to
104 | * directly print that string in a snapshot without escaping all double quotes.
105 | * Backticks will still be escaped.
106 | */
107 | function raw(string) {
108 | if (typeof string !== "string") {
109 | throw new Error("Raw snapshots have to be strings.");
110 | }
111 | return { [Symbol.for("raw")]: string };
112 | }
113 |
114 | function mergeDefaultOptions(parserConfig) {
115 | return Object.assign(
116 | {
117 | printWidth: 80,
118 | trailingComma: "none",
119 | },
120 | parserConfig
121 | );
122 | }
123 |
--------------------------------------------------------------------------------