@jest/globals#beforeEach TypeScript Examples

The following examples show how to use @jest/globals#beforeEach. 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: context.test.ts    From ghaction-virustotal with MIT License 6 votes vote down vote up
describe('setOutput', () => {
  beforeEach(() => {
    process.stdout.write = jest.fn() as typeof process.stdout.write;
  });

  // eslint-disable-next-line jest/expect-expect
  it('setOutput produces the correct command', () => {
    context.setOutput('some output', 'some value');
    assertWriteCalls([`::set-output name=some output::some value${os.EOL}`]);
  });

  // eslint-disable-next-line jest/expect-expect
  it('setOutput handles bools', () => {
    context.setOutput('some output', false);
    assertWriteCalls([`::set-output name=some output::false${os.EOL}`]);
  });

  // eslint-disable-next-line jest/expect-expect
  it('setOutput handles numbers', () => {
    context.setOutput('some output', 1.01);
    assertWriteCalls([`::set-output name=some output::1.01${os.EOL}`]);
  });
});
Example #2
Source File: github.test.ts    From ghaction-virustotal with MIT License 6 votes vote down vote up
beforeEach(() => {
  Object.keys(process.env).forEach(function (key) {
    if (key !== 'GITHUB_TOKEN' && key.startsWith('GITHUB_')) {
      delete process.env[key];
    }
  });
  const repoEnv = dotenv.parse(fs.readFileSync(path.join(__dirname, 'fixtures', 'repo.env')));
  for (const k in repoEnv) {
    process.env[k] = repoEnv[k];
  }
  octokit = github.getOctokit(process.env.GITHUB_TOKEN || '', {
    log: console
  });
});
Example #3
Source File: context.test.ts    From bake-action with Apache License 2.0 6 votes vote down vote up
describe('setOutput', () => {
  beforeEach(() => {
    process.stdout.write = jest.fn() as typeof process.stdout.write;
  });

  // eslint-disable-next-line jest/expect-expect
  it('setOutput produces the correct command', () => {
    context.setOutput('some output', 'some value');
    assertWriteCalls([`::set-output name=some output::some value${os.EOL}`]);
  });

  // eslint-disable-next-line jest/expect-expect
  it('setOutput handles bools', () => {
    context.setOutput('some output', false);
    assertWriteCalls([`::set-output name=some output::false${os.EOL}`]);
  });

  // eslint-disable-next-line jest/expect-expect
  it('setOutput handles numbers', () => {
    context.setOutput('some output', 1.01);
    assertWriteCalls([`::set-output name=some output::1.01${os.EOL}`]);
  });
});
Example #4
Source File: ProjectConfigurationEditor.test.tsx    From legend-studio with Apache License 2.0 6 votes vote down vote up
beforeEach(async () => {
  mockedEditorStore = TEST__provideMockedEditorStore();
  renderResult = await TEST__setUpEditorWithDefaultSDLCData(mockedEditorStore, {
    entities: [],
    projectConfiguration: TEST_DATA__ProjectConfiguration,
    latestProjectStructureVersion: TEST_DATA__latestProjectStructure,
    projects: TEST_DATA__Projects,
    projectData: TEST_DATA__ProjectData,
    projectDependency: TEST_DATA__DependencyEntities,
  });
  fireEvent.click(renderResult.getByText('config'));
  const editPanel = await renderResult.findByTestId(
    LEGEND_STUDIO_TEST_ID.EDIT_PANEL_CONTENT,
  );
  const updateButton = getByText(editPanel, 'Update');
  expect(updateButton.getAttribute('disabled')).not.toBeNull();
  await waitFor(() => renderResult.getByText('Project Structure'));
});
Example #5
Source File: context.test.ts    From build-push-action with Apache License 2.0 6 votes vote down vote up
describe('setOutput', () => {
  beforeEach(() => {
    process.stdout.write = jest.fn() as typeof process.stdout.write;
  });

  // eslint-disable-next-line jest/expect-expect
  it('setOutput produces the correct command', () => {
    context.setOutput('some output', 'some value');
    assertWriteCalls([`::set-output name=some output::some value${os.EOL}`]);
  });

  // eslint-disable-next-line jest/expect-expect
  it('setOutput handles bools', () => {
    context.setOutput('some output', false);
    assertWriteCalls([`::set-output name=some output::false${os.EOL}`]);
  });

  // eslint-disable-next-line jest/expect-expect
  it('setOutput handles numbers', () => {
    context.setOutput('some output', 1.01);
    assertWriteCalls([`::set-output name=some output::1.01${os.EOL}`]);
  });
});
Example #6
Source File: context.test.ts    From setup-buildx-action with Apache License 2.0 6 votes vote down vote up
describe('setOutput', () => {
  beforeEach(() => {
    process.stdout.write = jest.fn() as typeof process.stdout.write;
  });

  // eslint-disable-next-line jest/expect-expect
  it('setOutput produces the correct command', () => {
    context.setOutput('some output', 'some value');
    assertWriteCalls([`::set-output name=some output::some value${os.EOL}`]);
  });

  // eslint-disable-next-line jest/expect-expect
  it('setOutput handles bools', () => {
    context.setOutput('some output', false);
    assertWriteCalls([`::set-output name=some output::false${os.EOL}`]);
  });

  // eslint-disable-next-line jest/expect-expect
  it('setOutput handles numbers', () => {
    context.setOutput('some output', 1.01);
    assertWriteCalls([`::set-output name=some output::1.01${os.EOL}`]);
  });
});
Example #7
Source File: GraphBuildFailure.test.ts    From legend-studio with Apache License 2.0 5 votes vote down vote up
beforeEach(async () => {
  graphManagerState = TEST__getTestGraphManagerState();
});
Example #8
Source File: Explorer.test.tsx    From legend-studio with Apache License 2.0 5 votes vote down vote up
beforeEach(async () => {
  mockedEditorStore = TEST__provideMockedEditorStore();
  renderResult = await TEST__setUpEditorWithDefaultSDLCData(mockedEditorStore, {
    entities: TEST_DATA__m2mGraphEntities,
  });
});
Example #9
Source File: CreateNewElement.test.tsx    From legend-studio with Apache License 2.0 5 votes vote down vote up
beforeEach(async () => {
  mockedEditorStore = TEST__provideMockedEditorStore();
  renderResult = await TEST__setUpEditorWithDefaultSDLCData(mockedEditorStore);
});
Example #10
Source File: UMLEditor.test.tsx    From legend-studio with Apache License 2.0 5 votes vote down vote up
beforeEach(async () => {
  const mockedEditorStore = TEST__provideMockedEditorStore();
  renderResult = await TEST__setUpEditorWithDefaultSDLCData(mockedEditorStore, {
    entities: TEST_DATA__m2mGraphEntities,
  });
});
Example #11
Source File: EnumerationMappingEditor.test.tsx    From legend-studio with Apache License 2.0 5 votes vote down vote up
beforeEach(async () => {
  mockedEditorStore = TEST__provideMockedEditorStore();
  renderResult = await TEST__setUpEditorWithDefaultSDLCData(mockedEditorStore, {
    entities: TEST_DATA__enumerationMappingEntities,
  });
});
Example #12
Source File: EditPanel.test.tsx    From legend-studio with Apache License 2.0 5 votes vote down vote up
beforeEach(async () => {
  const mockedEditorStore = TEST__provideMockedEditorStore();
  renderResult = await TEST__setUpEditorWithDefaultSDLCData(mockedEditorStore, {
    entities: TEST_DATA__m2mGraphEntities,
  });
});
Example #13
Source File: SimpleRelationalGraphBuildSuccess.test.ts    From legend-studio with Apache License 2.0 5 votes vote down vote up
beforeEach(async () => {
  graphManagerState = TEST__getTestGraphManagerState();
  await TEST__buildGraphWithEntities(
    graphManagerState,
    TEST_DATA__relationalCompleteGraphEntities as Entity[],
  );
});
Example #14
Source File: PropertyThroughAssociationGraphSuccess.test.ts    From legend-studio with Apache License 2.0 5 votes vote down vote up
beforeEach(async () => {
  graphManagerState = TEST__getTestGraphManagerState();
  await TEST__buildGraphWithEntities(
    graphManagerState,
    TEST_DATA__targetSetImplementationThroughAssociation as Entity[],
  );
});
Example #15
Source File: OtherwiseEmbeddedRelational.test.ts    From legend-studio with Apache License 2.0 5 votes vote down vote up
beforeEach(async () => {
  graphManagerState = TEST__getTestGraphManagerState();
  await TEST__buildGraphWithEntities(
    graphManagerState,
    TEST_DATA__otherwiseEmbeddedRelationalTestData as Entity[],
  );
});
Example #16
Source File: InlineEmbeddedRelational.test.ts    From legend-studio with Apache License 2.0 5 votes vote down vote up
beforeEach(async () => {
  graphManagerState = TEST__getTestGraphManagerState();
  await TEST__buildGraphWithEntities(
    graphManagerState,
    TEST_DATA__inlineEmbeddedRelationalTestData as Entity[],
  );
});
Example #17
Source File: EmbeddedRelational.test.ts    From legend-studio with Apache License 2.0 5 votes vote down vote up
beforeEach(async () => {
  graphManagerState = TEST__getTestGraphManagerState();
  await TEST__buildGraphWithEntities(
    graphManagerState,
    TEST_DATA__embeddedRelationalTestData as Entity[],
  );
});
Example #18
Source File: FileGenerationBuildSuccess.test.ts    From legend-studio with Apache License 2.0 5 votes vote down vote up
beforeEach(async () => {
  graphManagerState = TEST__getTestGraphManagerState();
  await TEST__buildGraphWithEntities(
    graphManagerState,
    TEST_DATA__fileGeneration as Entity[],
  );
});
Example #19
Source File: GlobalTestRunner.test.tsx    From legend-studio with Apache License 2.0 5 votes vote down vote up
beforeEach(async () => {
  mockedEditorStore = TEST__provideMockedEditorStore();
  renderResult = await TEST__setUpEditorWithDefaultSDLCData(mockedEditorStore, {
    entities: TEST_DATA__RelationalServiceTestable,
  });
});
Example #20
Source File: Setup.test.tsx    From legend-studio with Apache License 2.0 5 votes vote down vote up
beforeEach(() => {
  sdlcServerClient = TEST__provideMockedSDLCServerClient();
});
Example #21
Source File: slices.spec.tsx    From slice-machine with Apache License 2.0 4 votes vote down vote up
describe("slices", () => {
  const fakeTracker = jest.fn().mockImplementation(() => Promise.resolve());

  beforeAll(async () => {
    const div = document.createElement("div");
    div.setAttribute("id", "__next");
    document.body.appendChild(div);

    const fakeAnalytics = jest
      .spyOn(AnalyticsBrowser, "standalone")
      .mockResolvedValue({
        track: fakeTracker,
      } as any);

    await Tracker.get().initialize("foo", "repoName");
    expect(fakeAnalytics).toHaveBeenCalled();
  });

  afterEach(() => {
    jest.clearAllMocks();
  });

  beforeEach(async () => {
    mockRouter.setCurrentUrl("/slices");
  });

  test("When user creates a slice it should send a tracking event", async () => {
    const environment = {
      framework: "next",
      mockConfig: { _cts: {} },
    };

    const libraries = [
      {
        path: "./slices",
        isLocal: true,
        name: "slices",
        meta: {
          isNodeModule: false,
          isDownloaded: false,
          isManual: true,
        },
        components: [
          {
            from: "slices",
            href: "slices",
            pathToSlice: "./slices",
            fileName: "index",
            extension: "js",
            screenshotPaths: {},
            mock: [
              {
                variation: "default",
                name: "Default",
                slice_type: "test_slice",
                items: [],
                primary: {
                  title: [
                    {
                      type: "heading1",
                      text: "Cultivate granular e-services",
                      spans: [],
                    },
                  ],
                  description: [
                    {
                      type: "paragraph",
                      text: "Anim in commodo exercitation qui. Elit cillum officia mollit dolore. Commodo voluptate sit est proident ea proident dolor esse ad.",
                      spans: [],
                    },
                  ],
                },
              },
            ],
            model: {
              id: "test_slice",
              type: "SharedSlice",
              name: "TestSlice",
              description: "TestSlice",
              variations: [
                {
                  id: "default",
                  name: "Default",
                  docURL: "...",
                  version: "sktwi1xtmkfgx8626",
                  description: "TestSlice",
                  primary: [
                    {
                      key: "title",
                      value: {
                        type: "StructuredText",
                        config: {
                          single: "heading1",
                          label: "Title",
                          placeholder: "This is where it all begins...",
                        },
                      },
                    },
                    {
                      key: "description",
                      value: {
                        type: "StructuredText",
                        config: {
                          single: "paragraph",
                          label: "Description",
                          placeholder: "A nice description of your feature",
                        },
                      },
                    },
                  ],
                  items: [],
                  imageUrl:
                    "https://images.prismic.io/slice-machine/621a5ec4-0387-4bc5-9860-2dd46cbc07cd_default_ss.png?auto=compress,format",
                },
              ],
            },
            screenshotUrls: {},
            __status: "NEW_SLICE",
          },
        ],
      },
    ];
    const App = render(
      <LibrariesProvider
        env={environment}
        libraries={libraries}
        remoteSlices={[]}
      >
        <SlicesIndex />
      </LibrariesProvider>,
      {
        preloadedState: {
          environment,
          slices: {
            libraries,
            remoteSlices: [],
          },
        },
      }
    );

    const createOneButton = document.querySelector('[data-cy="create-slice"]');
    await act(async () => {
      fireEvent.click(createOneButton);
    });

    const nameInput = document.querySelector('[data-cy="slice-name-input"]');
    await act(async () => {
      fireEvent.change(nameInput, { target: { value: "FooBar" } });
    });

    const submitButton = screen.getByText("Create");
    await act(async () => {
      fireEvent.click(submitButton);
    });

    // very hacky, done because of bug where calling Router.router.push causes issues with re-renders and context
    delete window.location;
    window.location = {} as Location;

    await waitFor(() => {
      expect(fakeTracker).toHaveBeenCalledWith(
        "SliceMachine Slice Created",
        { id: "FooBar", name: "FooBar", library: "slices" },
        { context: { groupId: { Repository: "repoName" } } }
      );
    });
  });
});
Example #22
Source File: configure-project.test.ts    From slice-machine with Apache License 2.0 4 votes vote down vote up
describe("configure-project", () => {
  void beforeEach(() => {
    jest.spyOn(process, "exit").mockImplementation((number) => number as never);
    Tracker.get().initialize("foo");
    Tracker.get().setRepository("repoName");
  });

  void afterEach(() => {
    jest.clearAllMocks();
  });

  const fakeCwd = "./";
  const fakeBase = "https://music.to.my.hears.io" as Prismic.Endpoints.Base;
  const fakeRepository = "testing-repo";
  const fakeFrameworkStats = {
    value: Models.Frameworks.react,
    manuallyAdded: false,
  };

  const retrieveManifestMock = NodeUtils.retrieveManifest as jest.Mock;
  const createManifestMock = NodeUtils.createManifest as jest.Mock;
  const patchManifestMock = NodeUtils.patchManifest as jest.Mock;
  const addJsonPackageSmScriptMock =
    NodeUtils.addJsonPackageSmScript as jest.Mock;

  const { exists, mkdir } = NodeUtils.Files;
  const fileExistsMock = exists as jest.Mock;
  const mkdirMock = mkdir as jest.Mock;

  test("it should create a new manifest if it doesn't exist yet", async () => {
    retrieveManifestMock.mockReturnValue({
      exists: false,
      content: null,
    });
    addJsonPackageSmScriptMock.mockReturnValue(true);

    await configureProject(
      fakeCwd,
      fakeBase,
      fakeRepository,
      fakeFrameworkStats,
      []
    );

    expect(retrieveManifestMock).toBeCalled();
    expect(createManifestMock).toHaveBeenCalledWith("./", {
      _latest: "0.0.41",
      apiEndpoint: "https://testing-repo.music.to.my.hears.io/api/v2",
      libraries: ["@/slices"],
    });
    expect(patchManifestMock).not.toBeCalled();

    expect(successFn).toHaveBeenCalled();
    expect(failFn).not.toHaveBeenCalled();
    expect(MockTracker).toHaveBeenCalled();
  });

  test("it should patch the existing manifest", async () => {
    retrieveManifestMock.mockReturnValue({
      exists: true,
      content: {
        framework: Models.Frameworks.react,
      },
    });
    addJsonPackageSmScriptMock.mockReturnValue(true);

    await configureProject(
      fakeCwd,
      fakeBase,
      fakeRepository,
      fakeFrameworkStats,
      []
    );

    expect(retrieveManifestMock).toBeCalled();
    expect(patchManifestMock).toHaveBeenCalledWith("./", {
      apiEndpoint: "https://testing-repo.music.to.my.hears.io/api/v2",
      framework: "react",
      libraries: ["@/slices"],
    });

    expect(successFn).toHaveBeenCalled();
    expect(failFn).not.toHaveBeenCalled();
    expect(MockTracker).toHaveBeenCalled();
  });

  test("it should patch the existing manifest with external lib", async () => {
    retrieveManifestMock.mockReturnValue({
      exists: true,
      content: {
        framework: Models.Frameworks.react,
      },
    });
    addJsonPackageSmScriptMock.mockReturnValue(true);

    await configureProject(
      fakeCwd,
      fakeBase,
      fakeRepository,
      fakeFrameworkStats,
      ["@/material/slices"]
    );

    expect(retrieveManifestMock).toBeCalled();
    expect(patchManifestMock).toHaveBeenCalledWith("./", {
      apiEndpoint: "https://testing-repo.music.to.my.hears.io/api/v2",
      framework: "react",
      libraries: ["@/slices", "@/material/slices"],
    });

    expect(successFn).toHaveBeenCalled();
    expect(failFn).not.toHaveBeenCalled();
    expect(MockTracker).toHaveBeenCalled();
  });

  test("it should fail if retrieve manifest throws", async () => {
    retrieveManifestMock.mockImplementation(() => {
      throw new Error("fake error to test the catch");
    });

    // process.exit should throw
    await configureProject(
      fakeCwd,
      fakeBase,
      fakeRepository,
      fakeFrameworkStats,
      []
    );

    expect(retrieveManifestMock).toBeCalled();
    expect(createManifestMock).not.toBeCalled();
    expect(patchManifestMock).not.toBeCalled();

    expect(successFn).not.toHaveBeenCalled();
    expect(failFn).toHaveBeenCalled();
    expect(MockTracker).not.toHaveBeenCalled();
  });

  test("it should fail if create or update manifest throws", async () => {
    retrieveManifestMock.mockReturnValue({
      exists: false,
      content: null,
    });
    createManifestMock.mockImplementation(() => {
      throw new Error("fake error to test the catch");
    });

    await configureProject(
      fakeCwd,
      fakeBase,
      fakeRepository,
      fakeFrameworkStats,
      []
    );

    expect(retrieveManifestMock).toBeCalled();
    expect(createManifestMock).toBeCalled();
    expect(patchManifestMock).not.toBeCalled();

    expect(successFn).not.toHaveBeenCalled();
    expect(failFn).toHaveBeenCalled();
    expect(MockTracker).not.toHaveBeenCalled();
  });

  test("it should fail if add SM script throws", async () => {
    retrieveManifestMock.mockReturnValue({
      exists: false,
      content: null,
    });
    createManifestMock.mockReturnValue(null); // we don't care about this void.
    addJsonPackageSmScriptMock.mockImplementation(() => {
      throw new Error("fake error to test the catch");
    });

    await configureProject(
      fakeCwd,
      fakeBase,
      fakeRepository,
      fakeFrameworkStats,
      []
    );

    expect(retrieveManifestMock).toBeCalled();
    expect(createManifestMock).toBeCalled();
    expect(patchManifestMock).not.toBeCalled();

    expect(successFn).not.toHaveBeenCalled();
    expect(failFn).toHaveBeenCalled();
    expect(MockTracker).not.toHaveBeenCalled();
  });

  test("it should create a slice folder if it doesnt exists.", async () => {
    // situation where the SM.Json doesn't exists.
    retrieveManifestMock.mockReturnValue({
      exists: false,
      content: null,
    });
    addJsonPackageSmScriptMock.mockReturnValue(true);

    // only called to verify if slice folder exists.
    fileExistsMock.mockReturnValue(false);

    await configureProject(
      fakeCwd,
      fakeBase,
      fakeRepository,
      fakeFrameworkStats
    );

    expect(mkdirMock).toHaveBeenCalled();
    expect(MockTracker).toHaveBeenCalled();
  });

  test("it shouldn' create a slice folder if it exists.", async () => {
    // situation where the SM.Json doesn't exists.
    retrieveManifestMock.mockReturnValue({
      exists: false,
      content: null,
    });
    addJsonPackageSmScriptMock.mockReturnValue(true);
    // only called to verify if slice folder exists.
    fileExistsMock.mockReturnValue(true);

    await configureProject(
      fakeCwd,
      fakeBase,
      fakeRepository,
      fakeFrameworkStats
    );

    expect(mkdirMock).not.toHaveBeenCalled();
    expect(MockTracker).toHaveBeenCalled();
  });
});
Example #23
Source File: auth.test.ts    From slice-machine with Apache License 2.0 4 votes vote down vote up
describe("auth", () => {
  beforeEach(() => nock.cleanAll());

  afterEach(() => {
    jest.clearAllMocks();
  });

  const fakeBase = "https://fake.io";
  const endpoints = Endpoints.buildEndpoints(fakeBase);

  test("login should always have the same parameters", async () => {
    const fakeProfile = {
      email: "[email protected]",
      type: "USER",
      repositories: {},
    };

    jest.spyOn(fs, "lstatSync").mockReturnValue({} as fs.Stats);
    const fakeCookie = {
      base: fakeBase,
      cookies: "prismic-auth=biscuits",
    };

    jest.spyOn(fs, "readFileSync").mockReturnValue(JSON.stringify(fakeCookie)); // called more than once?

    nock("https://auth.fake.io")
      .get("/validate?token=biscuits")
      .reply(200, fakeProfile);

    const spy = jest.spyOn(authHelpers, "startServerAndOpenBrowser"); // untestable code, should be refactored
    spy.mockImplementation((url, action, base) => {
      expect(url).toEqual(endpoints.Dashboard.cliLogin);
      expect(action).toEqual("login");
      expect(base).toEqual(fakeBase);
      return Promise.resolve({ onLoginFail: () => null });
    });

    await Auth.login(fakeBase);
  });

  test("signup should always open the browser at the same url", async () => {
    const fakeProfile = {
      email: "[email protected]",
      type: "USER",
      repositories: {},
    };

    jest.spyOn(fs, "lstatSync").mockReturnValue({} as fs.Stats);
    const fakeCookie = {
      base: fakeBase,
      cookies: "prismic-auth=biscuits",
    };

    jest.spyOn(fs, "readFileSync").mockReturnValue(JSON.stringify(fakeCookie)); // called more than once?

    nock("https://auth.fake.io")
      .get("/validate?token=biscuits")
      .reply(200, fakeProfile);
    const spy = jest.spyOn(authHelpers, "startServerAndOpenBrowser");

    spy.mockImplementation((url, action, base) => {
      expect(url).toEqual(endpoints.Dashboard.cliSignup);
      expect(action).toEqual("signup");
      expect(base).toEqual(fakeBase);
      return Promise.resolve({ onLoginFail: () => null });
    });

    await Auth.signup(fakeBase);
  });

  test("isHandler should work", () => {
    const handlerData: authHelpers.HandlerData = {
      email: "fake",
      cookies: ["bla", "ta", "cla"],
    };

    const nonHandlerData = "this should not work";
    const nonHandlerData2 = {
      email: "this should not work",
    };
    const nonHandlerData3 = {
      cookies: {
        status: "this is not an array",
      },
    };
    const nonHandlerData4 = {
      email: "this should not work",
      cookies: {
        status: "this is not an array",
      },
    };
    const nonHandlerData5 = {
      email: "this should not work",
      cookies: ["2", 3, 4],
    };

    expect(authHelpers.isHandlerData(handlerData)).toBe(true);
    expect(authHelpers.isHandlerData(nonHandlerData)).toBe(false);
    expect(authHelpers.isHandlerData(nonHandlerData2)).toBe(false);
    expect(authHelpers.isHandlerData(nonHandlerData3)).toBe(false);
    expect(authHelpers.isHandlerData(nonHandlerData4)).toBe(false);
    expect(authHelpers.isHandlerData(nonHandlerData5)).toBe(false);
  });

  test("validate session should return null if there is no cookies", async () => {
    jest.spyOn(fs, "lstatSync").mockReturnValueOnce({} as fs.Stats);
    jest
      .spyOn(fs, "readFileSync")
      .mockReturnValueOnce(JSON.stringify({ base: fakeBase, cookies: "" }));

    const result = await Auth.validateSession(fakeBase);
    expect(result).toBe(null);
  });

  test("validate session should return null if there is different bases", async () => {
    jest.spyOn(fs, "lstatSync").mockReturnValueOnce({} as fs.Stats);
    const fakeCookie = {
      base: "https://prismic.io",
      cookies: "prismic-auth=biscuits",
    };
    jest
      .spyOn(fs, "readFileSync")
      .mockReturnValueOnce(JSON.stringify(fakeCookie));

    const result = await Auth.validateSession(fakeBase);
    expect(result).toBe(null);
  });

  test("validate session should return null when validate session reject the promise", async () => {
    const fakeCookie = {
      base: "https://prismic.io",
      cookies: "prismic-auth=biscuits",
    };
    jest.spyOn(fs, "lstatSync").mockReturnValueOnce({} as fs.Stats);
    jest
      .spyOn(fs, "readFileSync")
      .mockReturnValueOnce(JSON.stringify(fakeCookie));

    nock("https://auth.prismic.io").get("/validate?token=biscuits").reply(401);

    const result = await Auth.validateSession(fakeBase);
    expect(result).toBe(null);
  });

  test("validate session should work", async () => {
    const fakeCookie = {
      base: "https://prismic.io",
      cookies: "prismic-auth=biscuits",
    };

    const wanted = {
      email: "[email protected]",
      type: "USER",
      repositories: {
        "foo-repo": { dbid: "abcd", role: Roles.PUBLISHER },
        qwerty: { dbid: "efgh", role: Roles.WRITER },
      },
    };

    jest.spyOn(fs, "lstatSync").mockReturnValueOnce({} as fs.Stats);
    // readFileSync seems to be called more than once :/
    jest
      .spyOn(fs, "readFileSync")
      .mockReturnValueOnce(JSON.stringify(fakeCookie));

    nock("https://auth.prismic.io")
      .get("/validate?token=biscuits")
      .reply(200, wanted);

    const got = await Auth.validateSession(fakeCookie.base);
    expect(got).toEqual(wanted);
  });
});
Example #24
Source File: cts.spec.tsx    From slice-machine with Apache License 2.0 4 votes vote down vote up
describe("Custom Type Builder", () => {
  const fakeTracker = jest.fn().mockImplementation(() => Promise.resolve());

  beforeAll(async () => {
    const div = document.createElement("div");
    div.setAttribute("id", "__next");
    document.body.appendChild(div);

    const fakeAnalytics = jest
      .spyOn(AnalyticsBrowser, "standalone")
      .mockResolvedValue({
        track: fakeTracker,
      } as any);

    await Tracker.get().initialize("foo", "repoName");
    expect(fakeAnalytics).toHaveBeenCalled();
  });

  afterEach(() => {
    jest.clearAllMocks();
  });

  beforeEach(async () => {
    mockRouter.setCurrentUrl("/");
  });

  test("should send a tracking event when the user adds a field", async () => {
    const customTypeId = "a-page";

    singletonRouter.push({
      pathname: "cts/[ct]",
      query: { ct: customTypeId },
    });

    const App = render(<CreateCustomTypeBuilder />, {
      preloadedState: {
        environment: {
          framework: "next",
          mockConfig: { _cts: { [customTypeId]: {} } },
        },
        availableCustomTypes: {
          [customTypeId]: {
            local: {
              id: customTypeId,
              label: customTypeId,
              repeatable: true,
              status: true,
              tabs: [
                {
                  key: "Main",
                  value: [],
                },
              ],
            },
          },
        },
        selectedCustomType: {
          model: {
            id: "a-page",
            label: "a-page",
            repeatable: true,
            status: true,
            tabs: [
              {
                key: "Main",
                value: [],
              },
            ],
          },
          initialModel: {
            id: "a-page",
            label: "a-page",
            repeatable: true,
            status: true,
            tabs: [
              {
                key: "Main",
                value: [],
              },
            ],
          },
          mockConfig: {},
          initialMockConfig: {},
        },
      },
    });

    const addButton = screen.getByTestId("empty-zone-add-new-field");
    fireEvent.click(addButton);

    const uid = screen.getByText("UID");
    fireEvent.click(uid);

    const saveFieldButton = screen.getByText("Add");

    await act(async () => {
      fireEvent.click(saveFieldButton);
    });

    expect(fakeTracker).toHaveBeenCalledWith(
      "SliceMachine Custom Type Field Added",
      { id: "uid", name: "a-page", type: "UID", zone: "static" },
      { context: { groupId: { Repository: "repoName" } } }
    );
  });

  test("should send a tracking event when the user adds a slice", async () => {
    const customTypeId = "a-page";

    singletonRouter.push({
      pathname: "cts/[ct]",
      query: { ct: customTypeId },
    });

    // duplicated state for library context :/

    const environment = {
      framework: "next",
      mockConfig: { _cts: { [customTypeId]: {} } },
    };

    const libraries = [
      {
        path: "./slices",
        isLocal: true,
        name: "slices",
        meta: {
          isNodeModule: false,
          isDownloaded: false,
          isManual: true,
        },
        components: [
          {
            from: "slices",
            href: "slices",
            pathToSlice: "./slices",
            fileName: "index",
            extension: "js",
            screenshotPaths: {},
            mock: [
              {
                variation: "default",
                name: "Default",
                slice_type: "test_slice",
                items: [],
                primary: {
                  title: [
                    {
                      type: "heading1",
                      text: "Cultivate granular e-services",
                      spans: [],
                    },
                  ],
                  description: [
                    {
                      type: "paragraph",
                      text: "Anim in commodo exercitation qui. Elit cillum officia mollit dolore. Commodo voluptate sit est proident ea proident dolor esse ad.",
                      spans: [],
                    },
                  ],
                },
              },
            ],
            model: {
              id: "test_slice",
              type: "SharedSlice",
              name: "TestSlice",
              description: "TestSlice",
              variations: [
                {
                  id: "default",
                  name: "Default",
                  docURL: "...",
                  version: "sktwi1xtmkfgx8626",
                  description: "TestSlice",
                  primary: [
                    {
                      key: "title",
                      value: {
                        type: "StructuredText",
                        config: {
                          single: "heading1",
                          label: "Title",
                          placeholder: "This is where it all begins...",
                        },
                      },
                    },
                    {
                      key: "description",
                      value: {
                        type: "StructuredText",
                        config: {
                          single: "paragraph",
                          label: "Description",
                          placeholder: "A nice description of your feature",
                        },
                      },
                    },
                  ],
                  items: [],
                  imageUrl:
                    "https://images.prismic.io/slice-machine/621a5ec4-0387-4bc5-9860-2dd46cbc07cd_default_ss.png?auto=compress,format",
                },
              ],
            },
            screenshotUrls: {},
            __status: "NEW_SLICE",
          },
        ],
      },
    ];

    const App = render(
      <LibrariesProvider
        env={environment}
        libraries={libraries}
        remoteSlices={[]}
      >
        <CreateCustomTypeBuilder />
      </LibrariesProvider>,
      {
        preloadedState: {
          environment,
          availableCustomTypes: {
            [customTypeId]: {
              local: {
                id: customTypeId,
                label: customTypeId,
                repeatable: true,
                status: true,
                tabs: [
                  {
                    key: "Main",
                    value: [],
                  },
                ],
              },
            },
          },
          selectedCustomType: {
            model: {
              id: "a-page",
              label: "a-page",
              repeatable: true,
              status: true,
              tabs: [
                {
                  key: "Main",
                  value: [],
                },
              ],
            },
            initialModel: {
              id: "a-page",
              label: "a-page",
              repeatable: true,
              status: true,
              tabs: [
                {
                  key: "Main",
                  value: [],
                },
              ],
            },
            mockConfig: {},
            initialMockConfig: {},
          },
          slices: {
            libraries,
            remoteSlices: [],
          },
        },
      }
    );

    const addButton = screen.getByTestId("empty-zone-add-a-new-slice");
    await act(async () => {
      fireEvent.click(addButton);
    });

    const slicesToSelect = screen.getAllByTestId("slicezone-modal-item");

    for (const elem of slicesToSelect) {
      await act(async () => {
        fireEvent.click(elem);
      });
    }

    const saveButton = screen.getByText("Save");

    await act(async () => {
      fireEvent.click(saveButton);
    });

    expect(fakeTracker).toHaveBeenCalledWith(
      "SliceMachine Slicezone Updated",
      { customTypeId },
      { context: { groupId: { Repository: "repoName" } } }
    );
  });

  test("it should send a tracking event when the user saves a custom-type", async () => {
    const customTypeId = "a-page";

    singletonRouter.push({
      pathname: "cts/[ct]",
      query: { ct: customTypeId },
    });

    const App = render(<CreateCustomTypeBuilder />, {
      preloadedState: {
        environment: {
          framework: "next",
          mockConfig: { _cts: { [customTypeId]: {} } },
        },
        availableCustomTypes: {
          [customTypeId]: {
            local: {
              id: customTypeId,
              label: customTypeId,
              repeatable: true,
              status: true,
              tabs: [
                {
                  key: "Main",
                  value: [],
                },
              ],
            },
          },
        },
        selectedCustomType: {
          model: {
            id: "a-page",
            label: "a-page",
            repeatable: true,
            status: true,
            tabs: [
              {
                key: "Main",
                value: [],
              },
            ],
          },
          initialModel: {
            id: "a-page",
            label: "a-page",
            repeatable: true,
            status: true,
            tabs: [
              {
                key: "Main",
                value: [],
              },
            ],
          },
          mockConfig: {},
          initialMockConfig: {},
        },
      },
    });

    const addButton = screen.getByTestId("empty-zone-add-new-field");
    fireEvent.click(addButton);

    const uid = screen.getByText("UID");
    fireEvent.click(uid);

    const saveFieldButton = screen.getByText("Add");

    await act(async () => {
      fireEvent.click(saveFieldButton);
    });

    expect(fakeTracker).toHaveBeenCalledWith(
      "SliceMachine Custom Type Field Added",
      { id: "uid", name: customTypeId, type: "UID", zone: "static" },
      { context: { groupId: { Repository: "repoName" } } }
    );

    const saveCustomType = screen.getByText("Save to File System");

    await act(async () => {
      fireEvent.click(saveCustomType);
    });

    await waitFor(() => {
      expect(fakeTracker).toHaveBeenLastCalledWith(
        "SliceMachine Custom Type Saved",
        { type: "repeatable", id: customTypeId, name: customTypeId },
        { context: { groupId: { Repository: "repoName" } } }
      );
    });
  });

  test("if saving fails a it should not send the save event", async () => {
    server.use(
      rest.post("/api/custom-types/save", (_, res, ctx) => {
        return res(ctx.status(500), ctx.json({}));
      })
    );
    const customTypeId = "a-page";

    singletonRouter.push({
      pathname: "cts/[ct]",
      query: { ct: customTypeId },
    });

    const App = render(<CreateCustomTypeBuilder />, {
      preloadedState: {
        environment: {
          framework: "next",
          mockConfig: { _cts: { [customTypeId]: {} } },
        },
        availableCustomTypes: {
          [customTypeId]: {
            local: {
              id: customTypeId,
              label: customTypeId,
              repeatable: true,
              status: true,
              tabs: [
                {
                  key: "Main",
                  value: [],
                },
              ],
            },
          },
        },
        selectedCustomType: {
          model: {
            id: "a-page",
            label: "a-page",
            repeatable: true,
            status: true,
            tabs: [
              {
                key: "Main",
                value: [],
              },
            ],
          },
          initialModel: {
            id: "a-page",
            label: "a-page",
            repeatable: true,
            status: true,
            tabs: [
              {
                key: "Main",
                value: [],
              },
            ],
          },
          mockConfig: {},
          initialMockConfig: {},
        },
      },
    });

    const addButton = screen.getByTestId("empty-zone-add-new-field");
    fireEvent.click(addButton);

    const uid = screen.getByText("UID");
    fireEvent.click(uid);

    const saveFieldButton = screen.getByText("Add");

    await act(async () => {
      fireEvent.click(saveFieldButton);
    });

    expect(fakeTracker).toHaveBeenCalledWith(
      "SliceMachine Custom Type Field Added",
      { id: "uid", name: customTypeId, type: "UID", zone: "static" },
      { context: { groupId: { Repository: "repoName" } } }
    );

    const saveCustomType = screen.getByText("Save to File System");

    await act(async () => {
      fireEvent.click(saveCustomType);
    });

    await new Promise((r) => setTimeout(r, 1000));

    expect(fakeTracker).toHaveBeenCalledTimes(1);
  });

  test("when the user pushes a custom-type it should send a tracking event", async () => {
    const customTypeId = "a-page";

    server.use(
      rest.get("/api/custom-types/push", (req, res, ctx) => {
        expect(req.url.searchParams.get("id")).toEqual(customTypeId);
        return res(ctx.json({}));
      })
    );

    singletonRouter.push({
      pathname: "cts/[ct]",
      query: { ct: customTypeId },
    });

    const App = render(<CreateCustomTypeBuilder />, {
      preloadedState: {
        environment: {
          framework: "next",
          mockConfig: { _cts: { [customTypeId]: {} } },
        },
        availableCustomTypes: {
          [customTypeId]: {
            local: {
              id: customTypeId,
              label: customTypeId,
              repeatable: true,
              status: true,
              tabs: [
                {
                  key: "Main",
                  value: [],
                },
              ],
            },
          },
        },
        selectedCustomType: {
          model: {
            id: "a-page",
            label: "a-page",
            repeatable: true,
            status: true,
            tabs: [
              {
                key: "Main",
                value: [],
              },
            ],
          },
          initialModel: {
            id: "a-page",
            label: "a-page",
            repeatable: true,
            status: true,
            tabs: [
              {
                key: "Main",
                value: [],
              },
            ],
          },
          mockConfig: {},
          initialMockConfig: {},
        },
      },
    });

    const pushButton = screen.getByText("Push to Prismic");
    await act(async () => {
      fireEvent.click(pushButton);
    });

    await waitFor(() => {
      expect(fakeTracker).toHaveBeenCalledWith(
        "SliceMachine Custom Type Pushed",
        { id: customTypeId, name: customTypeId, type: "repeatable" },
        { context: { groupId: { Repository: "repoName" } } }
      );
    });
  });
});
Example #25
Source File: behavioural-subject-service.spec.ts    From leapp with Mozilla Public License 2.0 4 votes vote down vote up
describe("WorkspaceService", () => {
  let repositoryMock: Repository;
  let mockedSession1: Session;
  let mockedSession2: Session;
  let mockedSession3: Session;
  let behaviouralSubjectService: BehaviouralSubjectService;

  beforeEach(() => {
    mockedSession1 = {
      region: "eu-west-1",
      sessionId: "session-id-1",
      sessionName: "session1",
      status: SessionStatus.active,
      type: SessionType.awsSsoRole,
      expired: (): boolean => false,
    };
    mockedSession2 = {
      region: "eu-west-2",
      sessionId: "session-id-2",
      sessionName: "session2",
      status: SessionStatus.inactive,
      type: SessionType.awsSsoRole,
      expired: (): boolean => false,
    };
    mockedSession3 = {
      region: "eu-west-3",
      sessionId: "session-id-3",
      sessionName: "session3",
      status: SessionStatus.inactive,
      type: SessionType.azure,
      expired: (): boolean => false,
    };

    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore
    repositoryMock = {
      getSessions: jest.fn((): Session[] => [mockedSession1, mockedSession2, mockedSession3]),
    };

    behaviouralSubjectService = new BehaviouralSubjectService(repositoryMock);
  });

  test("Should exists when created", () => {
    expect(behaviouralSubjectService).not.toBe(undefined);
  });

  test("get sessions() - retrieve sessions as Values from Behavioural Subject", () => {
    expect(behaviouralSubjectService.sessions).toStrictEqual(repositoryMock.getSessions());
    expect(behaviouralSubjectService.sessions.length).toBe(3);
  });

  test("getSessions() - retrieve sessions as Values from Behavioural Subject", () => {
    expect(behaviouralSubjectService.getSessions()).toStrictEqual(repositoryMock.getSessions());
    expect(behaviouralSubjectService.getSessions().length).toBe(3);
  });

  test("set sessions() - set sessions as Values to Behavioural Subject", () => {
    const newSessionArray = repositoryMock.getSessions();
    newSessionArray.push({
      region: "eu-west-2",
      sessionId: "session-id-4",
      sessionName: "session4",
      status: SessionStatus.pending,
      type: SessionType.azure,
      expired: (): boolean => false,
    });
    behaviouralSubjectService.sessions = [...newSessionArray];

    expect(behaviouralSubjectService.sessions).toStrictEqual(newSessionArray);
    expect(behaviouralSubjectService.sessions.length).toBe(4);
  });

  test("setSessions() - set sessions as Values to Behavioural Subject", () => {
    const newSessionArray = repositoryMock.getSessions();
    newSessionArray.push({
      region: "eu-west-2",
      sessionId: "session-id-4",
      sessionName: "session4",
      status: SessionStatus.pending,
      type: SessionType.azure,
      expired: (): boolean => false,
    });
    behaviouralSubjectService.sessions = [...newSessionArray];

    expect(behaviouralSubjectService.getSessions()).toStrictEqual(newSessionArray);
    expect(behaviouralSubjectService.getSessions().length).toBe(4);
  });

  test("getSessionById() - retrieve a session given its id", () => {
    expect(behaviouralSubjectService.getSessionById("session-id-3")).toStrictEqual(mockedSession3);
  });
});
Example #26
Source File: aws.test.ts    From login-action with Apache License 2.0 4 votes vote down vote up
describe('getRegistriesData', () => {
  beforeEach(() => {
    jest.clearAllMocks();
    delete process.env.AWS_ACCOUNT_IDS;
  });
  // prettier-ignore
  test.each([
    [
      '012345678901.dkr.ecr.aws-region-1.amazonaws.com',
      'dkr.ecr.aws-region-1.amazonaws.com', undefined,
      [
        {
          registry: '012345678901.dkr.ecr.aws-region-1.amazonaws.com',
          username: '012345678901',
          password: 'world'
        }
      ]
    ],
    [
      '012345678901.dkr.ecr.eu-west-3.amazonaws.com',
      'dkr.ecr.eu-west-3.amazonaws.com',
      '012345678910,023456789012',
      [
        {
          registry: '012345678901.dkr.ecr.eu-west-3.amazonaws.com',
          username: '012345678901',
          password: 'world'
        },
        {
          registry: '012345678910.dkr.ecr.eu-west-3.amazonaws.com',
          username: '012345678910',
          password: 'world'
        },
        {
          registry: '023456789012.dkr.ecr.eu-west-3.amazonaws.com',
          username: '023456789012',
          password: 'world'
        }
      ]
    ],
    [
      'public.ecr.aws',
      undefined,
      undefined,
      [
        {
          registry: 'public.ecr.aws',
          username: 'AWS',
          password: 'world'
        }
      ]
    ]
  ])('given registry %p', async (registry, fqdn, accountIDsEnv, expected: aws.RegistryData[]) => {
    if (accountIDsEnv) {
      process.env.AWS_ACCOUNT_IDS = accountIDsEnv;
    }
    const accountIDs = aws.getAccountIDs(registry);
    const authData: AuthorizationData[] = [];
    if (accountIDs.length == 0) {
      mockEcrPublicGetAuthToken.mockImplementation(() => {
        return Promise.resolve({
          authorizationData: {
            authorizationToken: Buffer.from(`AWS:world`).toString('base64'),
          }
        });
      });
    } else {
      aws.getAccountIDs(registry).forEach(accountID => {
        authData.push({
          authorizationToken: Buffer.from(`${accountID}:world`).toString('base64'),
          proxyEndpoint: `${accountID}.${fqdn}`
        });
      });
      mockEcrGetAuthToken.mockImplementation(() => {
        return Promise.resolve({
          authorizationData: authData
        });
      });
    }
    const regData = await aws.getRegistriesData(registry);
    expect(regData).toEqual(expected);
  });
});
Example #27
Source File: context.test.ts    From build-push-action with Apache License 2.0 4 votes vote down vote up
describe('getArgs', () => {
  beforeEach(() => {
    process.env = Object.keys(process.env).reduce((object, key) => {
      if (!key.startsWith('INPUT_')) {
        object[key] = process.env[key];
      }
      return object;
    }, {});
  });

  // prettier-ignore
  test.each([
    [
      0,
      '0.4.1',
      new Map<string, string>([
        ['context', '.'],
        ['load', 'false'],
        ['no-cache', 'false'],
        ['push', 'false'],
        ['pull', 'false'],
      ]),
      [
        'build',
        '--iidfile', '/tmp/.docker-build-push-jest/iidfile',
        '.'
      ]
    ],
    [
      1,
      '0.4.2',
      new Map<string, string>([
        ['build-args', 'MY_ARG=val1,val2,val3\nARG=val'],
        ['load', 'false'],
        ['no-cache', 'false'],
        ['push', 'false'],
        ['pull', 'false'],
      ]),
      [
        'build',
        '--build-arg', 'MY_ARG=val1,val2,val3',
        '--build-arg', 'ARG=val',
        '--iidfile', '/tmp/.docker-build-push-jest/iidfile',
        'https://github.com/docker/build-push-action.git#refs/heads/test-jest'
      ]
    ],
    [
      2,
      '0.4.2',
      new Map<string, string>([
        ['tags', 'name/app:7.4, name/app:latest'],
        ['load', 'false'],
        ['no-cache', 'false'],
        ['push', 'false'],
        ['pull', 'false'],
      ]),
      [
        'build',
        '--iidfile', '/tmp/.docker-build-push-jest/iidfile',
        '--tag', 'name/app:7.4',
        '--tag', 'name/app:latest',
        'https://github.com/docker/build-push-action.git#refs/heads/test-jest'
      ]
    ],
    [
      3,
      '0.4.2',
      new Map<string, string>([
        ['context', '.'],
        ['labels', 'org.opencontainers.image.title=buildkit\norg.opencontainers.image.description=concurrent, cache-efficient, and Dockerfile-agnostic builder toolkit'],
        ['outputs', 'type=local,dest=./release-out'],
        ['load', 'false'],
        ['no-cache', 'false'],
        ['push', 'false'],
        ['pull', 'false'],
      ]),
      [
        'build',
        '--label', 'org.opencontainers.image.title=buildkit',
        '--label', 'org.opencontainers.image.description=concurrent, cache-efficient, and Dockerfile-agnostic builder toolkit',
        '--output', 'type=local,dest=./release-out',
        '.'
      ]
    ],
    [
      4,
      '0.4.1',
      new Map<string, string>([
        ['context', '.'],
        ['platforms', 'linux/amd64,linux/arm64'],
        ['load', 'false'],
        ['no-cache', 'false'],
        ['push', 'false'],
        ['pull', 'false'],
      ]),
      [
        'build',
        '--platform', 'linux/amd64,linux/arm64',
        '.'
      ]
    ],
    [
      5,
      '0.4.1',
      new Map<string, string>([
        ['context', '.'],
        ['load', 'false'],
        ['no-cache', 'false'],
        ['push', 'false'],
        ['pull', 'false'],
      ]),
      [
        'build',
        '--iidfile', '/tmp/.docker-build-push-jest/iidfile',
        '.'
      ]
    ],
    [
      6,
      '0.4.2',
      new Map<string, string>([
        ['context', '.'],
        ['secrets', 'GIT_AUTH_TOKEN=abcdefghijklmno=0123456789'],
        ['load', 'false'],
        ['no-cache', 'false'],
        ['push', 'false'],
        ['pull', 'false'],
      ]),
      [
        'build',
        '--iidfile', '/tmp/.docker-build-push-jest/iidfile',
        '--secret', 'id=GIT_AUTH_TOKEN,src=/tmp/.docker-build-push-jest/.tmpname-jest',
        '.'
      ]
    ],
    [
      7,
      '0.4.2',
      new Map<string, string>([
        ['github-token', 'abcdefghijklmno0123456789'],
        ['outputs', '.'],
        ['load', 'false'],
        ['no-cache', 'false'],
        ['push', 'false'],
        ['pull', 'false'],
      ]),
      [
        'build',
        '--output', '.',
        '--secret', 'id=GIT_AUTH_TOKEN,src=/tmp/.docker-build-push-jest/.tmpname-jest',
        'https://github.com/docker/build-push-action.git#refs/heads/test-jest'
      ]
    ],
    [
      8,
      '0.4.2',
      new Map<string, string>([
        ['context', 'https://github.com/docker/build-push-action.git#refs/heads/master'],
        ['tag', 'localhost:5000/name/app:latest'],
        ['platforms', 'linux/amd64,linux/arm64'],
        ['secrets', 'GIT_AUTH_TOKEN=abcdefghijklmno=0123456789'],
        ['file', './test/Dockerfile'],
        ['builder', 'builder-git-context-2'],
        ['load', 'false'],
        ['no-cache', 'false'],
        ['push', 'true'],
        ['pull', 'false'],
      ]),
      [
        'build',
        '--file', './test/Dockerfile',
        '--iidfile', '/tmp/.docker-build-push-jest/iidfile',
        '--platform', 'linux/amd64,linux/arm64',
        '--secret', 'id=GIT_AUTH_TOKEN,src=/tmp/.docker-build-push-jest/.tmpname-jest',
        '--builder', 'builder-git-context-2',
        '--push',
        'https://github.com/docker/build-push-action.git#refs/heads/master'
      ]
    ],
    [
      9,
      '0.4.2',
      new Map<string, string>([
        ['context', 'https://github.com/docker/build-push-action.git#refs/heads/master'],
        ['tag', 'localhost:5000/name/app:latest'],
        ['platforms', 'linux/amd64,linux/arm64'],
        ['secrets', `GIT_AUTH_TOKEN=abcdefghi,jklmno=0123456789
"MYSECRET=aaaaaaaa
bbbbbbb
ccccccccc"
FOO=bar
"EMPTYLINE=aaaa

bbbb
ccc"`],
        ['file', './test/Dockerfile'],
        ['builder', 'builder-git-context-2'],
        ['load', 'false'],
        ['no-cache', 'false'],
        ['push', 'true'],
        ['pull', 'false'],
      ]),
      [
        'build',
        '--file', './test/Dockerfile',
        '--iidfile', '/tmp/.docker-build-push-jest/iidfile',
        '--platform', 'linux/amd64,linux/arm64',
        '--secret', 'id=GIT_AUTH_TOKEN,src=/tmp/.docker-build-push-jest/.tmpname-jest',
        '--secret', 'id=MYSECRET,src=/tmp/.docker-build-push-jest/.tmpname-jest',
        '--secret', 'id=FOO,src=/tmp/.docker-build-push-jest/.tmpname-jest',
        '--secret', 'id=EMPTYLINE,src=/tmp/.docker-build-push-jest/.tmpname-jest',
        '--builder', 'builder-git-context-2',
        '--push',
        'https://github.com/docker/build-push-action.git#refs/heads/master'
      ]
    ],
    [
      10,
      '0.4.2',
      new Map<string, string>([
        ['context', 'https://github.com/docker/build-push-action.git#refs/heads/master'],
        ['tag', 'localhost:5000/name/app:latest'],
        ['platforms', 'linux/amd64,linux/arm64'],
        ['secrets', `GIT_AUTH_TOKEN=abcdefghi,jklmno=0123456789
MYSECRET=aaaaaaaa
bbbbbbb
ccccccccc
FOO=bar
EMPTYLINE=aaaa

bbbb
ccc`],
        ['file', './test/Dockerfile'],
        ['builder', 'builder-git-context-2'],
        ['load', 'false'],
        ['no-cache', 'false'],
        ['push', 'true'],
        ['pull', 'false'],
      ]),
      [
        'build',
        '--file', './test/Dockerfile',
        '--iidfile', '/tmp/.docker-build-push-jest/iidfile',
        '--platform', 'linux/amd64,linux/arm64',
        '--secret', 'id=GIT_AUTH_TOKEN,src=/tmp/.docker-build-push-jest/.tmpname-jest',
        '--secret', 'id=MYSECRET,src=/tmp/.docker-build-push-jest/.tmpname-jest',
        '--secret', 'id=FOO,src=/tmp/.docker-build-push-jest/.tmpname-jest',
        '--secret', 'id=EMPTYLINE,src=/tmp/.docker-build-push-jest/.tmpname-jest',
        '--builder', 'builder-git-context-2',
        '--push',
        'https://github.com/docker/build-push-action.git#refs/heads/master'
      ]
    ],
    [
      11,
      '0.5.1',
      new Map<string, string>([
        ['context', 'https://github.com/docker/build-push-action.git#refs/heads/master'],
        ['tag', 'localhost:5000/name/app:latest'],
        ['secret-files', `MY_SECRET=${path.join(__dirname, 'fixtures', 'secret.txt').split(path.sep).join(path.posix.sep)}`],
        ['file', './test/Dockerfile'],
        ['builder', 'builder-git-context-2'],
        ['network', 'host'],
        ['load', 'false'],
        ['no-cache', 'false'],
        ['push', 'true'],
        ['pull', 'false'],
      ]),
      [
        'build',
        '--file', './test/Dockerfile',
        '--iidfile', '/tmp/.docker-build-push-jest/iidfile',
        '--secret', 'id=MY_SECRET,src=/tmp/.docker-build-push-jest/.tmpname-jest',
        '--builder', 'builder-git-context-2',
        '--network', 'host',
        '--push',
        'https://github.com/docker/build-push-action.git#refs/heads/master'
      ]
    ],
    [
      12,
      '0.4.2',
      new Map<string, string>([
        ['context', '.'],
        ['labels', 'org.opencontainers.image.title=filter_results_top_n\norg.opencontainers.image.description=Reference implementation of operation "filter results (top-n)"'],
        ['outputs', 'type=local,dest=./release-out'],
        ['load', 'false'],
        ['no-cache', 'false'],
        ['push', 'false'],
        ['pull', 'false'],
      ]),
      [
        'build',
        '--label', 'org.opencontainers.image.title=filter_results_top_n',
        '--label', 'org.opencontainers.image.description=Reference implementation of operation "filter results (top-n)"',
        '--output', 'type=local,dest=./release-out',
        '.'
      ]
    ],
    [
      13,
      '0.6.0',
      new Map<string, string>([
        ['context', '.'],
        ['tag', 'localhost:5000/name/app:latest'],
        ['file', './test/Dockerfile'],
        ['add-hosts', 'docker:10.180.0.1,foo:10.0.0.1'],
        ['network', 'host'],
        ['load', 'false'],
        ['no-cache', 'false'],
        ['push', 'true'],
        ['pull', 'false'],
      ]),
      [
        'build',
        '--add-host', 'docker:10.180.0.1',
        '--add-host', 'foo:10.0.0.1',
        '--file', './test/Dockerfile',
        '--iidfile', '/tmp/.docker-build-push-jest/iidfile',
        '--metadata-file', '/tmp/.docker-build-push-jest/metadata-file',
        '--network', 'host',
        '--push',
        '.'
      ]
    ],
    [
      14,
      '0.7.0',
      new Map<string, string>([
        ['context', '.'],
        ['file', './test/Dockerfile'],
        ['add-hosts', 'docker:10.180.0.1\nfoo:10.0.0.1'],
        ['cgroup-parent', 'foo'],
        ['shm-size', '2g'],
        ['ulimit', `nofile=1024:1024
nproc=3`],
        ['load', 'false'],
        ['no-cache', 'false'],
        ['push', 'false'],
        ['pull', 'false'],
      ]),
      [
        'build',
        '--add-host', 'docker:10.180.0.1',
        '--add-host', 'foo:10.0.0.1',
        '--cgroup-parent', 'foo',
        '--file', './test/Dockerfile',
        '--iidfile', '/tmp/.docker-build-push-jest/iidfile',
        '--shm-size', '2g',
        '--ulimit', 'nofile=1024:1024',
        '--ulimit', 'nproc=3',
        '--metadata-file', '/tmp/.docker-build-push-jest/metadata-file',
        '.'
      ]
    ],
    [
      15,
      '0.7.0',
      new Map<string, string>([
        ['context', '{{defaultContext}}:docker'],
        ['load', 'false'],
        ['no-cache', 'false'],
        ['push', 'false'],
        ['pull', 'false'],
      ]),
      [
        'build',
        '--iidfile', '/tmp/.docker-build-push-jest/iidfile',
        '--metadata-file', '/tmp/.docker-build-push-jest/metadata-file',
        'https://github.com/docker/build-push-action.git#refs/heads/test-jest:docker'
      ]
    ],
  ])(
    '[%d] given %p with %p as inputs, returns %p',
    async (num: number, buildxVersion: string, inputs: Map<string, string>, expected: Array<string>) => {
      inputs.forEach((value: string, name: string) => {
        setInput(name, value);
      });
      const defContext = context.defaultContext();
      const inp = await context.getInputs(defContext);
      const res = await context.getArgs(inp, defContext, buildxVersion);
      expect(res).toEqual(expected);
    }
  );
});
Example #28
Source File: ssm-service.spec.ts    From leapp with Mozilla Public License 2.0 4 votes vote down vote up
describe("SsmService", () => {
  let ssmService: SsmService;
  let executeService: ExecuteService;
  let credentialInfo: CredentialsInfo;
  let mockedCallback: any;
  let setConfig;

  beforeEach(() => {
    credentialInfo = {
      sessionToken: {
        // eslint-disable-next-line @typescript-eslint/naming-convention
        aws_access_key_id: "123",
        // eslint-disable-next-line @typescript-eslint/naming-convention
        aws_secret_access_key: "345",
        // eslint-disable-next-line @typescript-eslint/naming-convention
        aws_session_token: "678",
      },
    };

    mockedCallback = jest.fn(() => {});
    setConfig = jest.spyOn(SsmService, "setConfig");

    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore
    executeService = {
      execute: jest.fn((_: string, _1?: boolean): Promise<string> => Promise.resolve("")),
      getQuote: jest.fn(() => ""),
      openTerminal: jest.fn((_: string, _1?: any): Promise<string> => Promise.resolve("")),
    };
    (executeService as any).nativeService = null;
    (executeService as any).repository = null;

    ssmService = new SsmService(null, executeService);
    ssmService.aws = {
      config: {
        update: jest.fn((_: any) => {}),
      },
      // eslint-disable-next-line @typescript-eslint/naming-convention
      SSM: jest.fn(() => {}),
      // eslint-disable-next-line @typescript-eslint/naming-convention
      EC2: jest.fn(() => {}),
    };
  });

  test("getSsmInstances - should retrieve a list of ssm sessions given a valid region", (done) => {
    (ssmService as any).applyEc2MetadataInformation = jest.fn((_: any): any => []);
    (ssmService as any).requestSsmInstances = jest.fn((_: any): any => []);

    ssmService.getSsmInstances(credentialInfo, "eu-west-1", mockedCallback);

    setTimeout(() => {
      expect(setConfig).toHaveBeenCalled();

      expect(ssmService.aws.config.update).toBeCalledWith({
        region: "eu-west-1",
        accessKeyId: "123",
        secretAccessKey: "345",
        sessionToken: "678",
      });

      expect(ssmService.aws.SSM).toHaveBeenCalled();
      expect(ssmService.aws.EC2).toHaveBeenCalled();

      expect(mockedCallback).toHaveBeenCalled();

      expect((ssmService as any).applyEc2MetadataInformation).toHaveBeenCalled();
      done();
    }, 100);
  });

  test("getSsmInstances - should call private method", (done) => {
    (ssmService as any).applyEc2MetadataInformation = jest.fn((_: any): any => []);
    (ssmService as any).requestSsmInstances = jest.fn((_: any): any => []);

    ssmService.getSsmInstances(credentialInfo, "eu-west-1", mockedCallback);

    setTimeout(() => {
      expect((ssmService as any).requestSsmInstances).toHaveBeenCalled();
      expect((ssmService as any).applyEc2MetadataInformation).toHaveBeenCalled();
      done();
    }, 100);
  });

  test("startSession - should start a ssm session by calling the execute service", (done) => {
    const env = {
      // eslint-disable-next-line @typescript-eslint/naming-convention
      AWS_ACCESS_KEY_ID: "123",
      // eslint-disable-next-line @typescript-eslint/naming-convention
      AWS_SECRET_ACCESS_KEY: "345",
      // eslint-disable-next-line @typescript-eslint/naming-convention
      AWS_SESSION_TOKEN: "678",
    };

    const region = "eu-west-1";
    const instanceId = "mocked-id";
    const quote = "";

    ssmService.startSession(credentialInfo, instanceId, region);

    setTimeout(() => {
      expect(executeService.getQuote).toHaveBeenCalled();
      expect(executeService.openTerminal).toHaveBeenCalledWith(
        `aws ssm start-session --region ${region} --target ${quote}${instanceId}${quote}`,
        env,
        undefined
      );
      done();
    }, 100);
  });
});
Example #29
Source File: aws-iam-role-chained-service.spec.ts    From leapp with Mozilla Public License 2.0 4 votes vote down vote up
describe("AwsIamRoleChainedService", () => {
  let sessionNotifier;
  let repository;
  let fileService;
  let awsCoreService;
  let session;
  let parentSession;
  let credentialFile;
  let generateSessionToken;
  let parentSessionServiceFactory;
  let parentSessionService;

  beforeEach(() => {
    session = {
      sessionId: "session1",
      type: SessionType.awsIamRoleChained,
      roleArn: "abcdefghijklmnopqrstuvwxyz/12345",
      region: "eu-west-1",
      profileId: "profileId",
      roleSessionName: "miao",
      parentSessionId: "sessionP",
    } as any;
    parentSession = {
      sessionId: "sessionP",
      type: SessionType.awsIamRoleFederated,
      roleArn: "federated/12345",
      region: "eu-west-1",
      profileId: "profileIdP",
    } as any;
    credentialFile = {
      profile1: {
        // eslint-disable-next-line @typescript-eslint/naming-convention
        aws_access_key_id: "",
        // eslint-disable-next-line @typescript-eslint/naming-convention
        aws_secret_access_key: "",
        // eslint-disable-next-line @typescript-eslint/naming-convention
        aws_session_token: "",
        region: session.region,
      },
    } as any;

    sessionNotifier = {
      addSession: jest.fn(() => {}),
      setSessions: jest.fn(() => {}),
    };
    repository = {
      addSession: jest.fn(() => {}),
      getSessions: jest.fn(() => [session]),
      getSessionById: jest.fn((sessionId: string) => (sessionId === session.sessionId ? session : parentSession)),
      getProfileName: jest.fn(() => "profile1"),
      updateSessions: jest.fn(() => {}),
    };
    fileService = {
      iniWriteSync: jest.fn((_: string, __: any) => {}),
      iniParseSync: jest.fn((_: string) => credentialFile),
      replaceWriteSync: jest.fn((_: string, __: any) => {}),
    };
    awsCoreService = {
      awsCredentialPath: jest.fn(() => "aws-path"),
      stsOptions: jest.fn(() => {}),
    };
    parentSessionService = {
      generateCredentials: jest.fn((_: string) => ({
        sessionToken: {
          // eslint-disable-next-line @typescript-eslint/naming-convention
          aws_session_token: "",
          // eslint-disable-next-line @typescript-eslint/naming-convention
          aws_access_key_id: "",
          // eslint-disable-next-line @typescript-eslint/naming-convention
          aws_secret_access_key: "",
        },
      })),
      generateCredentialsProxy: jest.fn((_: string) => ({
        sessionToken: {
          // eslint-disable-next-line @typescript-eslint/naming-convention
          aws_session_token: "",
          // eslint-disable-next-line @typescript-eslint/naming-convention
          aws_access_key_id: "",
          // eslint-disable-next-line @typescript-eslint/naming-convention
          aws_secret_access_key: "",
        },
      })),
    };
    parentSessionServiceFactory = {
      getSessionService: jest.fn(() => parentSessionService),
    };

    generateSessionToken = jest.fn((_: string, __: string, _2: string) => {});
  });

  test("create - add a new role chained session", async () => {
    const awsIamRoleChainedService = new AwsIamRoleChainedService(sessionNotifier, repository, awsCoreService, null, null, null);
    await awsIamRoleChainedService.create(session);

    expect(sessionNotifier.setSessions).toHaveBeenCalled();
    expect(repository.addSession).toHaveBeenCalled();
  });

  test("applyCredentials - apply a credential set by writing on the ini file", async () => {
    const credentialsInfo = {
      sessionToken: {
        // eslint-disable-next-line @typescript-eslint/naming-convention
        aws_access_key_id: "access",
        // eslint-disable-next-line @typescript-eslint/naming-convention
        aws_secret_access_key: "secret",
        // eslint-disable-next-line @typescript-eslint/naming-convention
        aws_session_token: "123456token",
      },
    } as any;

    const awsIamRoleChainedService = new AwsIamRoleChainedService(sessionNotifier, repository, awsCoreService, fileService, null, null);
    await awsIamRoleChainedService.applyCredentials(session.sessionId, credentialsInfo);

    expect(repository.getSessionById).toHaveBeenCalledWith("session1");
    expect(repository.getProfileName).toHaveBeenCalledWith("profileId");
    expect(fileService.iniWriteSync).toHaveBeenCalledWith("aws-path", {
      profile1: {
        // eslint-disable-next-line @typescript-eslint/naming-convention
        aws_access_key_id: credentialsInfo.sessionToken.aws_access_key_id,
        // eslint-disable-next-line @typescript-eslint/naming-convention
        aws_secret_access_key: credentialsInfo.sessionToken.aws_secret_access_key,
        // eslint-disable-next-line @typescript-eslint/naming-convention
        aws_session_token: credentialsInfo.sessionToken.aws_session_token,
        region: session.region,
      },
    });
  });

  test("deApplyCredentials - remove data from the credentials file", async () => {
    const awsIamRoleChainedService = new AwsIamRoleChainedService(sessionNotifier, repository, awsCoreService, fileService, null, null);
    await awsIamRoleChainedService.deApplyCredentials(session.sessionId);

    expect(repository.getSessionById).toHaveBeenCalledWith("session1");
    expect(repository.getProfileName).toHaveBeenCalledWith("profileId");
    expect(fileService.iniParseSync).toHaveBeenCalledWith("aws-path");
    expect(fileService.replaceWriteSync).toHaveBeenCalledWith("aws-path", {});
  });

  test("generateCredentials - generate a credential set", async () => {
    const awsIamRoleChainedService = new AwsIamRoleChainedService(
      sessionNotifier,
      repository,
      awsCoreService,
      fileService,
      null,
      parentSessionServiceFactory
    );
    (awsIamRoleChainedService as any).generateSessionToken = generateSessionToken;

    await awsIamRoleChainedService.generateCredentials(session.sessionId);

    expect(repository.getSessionById).toHaveBeenCalledWith("session1");
    expect(repository.getSessionById).toHaveBeenCalledWith("sessionP");

    expect(generateSessionToken).toHaveBeenCalled();
  });

  test("removeSecret - exists", () => {
    const awsIamRoleChainedService = new AwsIamRoleChainedService(sessionNotifier, repository, awsCoreService, null, null, null);
    expect(awsIamRoleChainedService.removeSecrets).not.toBe(undefined);
  });

  test("getAccountNumberFromCallerIdentity", async () => {
    const awsIamRoleChainedService = new AwsIamRoleChainedService(null, null, null, null, null, null);
    const accountNumber = await awsIamRoleChainedService.getAccountNumberFromCallerIdentity(session);

    expect(accountNumber).toBe("nopqrstuvwxy");
  });

  test("getAccountNumberFromCallerIdentity - error", async () => {
    session = {};
    const awsIamRoleChainedService = new AwsIamRoleChainedService(null, null, null, null, null, null);

    await expect(() => awsIamRoleChainedService.getAccountNumberFromCallerIdentity(session as AwsIamRoleChainedSession)).rejects.toThrow(
      new Error("AWS IAM Role Chained Session required")
    );
  });

  test("generateSessionToken - create a session token given the credential information we need", async () => {
    const awsIamRoleChainedService = new AwsIamRoleChainedService(
      sessionNotifier,
      repository,
      awsCoreService,
      fileService,
      null,
      parentSessionServiceFactory
    );
    (awsIamRoleChainedService as any).saveSessionTokenExpirationInTheSession = jest.fn();
    const stsMock = {
      assumeRole: jest.fn(() => ({
        promise: () => ({
          // eslint-disable-next-line @typescript-eslint/naming-convention
          Credentials: {
            // eslint-disable-next-line @typescript-eslint/naming-convention
            AccessKeyId: "",
            // eslint-disable-next-line @typescript-eslint/naming-convention
            SecretAccessKey: "",
            // eslint-disable-next-line @typescript-eslint/naming-convention
            SessionToken: "",
          },
        }),
      })),
    };

    await (awsIamRoleChainedService as any).generateSessionToken(session, stsMock, {});

    expect((awsIamRoleChainedService as any).saveSessionTokenExpirationInTheSession).toHaveBeenCalled();
    expect(stsMock.assumeRole).toHaveBeenCalled();
  });

  test("saveSessionTokenExpirationInTheSession - save a new token expiration in a specified session", async () => {
    const awsIamRoleChainedService = new AwsIamRoleChainedService(
      sessionNotifier,
      repository,
      awsCoreService,
      fileService,
      null,
      parentSessionServiceFactory
    );

    // eslint-disable-next-line @typescript-eslint/naming-convention
    await (awsIamRoleChainedService as any).saveSessionTokenExpirationInTheSession(session, { Expiration: new Date() });

    expect(session.sessionTokenExpiration).not.toBe(undefined);
    expect(repository.getSessions).toHaveBeenCalled();
    expect(repository.updateSessions).toHaveBeenCalledWith([session]);
    expect(sessionNotifier.setSessions).toHaveBeenCalledWith([session]);
  });
});