How to use stdout method in stryker-parent

Best JavaScript code snippet using stryker-parent

text.spec.ts

Source:text.spec.ts Github

copy

Full Screen

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 });...

Full Screen

Full Screen

test-directory.spec.ts

Source:test-directory.spec.ts Github

copy

Full Screen

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 });...

Full Screen

Full Screen

generate_notifications.py

Source:generate_notifications.py Github

copy

Full Screen

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)...

Full Screen

Full Screen

test-terraform.spec.ts

Source:test-terraform.spec.ts Github

copy

Full Screen

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 });...

Full Screen

Full Screen

test_iostream.py

Source:test_iostream.py Github

copy

Full Screen

...15 # Python 3.416 from contextlib import redirect_stdout17except ImportError:18 @contextmanager19 def redirect_stdout(target):20 original = sys.stdout21 sys.stdout = target22 yield23 sys.stdout = original24try:25 # Python 3.526 from contextlib import redirect_stderr27except ImportError:28 @contextmanager29 def redirect_stderr(target):30 original = sys.stderr31 sys.stderr = target32 yield33 sys.stderr = original34def test_captured(capsys):35 msg = "I've been redirected to Python, I hope!"36 m.captured_output(msg)37 stdout, stderr = capsys.readouterr()38 assert stdout == msg39 assert stderr == ""40 m.captured_output_default(msg)41 stdout, stderr = capsys.readouterr()42 assert stdout == msg43 assert stderr == ""44 m.captured_err(msg)45 stdout, stderr = capsys.readouterr()46 assert stdout == ""47 assert stderr == msg48def test_captured_large_string(capsys):49 # Make this bigger than the buffer used on the C++ side: 1024 chars50 msg = "I've been redirected to Python, I hope!"51 msg = msg * (1024 // len(msg) + 1)52 m.captured_output_default(msg)53 stdout, stderr = capsys.readouterr()54 assert stdout == msg55 assert stderr == ""56def test_captured_utf8_2byte_offset0(capsys):57 msg = "\u07FF"58 msg = "" + msg * (1024 // len(msg) + 1)59 m.captured_output_default(msg)60 stdout, stderr = capsys.readouterr()61 assert stdout == msg62 assert stderr == ""63def test_captured_utf8_2byte_offset1(capsys):64 msg = "\u07FF"65 msg = "1" + msg * (1024 // len(msg) + 1)66 m.captured_output_default(msg)67 stdout, stderr = capsys.readouterr()68 assert stdout == msg69 assert stderr == ""70def test_captured_utf8_3byte_offset0(capsys):71 msg = "\uFFFF"72 msg = "" + msg * (1024 // len(msg) + 1)73 m.captured_output_default(msg)74 stdout, stderr = capsys.readouterr()75 assert stdout == msg76 assert stderr == ""77def test_captured_utf8_3byte_offset1(capsys):78 msg = "\uFFFF"79 msg = "1" + msg * (1024 // len(msg) + 1)80 m.captured_output_default(msg)81 stdout, stderr = capsys.readouterr()82 assert stdout == msg83 assert stderr == ""84def test_captured_utf8_3byte_offset2(capsys):85 msg = "\uFFFF"86 msg = "12" + msg * (1024 // len(msg) + 1)87 m.captured_output_default(msg)88 stdout, stderr = capsys.readouterr()89 assert stdout == msg90 assert stderr == ""91def test_captured_utf8_4byte_offset0(capsys):92 msg = "\U0010FFFF"93 msg = "" + msg * (1024 // len(msg) + 1)94 m.captured_output_default(msg)95 stdout, stderr = capsys.readouterr()96 assert stdout == msg97 assert stderr == ""98def test_captured_utf8_4byte_offset1(capsys):99 msg = "\U0010FFFF"100 msg = "1" + msg * (1024 // len(msg) + 1)101 m.captured_output_default(msg)102 stdout, stderr = capsys.readouterr()103 assert stdout == msg104 assert stderr == ""105def test_captured_utf8_4byte_offset2(capsys):106 msg = "\U0010FFFF"107 msg = "12" + msg * (1024 // len(msg) + 1)108 m.captured_output_default(msg)109 stdout, stderr = capsys.readouterr()110 assert stdout == msg111 assert stderr == ""112def test_captured_utf8_4byte_offset3(capsys):113 msg = "\U0010FFFF"114 msg = "123" + msg * (1024 // len(msg) + 1)115 m.captured_output_default(msg)116 stdout, stderr = capsys.readouterr()117 assert stdout == msg118 assert stderr == ""119def test_guard_capture(capsys):120 msg = "I've been redirected to Python, I hope!"121 m.guard_output(msg)122 stdout, stderr = capsys.readouterr()123 assert stdout == msg124 assert stderr == ""125def test_series_captured(capture):126 with capture:127 m.captured_output("a")128 m.captured_output("b")129 assert capture == "ab"130def test_flush(capfd):131 msg = "(not flushed)"132 msg2 = "(flushed)"133 with m.ostream_redirect():134 m.noisy_function(msg, flush=False)135 stdout, stderr = capfd.readouterr()136 assert stdout == ""137 m.noisy_function(msg2, flush=True)138 stdout, stderr = capfd.readouterr()139 assert stdout == msg + msg2140 m.noisy_function(msg, flush=False)141 stdout, stderr = capfd.readouterr()142 assert stdout == msg143def test_not_captured(capfd):144 msg = "Something that should not show up in log"145 stream = StringIO()146 with redirect_stdout(stream):147 m.raw_output(msg)148 stdout, stderr = capfd.readouterr()149 assert stdout == msg150 assert stderr == ""151 assert stream.getvalue() == ""152 stream = StringIO()153 with redirect_stdout(stream):154 m.captured_output(msg)155 stdout, stderr = capfd.readouterr()156 assert stdout == ""157 assert stderr == ""158 assert stream.getvalue() == msg159def test_err(capfd):160 msg = "Something that should not show up in log"161 stream = StringIO()162 with redirect_stderr(stream):163 m.raw_err(msg)164 stdout, stderr = capfd.readouterr()165 assert stdout == ""166 assert stderr == msg167 assert stream.getvalue() == ""168 stream = StringIO()169 with redirect_stderr(stream):170 m.captured_err(msg)171 stdout, stderr = capfd.readouterr()172 assert stdout == ""173 assert stderr == ""174 assert stream.getvalue() == msg175def test_multi_captured(capfd):176 stream = StringIO()177 with redirect_stdout(stream):178 m.captured_output("a")179 m.raw_output("b")180 m.captured_output("c")181 m.raw_output("d")182 stdout, stderr = capfd.readouterr()183 assert stdout == "bd"184 assert stream.getvalue() == "ac"185def test_dual(capsys):186 m.captured_dual("a", "b")187 stdout, stderr = capsys.readouterr()188 assert stdout == "a"189 assert stderr == "b"190def test_redirect(capfd):191 msg = "Should not be in log!"192 stream = StringIO()193 with redirect_stdout(stream):194 m.raw_output(msg)195 stdout, stderr = capfd.readouterr()196 assert stdout == msg197 assert stream.getvalue() == ""198 stream = StringIO()199 with redirect_stdout(stream):200 with m.ostream_redirect():201 m.raw_output(msg)202 stdout, stderr = capfd.readouterr()203 assert stdout == ""204 assert stream.getvalue() == msg205 stream = StringIO()206 with redirect_stdout(stream):207 m.raw_output(msg)208 stdout, stderr = capfd.readouterr()209 assert stdout == msg210 assert stream.getvalue() == ""211def test_redirect_err(capfd):212 msg = "StdOut"213 msg2 = "StdErr"214 stream = StringIO()215 with redirect_stderr(stream):216 with m.ostream_redirect(stdout=False):217 m.raw_output(msg)218 m.raw_err(msg2)219 stdout, stderr = capfd.readouterr()220 assert stdout == msg221 assert stderr == ""222 assert stream.getvalue() == msg2223def test_redirect_both(capfd):224 msg = "StdOut"225 msg2 = "StdErr"226 stream = StringIO()227 stream2 = StringIO()228 with redirect_stdout(stream):229 with redirect_stderr(stream2):230 with m.ostream_redirect():231 m.raw_output(msg)232 m.raw_err(msg2)233 stdout, stderr = capfd.readouterr()234 assert stdout == ""235 assert stderr == ""236 assert stream.getvalue() == msg237 assert stream2.getvalue() == msg2238def test_threading():239 with m.ostream_redirect(stdout=True, stderr=False):240 # start some threads241 threads = []242 # start some threads...

