xml2js#parseString TypeScript Examples

The following examples show how to use xml2js#parseString. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: jacoco.test.ts    From backstage with Apache License 2.0 6 votes vote down vote up
/* eslint-disable no-restricted-syntax */

describe('convert jacoco', () => {
  const converter = new Jacoco(getVoidLogger());
  let fixture: JacocoXML;
  parseString(
    fs.readFileSync(
      path.resolve(`${__dirname}/../__fixtures__/jacoco-testdata-1.xml`),
    ),
    (_e, r) => {
      fixture = r;
    },
  );
  const expected = JSON.parse(
    fs
      .readFileSync(
        path.resolve(
          `${__dirname}/../__fixtures__/jacoco-jsoncoverage-files-1.json`,
        ),
      )
      .toString(),
  );
  const scmFiles = fs
    .readFileSync(
      path.resolve(`${__dirname}/../__fixtures__/jacoco-sourcefiles-1.txt`),
    )
    .toString()
    .split('\n');

  it('converts a jacoco report', () => {
    const files = converter.convert(fixture, scmFiles);

    expect(files.sort()).toEqual(expected.sort());
  });
});
Example #2
Source File: cobertura.test.ts    From backstage with Apache License 2.0 5 votes vote down vote up
/* eslint-disable no-restricted-syntax */

describe('convert cobertura', () => {
  const converter = new Cobertura(getVoidLogger());
  [1, 2, 3, 4, 5].forEach(idx => {
    let fixture: CoberturaXML;
    parseString(
      fs.readFileSync(
        path.resolve(
          __dirname,
          '..',
          '__fixtures__',
          `cobertura-testdata-${idx}.xml`,
        ),
      ),
      (_e, r) => {
        fixture = r;
      },
    );
    const expected = JSON.parse(
      fs
        .readFileSync(
          path.resolve(
            __dirname,
            '..',
            '__fixtures__',
            `cobertura-jsoncoverage-files-${idx}.json`,
          ),
        )
        .toString(),
    );
    const scmFiles = fs
      .readFileSync(
        path.resolve(
          __dirname,
          '..',
          '__fixtures__',
          `cobertura-sourcefiles-${idx}.txt`,
        ),
      )
      .toString()
      .split('\n');

    it(`${idx} converts a cobertura report`, () => {
      const files = converter.convert(fixture, scmFiles);

      expect(files).toEqual(expected);
    });
  });
});
Example #3
Source File: CoverageUtils.test.ts    From backstage with Apache License 2.0 4 votes vote down vote up
describe('CodeCoverageUtils', () => {
  const scmFilesFixture = fs
    .readFileSync(`${__dirname}/__fixtures__/cobertura-sourcefiles-1.txt`)
    .toString()
    .split('\n')
    .map(f => {
      return { path: f };
    });
  const scmIntegraions = {
    byUrl: jest.fn().mockReturnValue({
      type: 'local',
      title: 'local',
    }),
  };
  const scmTree = {
    files: jest
      .fn()
      .mockReturnValue(new Promise((r, _e) => r(scmFilesFixture))),
  };
  const urlReader = {
    readTree: jest.fn().mockReturnValue(new Promise((r, _e) => r(scmTree))),
  };
  const utils = new CoverageUtils(scmIntegraions, urlReader);

  describe('validateRequestBody', () => {
    it('rejects missing content type', () => {
      let err: Error | null = null;
      try {
        utils.validateRequestBody({
          headers: {},
        } as Request);
      } catch (error: any) {
        err = error;
      }
      expect(err?.message).toEqual('Content-Type missing');
    });

    it('rejects unsupported content type', () => {
      let err: Error | null = null;
      try {
        utils.validateRequestBody({
          headers: {
            'content-type': 'application/json',
          },
        } as Request);
      } catch (error: any) {
        err = error;
      }
      expect(err?.message).toEqual('Illegal Content-Type');
    });

    it('parses the body', () => {
      const data: Readable = utils.validateRequestBody({
        headers: {
          'content-type': 'text/xml',
        },
        body: Readable.from(
          '<?xml version="1.0" encoding="UTF-8" standalone="yes"?><report name="example"></report>',
        ),
      } as Request);

      expect(data.read()).toContain('<?xml');
    });
  });

  describe('processCoveragePayload', () => {
    const mockRequest = {
      headers: {
        'content-type': 'text/xml',
      },
      body: Readable.from(
        '<?xml version="1.0" encoding="UTF-8" standalone="yes"?><report name="example"></report>',
      ),
    } as Request;

    it('ignores scm if annotation is not set', async () => {
      const entity: Entity = {
        kind: 'Component',
        metadata: {
          name: 'test-entity',
          namespace: 'test',
        },
        apiVersion: 'backstage.io/v1alpha1',
      };

      const { scmFiles, sourceLocation, vcs, body } =
        await utils.processCoveragePayload(entity, mockRequest);
      let data;
      // in normal flow the express app will already have done this through the middleware
      parseString((body as Readable).read(), (_e, r) => {
        data = r;
      });

      expect(scmFiles.length).toBe(0);
      expect(vcs).toBeUndefined();
      expect(sourceLocation).toBeUndefined();
      expect(data).toEqual({
        report: {
          $: {
            name: 'example',
          },
        },
      });
    });

    it('populates scm data if annotation  is set', async () => {
      const entity: Entity = {
        kind: 'Component',
        metadata: {
          name: 'test-entity',
          namespace: 'test',
          annotations: {
            'backstage.io/code-coverage': 'scm-only',
            'backstage.io/source-location':
              'url:https://github.com/example/test/',
          },
        },
        apiVersion: 'backstage.io/v1alpha1',
      };

      const { scmFiles, sourceLocation, vcs } =
        await utils.processCoveragePayload(entity, mockRequest);

      expect(scmFiles.length).toBe(scmFiles.length);
      expect(vcs).not.toBeUndefined();
      expect(sourceLocation).not.toBeUndefined();
    });
  });
});