|
| 1 | +import test from 'ava'; |
| 2 | +import avaRuleTester from 'eslint-ava-rule-tester'; |
| 3 | +import rule from '../rules/no-new-buffer'; |
| 4 | + |
| 5 | +const ruleTester = avaRuleTester(test, { |
| 6 | + env: { |
| 7 | + es6: true |
| 8 | + }, |
| 9 | + parserOptions: { |
| 10 | + sourceType: 'module' |
| 11 | + } |
| 12 | +}); |
| 13 | + |
| 14 | +const allocError = { |
| 15 | + ruleId: 'no-new-buffer', |
| 16 | + message: '`new Buffer()` is deprecated, use `Buffer.alloc()` instead.' |
| 17 | +}; |
| 18 | + |
| 19 | +const fromError = { |
| 20 | + ruleId: 'no-new-buffer', |
| 21 | + message: '`new Buffer()` is deprecated, use `Buffer.from()` instead.' |
| 22 | +}; |
| 23 | + |
| 24 | +ruleTester.run('no-new-buffer', rule, { |
| 25 | + valid: [ |
| 26 | + `const buf = Buffer.from('buf')`, |
| 27 | + `const buf = Buffer.from('7468697320697320612074c3a97374', 'hex')`, |
| 28 | + 'const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72])', |
| 29 | + 'const buf = Buffer.alloc(10)' |
| 30 | + ], |
| 31 | + invalid: [ |
| 32 | + { |
| 33 | + code: 'const buf = new Buffer()', |
| 34 | + errors: [fromError], |
| 35 | + output: 'const buf = Buffer.from()' |
| 36 | + }, |
| 37 | + { |
| 38 | + code: `const buf = new Buffer('buf')`, |
| 39 | + errors: [fromError], |
| 40 | + output: `const buf = Buffer.from('buf')` |
| 41 | + }, |
| 42 | + { |
| 43 | + code: `const buf = new Buffer('7468697320697320612074c3a97374', 'hex')`, |
| 44 | + errors: [fromError], |
| 45 | + output: `const buf = Buffer.from('7468697320697320612074c3a97374', 'hex')` |
| 46 | + }, |
| 47 | + { |
| 48 | + code: 'const buf = new Buffer([0x62, 0x75, 0x66, 0x66, 0x65, 0x72])', |
| 49 | + errors: [fromError], |
| 50 | + output: 'const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72])' |
| 51 | + }, |
| 52 | + { |
| 53 | + code: 'const buf = new Buffer(10)', |
| 54 | + errors: [allocError], |
| 55 | + output: 'const buf = Buffer.alloc(10)' |
| 56 | + }, |
| 57 | + { |
| 58 | + code: ` |
| 59 | + const ab = new ArrayBuffer(10); |
| 60 | + const buf = new Buffer(ab, 0, 2); |
| 61 | + `, |
| 62 | + errors: [fromError], |
| 63 | + output: ` |
| 64 | + const ab = new ArrayBuffer(10); |
| 65 | + const buf = Buffer.from(ab, 0, 2); |
| 66 | + ` |
| 67 | + }, |
| 68 | + { |
| 69 | + code: ` |
| 70 | + const buf1 = new Buffer('buf'); |
| 71 | + const buf2 = new Buffer(buf1); |
| 72 | + `, |
| 73 | + errors: [fromError, fromError], |
| 74 | + output: ` |
| 75 | + const buf1 = Buffer.from('buf'); |
| 76 | + const buf2 = Buffer.from(buf1); |
| 77 | + ` |
| 78 | + } |
| 79 | + ] |
| 80 | +}); |
0 commit comments