Full Screen

Full Screen

process_monitor.py

Source:process_monitor.py Github

copy

Full Screen

1#!/usr/bin/python2import subprocess3import sys4import resource5import collections6import datetime7import socket8def execute_str(cmd_str):9 p = subprocess.Popen(cmd_str,shell=True,stdout = subprocess.PIPE,stderr = subprocess.PIPE)10 (stdout,stderr) = p.communicate()11 return_code = p.returncode12 err = return_code!=013 stdout_str = str(stdout)14 stderr_str = str(stderr)15 return (err,stdout_str,stderr_str)16def write_msg_to_file(filepath,msg):17 fid = open(filepath,'wt')18 fid.write(msg+'\n')19 fid.close()20def get_timestamp():21 t=datetime.datetime.now()22 try:23 #Python 3 version24 timestamp='{0.year:d}_{0.month:02d}_{0.day:02d}__{0.hour:02d}_{0.minute:02d}_{0.second:02d}'.format(t)25 except:26 #Python 2 version27 timestamp = '%d_%02d_%02d__%02d_%02d_%02d'%(t.year,t.month,t.day,t.hour,t.minute,t.second)28 return timestamp29def get_timestamp_delta(ts_begin,ts_end):30 begin_secs = timestamp_to_seconds(ts_begin)31 end_secs = timestamp_to_seconds(ts_end)32 duration = end_secs - begin_secs33 return duration34def timestamp_to_seconds(timestamp):35 (year,month,day,junk,hour,minute,second)= timestamp.split('_')36 (year,month,day,junk,hour,minute,second) = (37 int(year),int(month),int(day),junk,int(hour),int(minute),int(second))38 dt = datetime.datetime(year,month,day,hour,minute,second)39 days = dt.toordinal()40 days = days - 733000 # keep the seconds to a managable size...41 secs = days*24*60*60 + hour*60*60 + minute*60 + second42 return secs43cmd_str = ' '.join(sys.argv[1:])44(err,stdout_str1,stderr_str) = execute_str('whoami')45(err,stdout_str2,stderr_str) = execute_str('uname -a')46(err,stdout_str3,stderr_str) = execute_str('df -h')47(err,stdout_str4,stderr_str) = execute_str('echo num processors: `grep -c ^processor /proc/cpuinfo`')48(err,stdout_str5,stderr_str) = execute_str('free -th')49(err,stdout_str20,stderr_str) = execute_str('pwd')50(err,stdout_str10,stderr_str) = execute_str('curl "http://metadata.google.internal/computeMetadata/v1/project/project-id" -H "Metadata-Flavor: Google"')51(err,stdout_str11,stderr_str) = execute_str('curl "http://metadata.google.internal/computeMetadata/v1/instance/zone" -H "Metadata-Flavor: Google"')52(err,stdout_str12,stderr_str) = execute_str('curl "http://metadata.google.internal/computeMetadata/v1/instance/machine-type" -H "Metadata-Flavor: Google"')53(err,stdout_str13, stderr_str) = execute_str('curl "http://metadata.google.internal/computeMetadata/v1/instance/hostname" -H "Metadata-Flavor: Google"')54(err,stdout_str14, stderr_str) = execute_str('curl "http://metadata.google.internal/computeMetadata/v1/instance/scheduling/preemptible" -H "Metadata-Flavor: Google"')55(err,stdout_str15, stderr_str) = execute_str('curl "http://metadata.google.internal/computeMetadata/v1/instance/description" -H "Metadata-Flavor: Google"')56# todo - add info about gce disk types and sizes via instance/disks57(err,stdout_str16, stderr_str) = execute_str('curl "http://metadata.google.internal/computeMetadata/v1/instance/disks/" -H "Metadata-Flavor: Google" | wc -l')58num_disks = int(stdout_str16)59disk_info = ''60for d in range(num_disks):61 (err, stdout_str17, stderr_str) = execute_str(62 'curl "http://metadata.google.internal/computeMetadata/v1/instance/disks/%d/type" -H "Metadata-Flavor: Google" | wc -l')63 info = 'disk %d: %s; '%(d,stdout_str17)64 disk_info += info65#cmd_str66#write to log67fid = open('monitor_status_before.txt','w')68fid.write(stdout_str1)69fid.write(stdout_str2)70fid.write(stdout_str3)71fid.write(stdout_str4)72fid.write(stdout_str5)73fid.write('project-id: %s'%stdout_str10)74fid.write('zone: %s'%stdout_str11)75fid.write('machine-type: %s'%stdout_str12)76fid.write('hostname: %s'%stdout_str13)77fid.write('preemptable: %s'%stdout_str14)78fid.write('description: %s'%stdout_str15)79fid.write('disk info: %s'%disk_info)80fid.write('\n\ncd %s\n\n%s\n\n'%(stdout_str20, cmd_str))81fid.close()82#write to stdout83print(stdout_str1)84print(stdout_str2)85print(stdout_str3)86print(stdout_str4)87print(stdout_str5)88print('project-id: %s'%stdout_str10)89print('zone: %s'%stdout_str11)90print('machine-type: %s'%stdout_str12)91print('hostname: %s'%stdout_str13)92print('preemptable: %s'%stdout_str14)93print('description: %s'%stdout_str15)94print('disk info: %s'%disk_info)95print('\n\ncd %s\n\n%s\n\n' % (stdout_str20, cmd_str))96# launch dstat as a background process97dstat_cmd_str = "dstat --nocolor --noheaders --freespace --top-cpu-adv --top-io --top-mem --top-bio-adv --dstat-mem -cdngymt --output dstat.log.txt"98dstat_list=dstat_cmd_str.split()99dstat_process = subprocess.Popen(dstat_list)100#df_monitor_cmd_str="/home/disk_monitor.sh df.log.txt"101#df_monitor_process=subprocess.Popen(df_monitor_cmd_str.split())102start_timestamp = get_timestamp()103# run command, wait it to complete104exit_code = subprocess.call(cmd_str, shell=True)105end_timestamp = get_timestamp()106# kill the dstat background process in a way that allows it to close the file properly107dstat_process.terminate()108#df_monitor_process.terminate()109# generate stats from running110usage = resource.getrusage(resource.RUSAGE_CHILDREN)111if exit_code == 0:112 passfail = "pass"113else:114 passfail = "FAIL"115maxrss_memory = float(usage.ru_maxrss) / (2 ** 20) # convert memory to GB116usage_dict = collections.OrderedDict()117usage_dict['#status'] = passfail118usage_dict['exit_code'] = str(exit_code)119usage_dict['start_time'] = start_timestamp120usage_dict['end_time'] = end_timestamp121usage_dict['wallclock_duration_s'] = str(get_timestamp_delta(start_timestamp, end_timestamp))122usage_dict['user_cputime_s'] = '%7.3f' % usage.ru_utime123usage_dict['system_cputime_s'] = '%7.3f' % usage.ru_stime124# note maxrss may just capture the real memory used by the largest child, not all the children125usage_dict['maxrss_memory_gb'] = '%7.3f' % maxrss_memory126usage_dict['page_faults'] = '%d' % usage.ru_majflt127usage_dict['node_ip_addr'] = socket.gethostbyname(socket.gethostname())128(err,stdout_str3,stderr_str) = execute_str('df -h')129(err,stdout_str5,stderr_str) = execute_str('free -th')130#write to log131fid = open('monitor_status_after.txt','a')132fid.write(stdout_str3)133fid.write(stdout_str5)134for key in usage_dict:135 fid.write('%s: %s\n'%(key,usage_dict[key]))136fid.close()137# write to stdout138print(stdout_str3)139print(stdout_str5)140for key in usage_dict:141 print('%s: %s' % (key, usage_dict[key]))...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var strykerParent = require('stryker-parent');2strykerParent.stdout('Hello world!');3var strykerParent = require('stryker-parent');4strykerParent.stderr('Hello world!');5var strykerParent = require('stryker-parent');6strykerParent.write('Hello world!');7var strykerParent = require('stryker-parent');8strykerParent.write('Hello world!', 'utf8');9var strykerParent = require('stryker-parent');10strykerParent.write('Hello world!', 'utf8', function() {11 console.log('Data written');12});13var strykerParent = require('stryker-parent');14strykerParent.write('Hello world!', 'utf8', function() {15 console.log('Data written');16});17var strykerParent = require('stryker-parent');18strykerParent.write('Hello world!', 'utf8', function() {19 console.log('Data written');20});21var strykerParent = require('stryker-parent');22strykerParent.write('Hello world!', 'utf8', function() {23 console.log('Data written');24});25var strykerParent = require('stryker-parent');26strykerParent.write('Hello world!', 'utf8', function() {27 console.log('Data written');28});29var strykerParent = require('stryker-parent');30strykerParent.write('Hello world!', 'utf8', function() {31 console.log('Data written');32});33var strykerParent = require('stryker-parent');34strykerParent.write('Hello world!', 'utf

