Best Python code snippet using localstack_python
text.spec.ts
Source:text.spec.ts
1import chalk from 'chalk';2import { EOL } from 'os';3import * as pathLib from 'path';4import { spinnerMessage } from '../../../../../src/lib/formatters/iac-output';5import { FakeServer } from '../../../../acceptance/fake-server';6import { startMockServer } from '../helpers';7const IAC_CLI_OUTPUT_FF = 'iacCliOutputRelease';8jest.setTimeout(1_000 * 30);9describe('iac test text output', () => {10 let server: FakeServer;11 let run: (12 cmd: string,13 overrides?: Record<string, string>,14 ) => Promise<{ stdout: string; stderr: string; exitCode: number }>;15 let teardown: () => Promise<unknown>;16 beforeAll(async () => {17 ({ server, run, teardown } = await startMockServer());18 });19 afterEach(() => {20 server.restore();21 });22 afterAll(async () => {23 await teardown();24 });25 describe(`with the '${IAC_CLI_OUTPUT_FF}' feature flag`, () => {26 beforeEach(() => {27 server.setFeatureFlag(IAC_CLI_OUTPUT_FF, true);28 });29 it('should show the IaC test title', async () => {30 const dirPath = './iac/terraform';31 const { stdout } = await run(`snyk iac test ${dirPath}`);32 expect(stdout).toContain('Snyk Infrastructure as Code');33 });34 it('should show the spinner message', async () => {35 const dirPath = './iac/terraform';36 const { stdout } = await run(`snyk iac test ${dirPath}`);37 expect(stdout).toContain(38 'Snyk testing Infrastructure as Code configuration issues.',39 );40 });41 it('should show the test completion message', async () => {42 const dirPath = './iac/terraform';43 const { stdout } = await run(`snyk iac test ${dirPath}`);44 expect(stdout).toContain('Test completed.');45 });46 it('should show the issues list section with correct values', async () => {47 const { stdout } = await run('snyk iac test ./iac/arm/rule_test.json');48 expect(stdout).toContain(49 'Issues' +50 EOL.repeat(2) +51 'Medium Severity Issues: 1' +52 EOL.repeat(2) +53 ' [Medium] Azure Firewall Network Rule Collection allows public access' +54 EOL +55 ' Info: That inbound traffic is allowed to a resource from any source instead of a restricted range. That potentially everyone can access your resource' +56 EOL +57 ' Rule: https://snyk.io/security-rules/SNYK-CC-TF-20' +58 EOL +59 ' Path: resources[1] > properties > networkRuleCollections[0] > properties > rules[0] > sourceAddresses' +60 EOL +61 ' File: ./iac/arm/rule_test.json' +62 EOL +63 ' Resolve: Set `properties.networkRuleCollections.properties.rules.sourceAddresses` attribute to specific IP range only, e.g. `192.168.1.0/24`',64 );65 });66 it('should show the test summary section with correct values', async () => {67 const dirPath = 'iac/kubernetes';68 const policyPath = `iac/policy/.snyk`;69 const { stdout } = await run(70 `snyk iac test ${dirPath} --policy-path=${policyPath}`,71 );72 expect(stdout).toContain(73 'Test Summary' +74 EOL.repeat(2) +75 ' Organization: test-org' +76 EOL +77 ' Project name: fixtures' +78 EOL.repeat(2) +79 'â Files without issues: 0' +80 EOL +81 'â Files with issues: 3' +82 EOL +83 ' Ignored issues: 8' +84 EOL +85 ' Total issues: ',86 );87 });88 it('should not show the file meta sections', async () => {89 const dirPath = 'iac/arm';90 const { stdout } = await run(`snyk iac test ${dirPath}`);91 expect(stdout).not.toContain(`92Type: ARM93Target file: ${dirPath}/`);94 });95 it('should not show the file summary messages', async () => {96 const dirPath = 'iac/terraform';97 const { stdout } = await run(`snyk iac test ${dirPath}`);98 expect(stdout).not.toContain(`Tested ${dirPath} for known issues`);99 });100 it('should not show the test failures section', async () => {101 const dirPath = 'iac/only-valid';102 const { stdout } = await run(`snyk iac test ${dirPath}`);103 expect(stdout).not.toContain('Test Failures');104 });105 describe('with multiple test results', () => {106 describe('with test failures', () => {107 it('should show the failures list section with the correct values', async () => {108 const dirPath = 'iac';109 const { stdout } = await run(110 `snyk iac test ${dirPath} my-imaginary-file.tf my-imaginary-directory/`,111 );112 expect(stdout).toContain(113 ' Failed to parse JSON file' +114 EOL +115 ` Path: ${pathLib.join(116 'iac',117 'arm',118 'invalid_rule_test.json',119 )}` +120 EOL.repeat(2) +121 ' Failed to parse YAML file' +122 EOL +123 ` Path: ${pathLib.join(124 'iac',125 'cloudformation',126 'invalid-cfn.yml',127 )}` +128 EOL +129 ` ${pathLib.join(130 'iac',131 'kubernetes',132 'helm-config.yaml',133 )}` +134 EOL +135 ` ${pathLib.join(136 'iac',137 'only-invalid',138 'invalid-file1.yml',139 )}` +140 EOL +141 ` ${pathLib.join(142 'iac',143 'only-invalid',144 'invalid-file2.yaml',145 )}` +146 EOL.repeat(2) +147 ' Failed to parse Terraform file' +148 EOL +149 ` Path: ${pathLib.join(150 'iac',151 'terraform',152 'sg_open_ssh_invalid_go_templates.tf',153 )}` +154 EOL +155 ` ${pathLib.join(156 'iac',157 'terraform',158 'sg_open_ssh_invalid_hcl2.tf',159 )}` +160 EOL.repeat(2) +161 ' Failed to load file content' +162 EOL +163 ` Path: my-imaginary-file.tf` +164 EOL.repeat(2) +165 ' Could not find any valid IaC files' +166 EOL +167 ` Path: my-imaginary-directory/`,168 );169 });170 it('should include user tip for test failures', async () => {171 const dirPath = 'iac/terraform';172 const { stdout } = await run(`snyk iac test ${dirPath}`);173 expect(stdout).toContain(174 'Tip: Re-run in debug mode to see more information: DEBUG=*snyk* <COMMAND>' +175 EOL +176 'If the issue persists contact support@snyk.io',177 );178 });179 });180 });181 describe('with only test failures', () => {182 it('should display the test failures list', async () => {183 const invalidPaths = [184 pathLib.join('iac', 'cloudformation', 'invalid-cfn.yml'),185 pathLib.join(186 'iac',187 'terraform',188 'sg_open_ssh_invalid_go_templates.tf',189 ),190 pathLib.join('iac', 'terraform', 'sg_open_ssh_invalid_hcl2.tf'),191 pathLib.join('does', 'not', 'exist'),192 ];193 const { stdout } = await run(`snyk iac test ${invalidPaths.join(' ')}`);194 expect(stdout).toContain(195 ' Failed to parse YAML file' +196 EOL +197 ` Path: ${pathLib.join(198 'iac',199 'cloudformation',200 'invalid-cfn.yml',201 )}` +202 EOL.repeat(2) +203 ' Failed to parse Terraform file' +204 EOL +205 ` Path: ${pathLib.join(206 'iac',207 'terraform',208 'sg_open_ssh_invalid_go_templates.tf',209 )}` +210 EOL +211 ` ${pathLib.join(212 'iac',213 'terraform',214 'sg_open_ssh_invalid_hcl2.tf',215 )}` +216 EOL.repeat(2) +217 ' Could not find any valid IaC files' +218 EOL +219 ` Path: ${pathLib.join('does', 'not', 'exist')}`,220 );221 });222 it('should not show the issues section', async () => {223 const dirPath = 'iac/only-invalid';224 const { stdout } = await run(`snyk iac test ${dirPath}`);225 expect(stdout).not.toContain('Issues');226 });227 it('should not show the test summary section', async () => {228 const dirPath = 'iac/only-invalid';229 const { stdout } = await run(`snyk iac test ${dirPath}`);230 expect(stdout).not.toContain('Test Summary');231 });232 });233 describe('with no issues', () => {234 it('should display an appropriate message in the issues section', async () => {235 const filePath = 'iac/terraform/vars.tf';236 const { stdout } = await run(`snyk iac test ${filePath}`);237 expect(stdout).toContain('No vulnerable paths were found!');238 });239 });240 describe('with issues generated by custom rules', () => {241 it('should include the public custom rule IDs', async () => {242 const filePath = 'iac/terraform/sg_open_ssh.tf ';243 const { stdout } = await run(244 `snyk iac test ${filePath} --rules=./iac/custom-rules/custom.tar.gz`,245 );246 expect(stdout).toContain(`Rule: custom rule CUSTOM-1`);247 });248 });249 });250 describe(`without the '${IAC_CLI_OUTPUT_FF}' feature flag`, () => {251 it('should show the file meta sections for each file', async () => {252 const filePath = 'iac/arm/rule_test.json';253 const { stdout } = await run(`snyk iac test ${filePath}`);254 expect(stdout).toContain(`255Organization: test-org256Type: ARM257Target file: ${filePath}258Project name: fixtures259Open source: no260Project path: ${filePath}261`);262 });263 it('should show the file summary messages', async () => {264 const dirPath = 'iac/terraform';265 const { stdout } = await run(`snyk iac test ${dirPath}`);266 expect(stdout).toContain(267 'Tested sg_open_ssh.tf for known issues, found 1 issues',268 );269 expect(stdout).toContain('Tested vars.tf for known issues, found');270 expect(stdout).toContain(271 `Tested ${pathLib.join(272 'var_deref',273 'sg_open_ssh.tf',274 )} for known issues, found`,275 );276 expect(stdout).toContain(277 `Tested ${pathLib.join(278 'var_deref',279 'variables.tf',280 )} for known issues, found`,281 );282 expect(stdout).toContain(283 `Tested ${pathLib.join(284 'var_deref',285 'nested_var_deref',286 'sg_open_ssh.tf',287 )} for known issues, found`,288 );289 expect(stdout).toContain(290 `Tested ${pathLib.join(291 'var_deref',292 'nested_var_deref',293 'variables.tf',294 )} for known issues, found`,295 );296 });297 it('should show the test summary message', async () => {298 const dirPath = 'iac/kubernetes';299 const { stdout } = await run(`snyk iac test ${dirPath}`);300 expect(stdout).toContain(301 'Tested 3 projects, 3 contained issues. Failed to test 1 project.',302 );303 });304 it('should not show an initial message', async () => {305 const { stdout } = await run('snyk iac test ./iac/arm/rule_test.json');306 expect(stdout).not.toContain(chalk.reset(spinnerMessage));307 });308 it('should not show a subtitle for medium severity issues', async () => {309 const { stdout } = await run('snyk iac test ./iac/arm/rule_test.json');310 expect(stdout).not.toContain(311 'Issues' + EOL.repeat(2) + 'Medium Severity Issues: 1',312 );313 });314 it('should not show the test summary section', async () => {315 const filePath = 'iac/kubernetes/pod-valid.json';316 const { stdout } = await run(`snyk iac test ${filePath}`);317 expect(stdout).not.toContain('Test Summary');318 });319 it('should not show the test failures section', async () => {320 const dirPath = 'iac/only-valid';321 const { stdout } = await run(`snyk iac test ${dirPath}`);322 expect(stdout).not.toContain('Invalid Files');323 });324 describe('with multiple test results', () => {325 it('should show the test summary message', async () => {326 const dirPath = 'iac/kubernetes';327 const { stdout } = await run(`snyk iac test ${dirPath}`);328 expect(stdout).toContain('Tested 3 projects, 3 contained issues.');329 });330 describe('with test failures', () => {331 it('should show the failure reasons per file', async () => {332 const dirPath = 'iac/terraform';333 const { stdout } = await run(`snyk iac test ${dirPath}`);334 expect(stdout).toContain(335 `Testing sg_open_ssh_invalid_go_templates.tf...336Failed to parse Terraform file337-------------------------------------------------------338Testing sg_open_ssh_invalid_hcl2.tf...339Failed to parse Terraform file`,340 );341 });342 it('should include the failures count in the test summary message', async () => {343 const dirPath = 'iac/kubernetes';344 const { stdout } = await run(`snyk iac test ${dirPath}`);345 expect(stdout).toContain(346 'Tested 3 projects, 3 contained issues. Failed to test 1 project.',347 );348 });349 it('should include user tip for test failures', async () => {350 const dirPath = 'iac/terraform';351 const { stdout } = await run(`snyk iac test ${dirPath}`);352 expect(stdout).toContain(353 `Tip: Re-run in debug mode to see more information: DEBUG=*snyk* <COMMAND>354If the issue persists contact support@snyk.io`,355 );356 });357 });358 });359 describe('with only test failures', () => {360 it('should display the failure reason for the first failed test', async () => {361 const dirPath = 'iac/no-files';362 const { stdout } = await run(`snyk iac test ${dirPath}`);363 expect(stdout).toContain(364 `Could not find any valid infrastructure as code files. Supported file extensions are tf, yml, yaml & json.365More information can be found by running \`snyk iac test --help\` or through our documentation:366https://support.snyk.io/hc/en-us/articles/360012429477-Test-your-Kubernetes-files-with-our-CLI-tool367https://support.snyk.io/hc/en-us/articles/360013723877-Test-your-Terraform-files-with-our-CLI-tool`,368 );369 });370 it('should not show file issue lists', async () => {371 const dirPath = 'iac/only-invalid';372 const { stdout } = await run(`snyk iac test ${dirPath}`);373 expect(stdout).not.toContain('Infrastructure as code issues');374 });375 it('should not show the test summary section', async () => {376 const dirPath = 'iac/only-invalid';377 const { stdout } = await run(`snyk iac test ${dirPath}`);378 expect(stdout).not.toContain('Test Summary');379 });380 });381 });...
test-directory.spec.ts
Source:test-directory.spec.ts
1import { isValidJSONString, startMockServer } from './helpers';2import { FakeServer } from '../../../acceptance/fake-server';3import { EOL } from 'os';4import * as pathLib from 'path';5const IAC_CLI_OUTPUT_FF = 'iacCliOutputRelease';6jest.setTimeout(50000);7describe('Directory scan', () => {8 let server: FakeServer;9 let run: (10 cmd: string,11 ) => Promise<{ stdout: string; stderr: string; exitCode: number }>;12 let teardown: () => void;13 beforeAll(async () => {14 ({ server, run, teardown } = await startMockServer());15 });16 afterAll(async () => {17 await teardown();18 });19 it('scans all files in a directory with Kubernetes files', async () => {20 const { stdout, exitCode } = await run(`snyk iac test ./iac/kubernetes/`);21 expect(stdout).toContain('Testing pod-privileged.yaml'); //directory scan shows relative path to cwd in output22 expect(stdout).toContain('Testing pod-privileged-multi.yaml');23 expect(stdout).toContain('Testing pod-valid.json');24 expect(stdout).toContain('Testing helm-config.yaml');25 expect(stdout).toContain('Failed to parse YAML file');26 expect(stdout).toContain(27 'Tested 3 projects, 3 contained issues. Failed to test 1 project.',28 );29 expect(exitCode).toBe(1);30 });31 it('scans all files in a directory with a mix of IaC files', async () => {32 const { stdout, exitCode } = await run(`snyk iac test ./iac/`);33 //directory scan shows relative path to cwd in output34 // here we assert just on the filename to avoid the different slashes (/) for Unix/Windows on the CI runner35 expect(stdout).toContain('pod-privileged.yaml');36 expect(stdout).toContain('pod-privileged-multi.yaml');37 expect(stdout).toContain('rule_test.json');38 expect(stdout).toContain('aurora-valid.yml');39 expect(stdout).toContain('fargate-valid.json');40 expect(stdout).toContain('root.tf');41 expect(stdout).toContain('one.tf');42 expect(stdout).toContain('tf-plan-update.json');43 expect(stdout).toContain('Failed to parse Terraform file');44 expect(stdout).toContain('Failed to parse YAML file');45 expect(stdout).toContain('Failed to parse JSON file');46 expect(stdout).toEqual(47 expect.stringMatching(48 /\d+ projects, \d+ contained issues. Failed to test \d+ projects/,49 ),50 );51 expect(exitCode).toBe(1);52 });53 it('filters out issues when using severity threshold', async () => {54 const { stdout, exitCode } = await run(55 `snyk iac test ./iac/terraform --severity-threshold=high`,56 );57 expect(exitCode).toBe(0);58 //directory scan shows relative path to cwd in output59 expect(stdout).toContain('Testing sg_open_ssh.tf');60 expect(stdout).toContain('Testing sg_open_ssh_invalid_hcl2.tf');61 expect(stdout).toContain('Testing sg_open_ssh_invalid_hcl2.tf');62 expect(stdout).toContain('Failed to parse Terraform file');63 });64 it('outputs the expected text when running with --sarif flag', async () => {65 const { stdout, exitCode } = await run(66 `snyk iac test ./iac/terraform --sarif`,67 );68 expect(exitCode).toBe(1);69 expect(isValidJSONString(stdout)).toBe(true);70 expect(stdout).toContain('"id": "SNYK-CC-TF-1",');71 expect(stdout).toContain('"ruleId": "SNYK-CC-TF-1",');72 });73 it('outputs the expected text when running with --json flag', async () => {74 const { stdout, exitCode } = await run(75 `snyk iac test ./iac/terraform --json`,76 );77 expect(exitCode).toBe(1);78 expect(isValidJSONString(stdout)).toBe(true);79 expect(stdout).toContain('"id": "SNYK-CC-TF-1",');80 expect(stdout).toContain('"packageManager": "terraformconfig",');81 });82 it('limits the depth of the directories', async () => {83 const { stdout, exitCode } = await run(84 `snyk iac test ./iac/depth_detection/ --detection-depth=2`,85 );86 expect(exitCode).toBe(1);87 // The CLI shows the output relative to the path: one/one.tf.88 // here we assert just on the filename to avoid the different slashes (/) for Unix/Windows on the CI runner89 expect(stdout).toContain('one.tf');90 expect(stdout).toContain('Infrastructure as code issues');91 expect(stdout).toContain('Testing root.tf');92 expect(stdout).toContain('Tested 2 projects');93 expect(stdout).not.toContain('two.tf');94 });95 describe('Variadic - multiple path scans', () => {96 it('outputs both results and failures combined when scanning three paths', async () => {97 const { stdout, exitCode } = await run(98 `snyk iac test ./iac/terraform ./iac/cloudformation ./iac/arm`,99 );100 //directory scan shows relative path to cwd in output101 expect(stdout).toContain('Testing sg_open_ssh.tf');102 expect(stdout).toContain('Testing sg_open_ssh_invalid_hcl2.tf');103 expect(stdout).toContain('Failed to parse Terraform file');104 expect(stdout).toContain('Testing aurora-valid.yml');105 expect(stdout).toContain('Testing invalid-cfn.yml');106 expect(stdout).toContain('Failed to parse YAML file');107 expect(stdout).toContain('Testing rule_test.json');108 expect(stdout).toContain('Testing invalid_rule_test.json');109 expect(stdout).toContain('Failed to parse JSON file');110 expect(exitCode).toBe(1);111 });112 it('outputs both results and failures combined with --json flag', async () => {113 const { stdout, exitCode } = await run(114 `snyk iac test ./iac/terraform ./iac/cloudformation --json`,115 );116 expect(isValidJSONString(stdout)).toBe(true);117 expect(stdout).toContain('"id": "SNYK-CC-TF-1",');118 expect(stdout).toContain('"id": "SNYK-CC-TF-124",');119 expect(stdout).toContain('"packageManager": "terraformconfig",');120 expect(stdout).toContain('"projectType": "terraformconfig",');121 expect(stdout).toContain('"id": "SNYK-CC-AWS-422",');122 expect(stdout).toContain('"packageManager": "cloudformationconfig",');123 expect(stdout).toContain('"projectType": "cloudformationconfig",');124 expect(exitCode).toBe(1);125 });126 it('outputs both results and failures combined with --sarif flag', async () => {127 const { stdout, exitCode } = await run(128 `snyk iac test ./iac/terraform ./iac/cloudformation --sarif`,129 );130 expect(isValidJSONString(stdout)).toBe(true);131 expect(stdout).toContain('"ruleId": "SNYK-CC-TF-1",');132 expect(stdout).toContain('"ruleId": "SNYK-CC-TF-124",');133 expect(stdout).toContain('"ruleId": "SNYK-CC-AWS-422",');134 expect(exitCode).toBe(1);135 });136 // regression test to check the case that an invalid path would override the overall output137 it('outputs both results and failures for first path when the last path is empty or non-existent', async () => {138 const { stdout, exitCode } = await run(139 `snyk iac test ./iac/arm non-existing-dir`,140 );141 //directory scan shows relative path to cwd in output142 expect(stdout).toContain('Testing rule_test.json.');143 expect(stdout).toContain('Testing invalid_rule_test.json.');144 expect(stdout).toContain('Failed to parse JSON file');145 expect(stdout).toContain('Testing non-existing-dir...');146 expect(stdout).toContain('Could not find any valid IaC files');147 expect(exitCode).toBe(1);148 });149 it('outputs issues and errors when one of the paths fails, with --json flag', async () => {150 const { stdout, exitCode } = await run(151 `snyk iac test ./iac/arm non-existing-dir --json`,152 );153 expect(isValidJSONString(stdout)).toBe(true);154 expect(stdout).toContain('"id": "SNYK-CC-TF-20",');155 expect(stdout).toContain('"ok": false');156 expect(stdout).toContain('"error": "Could not find any valid IaC files"');157 expect(stdout).toContain('"path": "non-existing-dir"');158 expect(exitCode).toBe(3);159 });160 it('filters out errors when one of the paths fails, with --sarif flag', async () => {161 const { stdout, exitCode } = await run(162 `snyk iac test ./iac/arm non-existing-dir --sarif`,163 );164 expect(isValidJSONString(stdout)).toBe(true);165 expect(stdout).not.toContain(166 '"error": "Could not find any valid IaC files"',167 );168 expect(stdout).not.toContain('"path": "non-existing-dir"');169 expect(exitCode).toBe(1);170 });171 //TODO: this test suite is a duplicate of the existing cases, only checking json and sarif flags combinations172 // delete when FF is removed and new IaC Cli output becomes default (after GA)173 describe('with iacCliOutput FF true', () => {174 beforeEach(() => {175 server.setFeatureFlag(IAC_CLI_OUTPUT_FF, true);176 });177 afterEach(() => {178 server.restore();179 });180 it('outputs issues and errors when one of the paths fails, with --json flag and iacCliOutput FF true', async () => {181 const { stdout, exitCode } = await run(182 `snyk iac test ./iac/arm non-existing-dir --json`,183 );184 expect(isValidJSONString(stdout)).toBe(true);185 expect(stdout).toContain('"id": "SNYK-CC-TF-20",');186 expect(stdout).toContain('"ok": false');187 expect(stdout).toContain(188 '"error": "Could not find any valid IaC files"',189 );190 expect(stdout).toContain('"path": "non-existing-dir"');191 expect(exitCode).toBe(3);192 });193 it('outputs both results and failures combined with --json flag and iacCliOutput FF true', async () => {194 const { stdout, exitCode } = await run(195 `snyk iac test ./iac/terraform ./iac/cloudformation --json`,196 );197 expect(isValidJSONString(stdout)).toBe(true);198 expect(stdout).toContain('"id": "SNYK-CC-TF-1",');199 expect(stdout).toContain('"id": "SNYK-CC-TF-124",');200 expect(stdout).toContain('"id": "SNYK-CC-AWS-422",');201 expect(exitCode).toBe(1);202 });203 it('outputs both results and failures combined with --sarif flag, flag on', async () => {204 const { stdout, exitCode } = await run(205 `snyk iac test ./iac/terraform ./iac/cloudformation --sarif`,206 );207 expect(isValidJSONString(stdout)).toBe(true);208 expect(stdout).toContain('"ruleId": "SNYK-CC-TF-1",');209 expect(stdout).toContain('"ruleId": "SNYK-CC-TF-124",');210 expect(stdout).toContain('"ruleId": "SNYK-CC-AWS-422",');211 expect(exitCode).toBe(1);212 });213 });214 });215 describe('directory with files that can not be parsed', () => {216 beforeEach(() => {217 server.setFeatureFlag(IAC_CLI_OUTPUT_FF, true);218 });219 afterEach(() => {220 server.restore();221 });222 it('prints all invalid paths', async () => {223 const { stdout, exitCode } = await run(224 `snyk iac test ./iac/only-invalid`,225 );226 expect(stdout).toContain(227 ' Failed to parse YAML file' +228 EOL +229 ` Path: ${pathLib.join(230 'iac',231 'only-invalid',232 'invalid-file1.yml',233 )}` +234 EOL +235 ` ${pathLib.join(236 'iac',237 'only-invalid',238 'invalid-file2.yaml',239 )}`,240 );241 expect(exitCode).toBe(2);242 });243 it('prints all errors and paths in --json', async () => {244 const { stdout, exitCode } = await run(245 `snyk iac test ./iac/only-invalid --json`,246 );247 expect(isValidJSONString(stdout)).toBe(true);248 expect(JSON.parse(stdout).length).toBe(2);249 expect(stdout).toContain('"ok": false');250 expect(stdout).toContain('"error": "Failed to parse YAML file"');251 expect(exitCode).toBe(2);252 });253 });254 describe('Exit codes', () => {255 describe('Issues found', () => {256 it('returns 1 even if some files failed to parse', async () => {257 const { exitCode, stderr, stdout } = await run(258 `snyk iac test ./iac/kubernetes/`,259 );260 expect(stderr).toBe('');261 expect(stdout).toContain(262 'Tested 3 projects, 3 contained issues. Failed to test 1 project',263 );264 expect(exitCode).toBe(1);265 });266 it('returns 1 even if some files failed to parse - using --json flag', async () => {267 const { exitCode, stderr, stdout } = await run(268 `snyk iac test ./iac/kubernetes/ --json`,269 );270 expect(stderr).toBe('');271 expect(stdout).toContain('"ok": false');272 expect(exitCode).toBe(1);273 });274 it('returns 1 even if some files failed to parse - using --sarif flag', async () => {275 const { exitCode, stderr } = await run(276 `snyk iac test ./iac/kubernetes/ --sarif`,277 );278 expect(stderr).toBe('');279 expect(exitCode).toBe(1);280 });281 });282 describe('No Issues found', () => {283 it('returns 0 even if some files failed to parse', async () => {284 const { exitCode, stderr, stdout } = await run(285 `snyk iac test ./iac/no_vulnerabilities/ --severity-threshold=high`,286 );287 expect(stderr).toBe('');288 expect(stdout).toContain('found 0 issues');289 expect(exitCode).toBe(0);290 });291 it('returns 0 even if some files failed to parse - using --json flag', async () => {292 const { exitCode, stderr, stdout } = await run(293 `snyk iac test ./iac/no_vulnerabilities/ --severity-threshold=high --json`,294 );295 expect(stderr).toBe('');296 expect(stdout).toContain('"ok": true');297 expect(exitCode).toBe(0);298 });299 it('returns 0 even if some files failed to parse - using --sarif flag', async () => {300 const { exitCode, stderr, stdout } = await run(301 `snyk iac test ./iac/no_vulnerabilities/ --severity-threshold=high --sarif`,302 );303 expect(stderr).toBe('');304 expect(stdout).toContain('"results": []');305 expect(exitCode).toBe(0);306 });307 });308 });...
generate_notifications.py
Source:generate_notifications.py
1import logging2from io import TextIOBase3from django.conf import settings4from django.core.management.base import BaseCommand5from django.utils import timezone6from notifications.types import NotificationCode7from notifications.utils import (8 # generate_client_registration_incomplete_notifications,9 # generate_deal_of_week_notifications,10 # generate_follow_up_invitation_sms,11 # generate_hint_to_first_book_notifications,12 # generate_hint_to_rebook_notifications,13 # generate_hint_to_select_stylist_notifications,14 # generate_invite_your_stylist_notifications,15 # generate_remind_add_photo_notifications,16 # generate_remind_define_discounts_notifications,17 # generate_remind_define_hours_notifications,18 # generate_remind_define_services_notification,19 # generate_remind_invite_clients_notifications,20 # generate_stylist_appeared_in_search_notification,21 # generate_stylist_registration_incomplete_notifications,22 generate_tomorrow_appointments_notifications,23 send_all_notifications,24)25logger = logging.getLogger(__name__)26def stdout_and_log(message: str, stdout: TextIOBase):27 """Output message to both stdout and configured logger"""28 stdout.write(message)29 logger.info(message)30class Command(BaseCommand):31 """32 Go over all functions generating notifications, generate notifications33 and then force-send them34 """35 def add_arguments(self, parser):36 parser.add_argument(37 '-d',38 '--dry-run',39 action='store_true',40 dest='dry_run',41 help="Dry-run. Don't actually do anything.",42 )43 parser.add_argument(44 '-f',45 '--force_send',46 action='store_true',47 dest='force_send',48 help="Actually force-send notifications after generation",49 )50 def handle(self, *args, **options):51 dry_run = options['dry_run']52 force_send = options['force_send']53 if not settings.NOTIFICATIONS_ENABLED:54 self.stdout.write('Notifications are disabled, exiting')55 return56 # stdout_and_log(57 # 'Generating {0} notifications'.format(NotificationCode.HINT_TO_FIRST_BOOK),58 # self.stdout59 # )60 # time_start = timezone.now()61 # notification_count = generate_hint_to_first_book_notifications(dry_run=dry_run)62 # time_end = timezone.now()63 # stdout_and_log('...{0} {2} notifications generated; took {1} seconds'.format(64 # notification_count, (time_end - time_start).total_seconds(),65 # NotificationCode.HINT_TO_FIRST_BOOK66 # ), self.stdout)67 # stdout_and_log(68 # 'Generating {0} notifications'.format(NotificationCode.HINT_TO_SELECT_STYLIST),69 # self.stdout70 # )71 # time_start = timezone.now()72 # notification_count = generate_hint_to_select_stylist_notifications(dry_run=dry_run)73 # time_end = timezone.now()74 # stdout_and_log('...{0} {2} notifications generated; took {1} seconds'.format(75 # notification_count, (time_end - time_start).total_seconds(),76 # NotificationCode.HINT_TO_SELECT_STYLIST77 # ), self.stdout)78 # stdout_and_log(79 # 'Generating {0} notifications'.format(NotificationCode.HINT_TO_REBOOK),80 # self.stdout81 # )82 # time_start = timezone.now()83 # notification_count = generate_hint_to_rebook_notifications(dry_run=dry_run)84 # time_end = timezone.now()85 # stdout_and_log('...{0} {2} notifications generated; took {1} seconds'.format(86 # notification_count, (time_end - time_start).total_seconds(),87 # NotificationCode.HINT_TO_REBOOK88 # ), self.stdout)89 stdout_and_log(90 'Generating {0} notifications'.format(NotificationCode.TOMORROW_APPOINTMENTS),91 self.stdout92 )93 time_start = timezone.now()94 notification_count = generate_tomorrow_appointments_notifications(dry_run=dry_run)95 time_end = timezone.now()96 stdout_and_log('...{0} {2} notifications generated; took {1} seconds'.format(97 notification_count, (time_end - time_start).total_seconds(),98 NotificationCode.TOMORROW_APPOINTMENTS99 ), self.stdout)100 # stdout_and_log(101 # 'Generating {0} notifications'.format(NotificationCode.REGISTRATION_INCOMPLETE),102 # self.stdout103 # )104 # time_start = timezone.now()105 # notification_count = generate_stylist_registration_incomplete_notifications(106 # dry_run=dry_run107 # )108 # time_end = timezone.now()109 # stdout_and_log('...{0} {2} notifications generated; took {1} seconds'.format(110 # notification_count, (time_end - time_start).total_seconds(),111 # NotificationCode.REGISTRATION_INCOMPLETE112 # ), self.stdout)113 # stdout_and_log(114 # 'Generating {0} notifications'.format(NotificationCode.REMIND_DEFINE_SERVICES),115 # self.stdout116 # )117 # time_start = timezone.now()118 # notification_count = generate_remind_define_services_notification(dry_run=dry_run)119 # time_end = timezone.now()120 # stdout_and_log('...{0} notifications generated; took {1} seconds'.format(121 # notification_count, (time_end - time_start).total_seconds()122 # ), self.stdout)123 # stdout_and_log(124 # 'Generating {0} notifications'.format(NotificationCode.REMIND_DEFINE_HOURS),125 # self.stdout126 # )127 # time_start = timezone.now()128 # notification_count = generate_remind_define_hours_notifications(129 # dry_run=dry_run130 # )131 # time_end = timezone.now()132 # stdout_and_log('...{0} {2} notifications generated; took {1} seconds'.format(133 # notification_count, (time_end - time_start).total_seconds(),134 # NotificationCode.REMIND_DEFINE_HOURS135 # ), self.stdout)136 # stdout_and_log(137 # 'Generating {0} notifications'.format(NotificationCode.REMIND_DEFINE_DISCOUNTS),138 # self.stdout139 # )140 # time_start = timezone.now()141 # notification_count = generate_remind_define_discounts_notifications(142 # dry_run=dry_run143 # )144 # time_end = timezone.now()145 # stdout_and_log('...{0} {2} notifications generated; took {1} seconds'.format(146 # notification_count, (time_end - time_start).total_seconds(),147 # NotificationCode.REMIND_DEFINE_DISCOUNTS148 # ), self.stdout)149 # stdout_and_log(150 # 'Generating {0} notifications'.format(NotificationCode.REMIND_ADD_PHOTO),151 # self.stdout152 # )153 # time_start = timezone.now()154 # notification_count = generate_remind_add_photo_notifications(155 # dry_run=dry_run156 # )157 # time_end = timezone.now()158 # stdout_and_log('...{0} {2} notifications generated; took {1} seconds'.format(159 # notification_count, (time_end - time_start).total_seconds(),160 # NotificationCode.REMIND_ADD_PHOTO161 # ), self.stdout)162 # stdout_and_log(163 # 'Generating {0} notifications'.format(NotificationCode.REMIND_INVITE_CLIENTS),164 # self.stdout165 # )166 # time_start = timezone.now()167 # notification_count = generate_remind_invite_clients_notifications(168 # dry_run=dry_run169 # )170 # time_end = timezone.now()171 # stdout_and_log('...{0} {2} notifications generated; took {1} seconds'.format(172 # notification_count, (time_end - time_start).total_seconds(),173 # NotificationCode.REMIND_INVITE_CLIENTS174 # ), self.stdout)175 # time_start = timezone.now()176 # sms_count = generate_follow_up_invitation_sms(177 # dry_run=dry_run178 # )179 # time_end = timezone.now()180 # stdout_and_log('...{0} Invitations follow-up SMS generated; took {1} seconds'.format(181 # sms_count, (time_end - time_start).total_seconds(),182 # ), self.stdout)183 # stdout_and_log(184 # 'Generating {0} notifications'.format(NotificationCode.DEAL_OF_THE_WEEK),185 # self.stdout186 # )187 # time_start = timezone.now()188 # notification_count = generate_deal_of_week_notifications(189 # dry_run=dry_run190 # )191 # time_end = timezone.now()192 # stdout_and_log('...{0} {2} notifications generated; took {1} seconds'.format(193 # notification_count, (time_end - time_start).total_seconds(),194 # NotificationCode.DEAL_OF_THE_WEEK195 # ), self.stdout)196 # stdout_and_log(197 # 'Generating {0} notifications'.format(NotificationCode.INVITE_YOUR_STYLIST),198 # self.stdout199 # )200 # time_start = timezone.now()201 # notification_count = generate_invite_your_stylist_notifications(202 # dry_run=dry_run203 # )204 # time_end = timezone.now()205 # stdout_and_log('...{0} {2} notifications generated; took {1} seconds'.format(206 # notification_count, (time_end - time_start).total_seconds(),207 # NotificationCode.INVITE_YOUR_STYLIST208 # ), self.stdout)209 # stdout_and_log(210 # 'Generating {0} notifications'.format(211 # NotificationCode.CLIENT_REGISTRATION_INCOMPLETE),212 # self.stdout213 # )214 # time_start = timezone.now()215 # notification_count = generate_client_registration_incomplete_notifications(216 # dry_run=dry_run217 # )218 # time_end = timezone.now()219 # stdout_and_log('...{0} {2} notifications generated; took {1} seconds'.format(220 # notification_count, (time_end - time_start).total_seconds(),221 # NotificationCode.CLIENT_REGISTRATION_INCOMPLETE222 # ), self.stdout)223 # stdout_and_log(224 # 'Generating {0} notifications'.format(225 # NotificationCode.APPEARED_IN_SEARCH),226 # self.stdout227 # )228 # time_start = timezone.now()229 # notification_count = generate_stylist_appeared_in_search_notification(230 # dry_run=dry_run231 # )232 # time_end = timezone.now()233 # stdout_and_log('...{0} {2} notifications generated; took {1} seconds'.format(234 # notification_count, (time_end - time_start).total_seconds(),235 # NotificationCode.APPEARED_IN_SEARCH236 # ), self.stdout)237 if force_send:238 self.stdout.write('Going to send push notifications now')239 sent, skipped = send_all_notifications(stdout=self.stdout, dry_run=dry_run)...
test-terraform.spec.ts
Source:test-terraform.spec.ts
1import { isValidJSONString, startMockServer } from './helpers';2import * as path from 'path';3jest.setTimeout(50000);4describe('Terraform', () => {5 let run: (6 cmd: string,7 ) => Promise<{ stdout: string; stderr: string; exitCode: number }>;8 let teardown: () => void;9 beforeAll(async () => {10 const result = await startMockServer();11 run = result.run;12 teardown = result.teardown;13 });14 afterAll(async () => teardown());15 describe('Terraform single file scans', () => {16 it('finds issues in Terraform file', async () => {17 const { stdout, exitCode } = await run(18 `snyk iac test ./iac/terraform/sg_open_ssh.tf`,19 );20 expect(stdout).toContain('Testing ./iac/terraform/sg_open_ssh.tf');21 expect(stdout).toContain('Infrastructure as code issues:');22 expect(stdout).toContain('â Security Group allows open ingress');23 expect(stdout).toContain(24 ' input > resource > aws_security_group[allow_ssh] > ingress',25 );26 expect(exitCode).toBe(1);27 });28 it('filters out issues when using severity threshold', async () => {29 const { stdout, exitCode } = await run(30 `snyk iac test ./iac/terraform/sg_open_ssh.tf --severity-threshold=high`,31 );32 expect(stdout).toContain('Infrastructure as code issues:');33 expect(stdout).toContain(34 'Tested ./iac/terraform/sg_open_ssh.tf for known issues, found 0 issues',35 );36 expect(exitCode).toBe(0);37 });38 it('outputs an error for files with invalid HCL2', async () => {39 const { stdout, exitCode } = await run(40 `snyk iac test ./iac/terraform/sg_open_ssh_invalid_hcl2.tf`,41 );42 expect(stdout).toContain('We were unable to parse the Terraform file');43 expect(exitCode).toBe(2);44 });45 it('outputs the expected text when running with --sarif flag', async () => {46 const { stdout, exitCode } = await run(47 `snyk iac test ./iac/terraform/sg_open_ssh.tf --sarif`,48 );49 expect(isValidJSONString(stdout)).toBe(true);50 expect(stdout).toContain('"id": "SNYK-CC-TF-1",');51 expect(stdout).toContain('"ruleId": "SNYK-CC-TF-1",');52 expect(exitCode).toBe(1);53 });54 it('outputs the expected text when running with --json flag', async () => {55 const { stdout, exitCode } = await run(56 `snyk iac test ./iac/terraform/sg_open_ssh.tf --json`,57 );58 expect(isValidJSONString(stdout)).toBe(true);59 expect(stdout).toContain('"id": "SNYK-CC-TF-1",');60 expect(stdout).toContain('"packageManager": "terraformconfig",');61 expect(stdout).toContain('"projectType": "terraformconfig",');62 expect(exitCode).toBe(1);63 });64 it('returns error empty Terraform file', async () => {65 const { exitCode } = await run(66 `snyk iac test ./iac/terraform/empty_file.tf`,67 );68 expect(exitCode).toBe(3);69 });70 });71 describe('Terraform directories', () => {72 it('dereferences variables in nested directories', async () => {73 const { stdout, exitCode } = await run(74 `snyk iac test ./iac/terraform/var_deref`,75 );76 expect(stdout).toContain('Testing sg_open_ssh.tf...');77 expect(78 stdout.match(/â Security Group allows open ingress/g),79 ).toHaveLength(5);80 expect(stdout).toContain('Tested sg_open_ssh.tf for known issues');81 expect(stdout).toContain(82 `Testing ${path.join('nested_var_deref', 'sg_open_ssh.tf')}...`,83 );84 expect(stdout.match(/â Rule allows open egress/g)).toHaveLength(1);85 expect(stdout).toContain(86 `Tested ${path.join(87 'nested_var_deref',88 'sg_open_ssh.tf',89 )} for known issues`,90 );91 expect(exitCode).toBe(1);92 });93 it('scans a mix of IaC files in nested directories', async () => {94 const { stdout, exitCode } = await run(`snyk iac test ./iac`);95 expect(stdout).toContain(96 `Testing ${path.join('kubernetes', 'pod-privileged.yaml')}`,97 );98 expect(stdout).toContain(99 `Tested ${path.join(100 'kubernetes',101 'pod-privileged.yaml',102 )} for known issues`,103 );104 expect(stdout).toContain(105 `Testing ${path.join('terraform', 'var_deref', 'sg_open_ssh.tf')}`,106 );107 expect(108 stdout.match(/â Security Group allows open ingress/g),109 ).toHaveLength(9);110 expect(stdout).toContain(111 `Tested ${path.join(112 'terraform',113 'var_deref',114 'sg_open_ssh.tf',115 )} for known issues`,116 );117 expect(stdout).toContain(118 `Testing ${path.join(119 'terraform',120 'var_deref',121 'nested_var_deref',122 'sg_open_ssh.tf',123 )}...`,124 );125 expect(stdout.match(/â Rule allows open egress/g)).toHaveLength(1);126 expect(stdout).toContain(127 `Tested ${path.join(128 'terraform',129 'var_deref',130 'nested_var_deref',131 'sg_open_ssh.tf',132 )} for known issues`,133 );134 expect(exitCode).toBe(1);135 });136 it('filters out issues when using detection depth', async () => {137 const { stdout, exitCode } = await run(138 `snyk iac test ./iac/terraform/ --detection-depth=1`,139 );140 expect(stdout).toContain(141 `Testing ${path.join('var_deref', 'sg_open_ssh.tf')}`,142 );143 expect(stdout).toContain(144 `Tested ${path.join('var_deref', 'sg_open_ssh.tf')} for known issues`,145 );146 expect(stdout).toContain(`Testing ${path.join('sg_open_ssh.tf')}`);147 expect(stdout).toContain('Tested sg_open_ssh.tf for known issues');148 expect(149 stdout.match(/â Security Group allows open ingress/g),150 ).toHaveLength(6);151 // Check that we didn't scan directories with depth > 2152 expect(stdout).not.toContain(153 `Testing ${path.join(154 'var_deref',155 'nested_var_deref',156 'sg_open_ssh.tf',157 )}...`,158 );159 expect(stdout.match(/â Rule allows open egress/g)).toBeNull();160 expect(stdout).not.toContain(161 `Tested ${path.join(162 'var_deref',163 'nested_var_deref',164 'sg_open_ssh.tf',165 )} for known issues`,166 );167 expect(exitCode).toBe(1);168 });169 });170 describe('with the --var-file flag', () => {171 it('picks up the file and dereferences the variable context for the right directory (pathToScan)', async () => {172 const { stdout, exitCode } = await run(173 `snyk iac test ./iac/terraform/var_deref/nested_var_deref --var-file=./iac/terraform/vars.tf`,174 );175 expect(stdout).toContain(176 `Testing ${path.relative(177 './iac/terraform/var_deref/nested_var_deref',178 './iac/terraform/vars.tf',179 )}`,180 );181 expect(stdout).toContain(182 'introduced by input > resource > aws_security_group[allow_ssh_external_var_file] > ingress\n',183 );184 expect(185 stdout.match(186 /Project path: {6}.\/iac\/terraform\/var_deref\/nested_var_deref/g,187 ),188 ).toHaveLength(3);189 expect(stdout.match(/Project path: {6}.\/iac\/terraform$/g)).toBeNull();190 expect(exitCode).toBe(1);191 });192 it('returns error if the file does not exist', async () => {193 const { stdout, exitCode } = await run(194 `snyk iac test ./iac/terraform/var_deref --var-file=./iac/terraform/non-existent.tfvars`,195 );196 expect(stdout).toContain(197 'We were unable to locate a variable definitions file at: "./iac/terraform/non-existent.tfvars". The file at the provided path does not exist',198 );199 expect(exitCode).toBe(2);200 });201 it('will not parse the external file if it is invalid', async () => {202 const { stdout, exitCode } = await run(203 `snyk iac test ./iac/terraform/var_deref --var-file=./iac/terraform/sg_open_ssh_invalid_hcl2.tf`,204 );205 expect(stdout).toContain('Testing sg_open_ssh_invalid_hcl2.tf...');206 expect(stdout).toContain('Failed to parse Terraform file');207 expect(exitCode).toBe(1);208 });209 });...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!