Full Screen

Using AI Code Generation

copy

Full Screen

1var stdout = require('stryker-parent').stdout;2stdout.write("Hello World");3var stderr = require('stryker-parent').stderr;4stderr.write("Hello World");5var log = require('stryker-parent').log;6log.info("Hello World");7log.trace("Hello World");8log.debug("Hello World");9log.warn("Hello World");10log.error("Hello World");11log.fatal("Hello World");12var strykerParent = require('stryker-parent');13strykerParent.stdout.write("Hello World");14strykerParent.stderr.write("Hello World");15strykerParent.log.info("Hello World");16strykerParent.log.trace("Hello World");17strykerParent.log.debug("Hello World");18strykerParent.log.warn("Hello World");19strykerParent.log.error("Hello World");20strykerParent.log.fatal("Hello World");

Full Screen

Using AI Code Generation

copy

Full Screen

1var parent = require('stryker-parent');2parent.stdout('Hello world');3var parent = require('stryker-parent');4parent.stderr('Hello world');5var parent = require('stryker-parent');6parent.exit(1);7var parent = require('stryker-parent');8parent.kill();9var parent = require('stryker-parent');10parent.log('Hello world');11var parent = require('stryker-parent');12parent.log('Hello world', 'log');13var parent = require('stryker-parent');14parent.log('Hello world', 'warn');15var parent = require('stryker-parent');16parent.log('Hello world', 'error');17var parent = require('stryker-parent');18parent.log('Hello world', 'info');19var parent = require('stryker-parent');20parent.log('Hello world', 'trace');21var parent = require('stryker-parent');22parent.log('Hello world', 'debug');23var parent = require('stryker-parent');24parent.log('Hello world', 'fatal');25var parent = require('stryker-parent');26parent.log('Hello world', 'error');27var parent = require('stryker-parent');28parent.log('Hello world', 'info');29var parent = require('stryker-parent');30parent.log('Hello world

Full Screen

Using AI Code Generation

copy

Full Screen

1var parent = require('stryker-parent');2var stryker = new parent.Stryker();3var options = {4 testRunnerOptions: {5 }6};7stryker.runMutationTest(options).then(function (result) {8 console.log(result);9}, function (error) {10 console.error(error);11});12var parent = require('stryker-parent');13var stryker = new parent.Stryker();14var options = {15 testRunnerOptions: {16 }17};18stryker.runMutationTest(options).then(function (result) {19 console.log(result);20}, function (error) {21 console.error(error);22});23var parent = require('stryker-parent');24var stryker = new parent.Stryker();25var options = {26 testRunnerOptions: {27 }28};29stryker.runMutationTest(options).then(function (result) {30 console.log(result);31}, function (error) {32 console.error(error);33});34var parent = require('stryker-parent');35var stryker = new parent.Stryker();36var options = {37 testRunnerOptions: {38 }39};40stryker.runMutationTest(options).then(function (result) {41 console.log(result);42}, function (error) {43 console.error(error);44});45var parent = require('stryker-parent');46var stryker = new parent.Stryker();47var options = {

Full Screen

Using AI Code Generation

copy

Full Screen

1var stryker = require('stryker-parent');2var strykerParent = stryker({port: 8080});3strykerParent.stdout.on('data', function (data) {4 console.log('stdout: ' + data);5});6var stryker = require('stryker-parent');7var strykerParent = stryker({port: 8080});8strykerParent.stderr.on('data', function (data) {9 console.log('stderr: ' + data);10});11var stryker = require('stryker-parent');12var strykerParent = stryker({port: 8080});13strykerParent.on('data', function (data) {14 console.log('data: ' + data);15});16var stryker = require('stryker-parent');17var strykerParent = stryker({port: 8080});18strykerParent.on('exit', function (data) {19 console.log('exit: ' + data);20});21var stryker = require('stryker-parent');22var strykerParent = stryker({port: 8080});23strykerParent.on('error', function (data) {24 console.log('error: ' + data);25});26var stryker = require('stryker-parent');27var strykerParent = stryker({port: 8080});28strykerParent.on('close', function (data) {29 console.log('close: ' + data);30});31var stryker = require('stryker-parent');32var strykerParent = stryker({port: 8080});33strykerParent.on('disconnect', function (data) {34 console.log('disconnect: ' + data);35});36var stryker = require('stryker-parent');37var strykerParent = stryker({port: 8080});38strykerParent.on('message', function (data) {39 console.log('message: ' + data);40});

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run stryker-parent automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful