Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8,031 changes: 7,150 additions & 881 deletions package-lock.json

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions packages/apollo-cli/@types/fs-monkey.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
declare module "fs-monkey";
1 change: 1 addition & 0 deletions packages/apollo-cli/@types/memfs.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
declare module "memfs";
6 changes: 4 additions & 2 deletions packages/apollo-cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
"env-ci": "^2.1.0",
"git-parse": "^1.0.3",
"git-rev-sync": "^1.12.0",
"globby": "^8.0.1",
"glob": "^7.1.2",
"graphql": "^0.13.1",
"graphql-tag": "^2.9.2",
"heroku-cli-util": "^8.0.9",
Expand Down Expand Up @@ -64,7 +64,9 @@
"ts-jest": "^22.4.6",
"ts-node": "^5.0.1",
"tslib": "^1.9.0",
"typescript": "^2.8.3"
"typescript": "^2.8.3",
"memfs": "^2.9.1",
"fs-monkey": "^0.3.3"
},
"precommit": "pretty-quick --staged",
"engines": {
Expand Down
12 changes: 12 additions & 0 deletions packages/apollo-cli/src/__mocks__/localfs.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import {Volume, createFsFromVolume} from 'memfs';
Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the main part of how fs mocking works. Instead of importing fs everywhere, we import localfs which points to fs when regularly running or the in-memory volume in unit tests.

import {patchFs} from 'fs-monkey';

export const vol = Volume.fromJSON({});
export const fs = createFsFromVolume(vol);

export function withGlobalFS<T>(thunk: () => T): T {
Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This patch is needed to handle libraries like glob, which directly use fs. For those situations we wrap the library call in withGlobalFS to patch the fs library with our in-memory volume for the duration of the call.

const unpatch = patchFs(vol);
const ret = thunk();
unpatch();
return ret;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,203 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`successful codegen infers Flow target and writes types 1`] = `
"

/* @flow */
/* eslint-disable */
// This file was automatically generated and should not be edited.

// ====================================================
// GraphQL query operation: SimpleQuery
// ====================================================

export type SimpleQuery = {
hello: string
};

/* @flow */
/* eslint-disable */
// This file was automatically generated and should not be edited.

//==============================================================
// START Enums and Input Objects
//==============================================================

//==============================================================
// END Enums and Input Objects
//=============================================================="
`;

exports[`successful codegen infers JSON target and writes operations 1`] = `
"{
\\"operations\\": [
{
\\"filePath\\": \\"queryOne.graphql\\",
\\"operationName\\": \\"SimpleQuery\\",
\\"operationType\\": \\"query\\",
\\"rootType\\": \\"Query\\",
\\"variables\\": [],
\\"source\\": \\"query SimpleQuery {\\\\n hello\\\\n}\\",
\\"fields\\": [
{
\\"responseName\\": \\"hello\\",
\\"fieldName\\": \\"hello\\",
\\"type\\": \\"String!\\",
\\"isConditional\\": false,
\\"isDeprecated\\": false
}
],
\\"fragmentSpreads\\": [],
\\"inlineFragments\\": [],
\\"fragmentsReferenced\\": [],
\\"sourceWithFragments\\": \\"query SimpleQuery {\\\\n hello\\\\n}\\",
\\"operationId\\": \\"4de1e386589b0853a102a87a3f21ca25266116517e59c1e8be9442e2571f00bc\\"
}
],
\\"fragments\\": [],
\\"typesUsed\\": []
}"
`;

exports[`successful codegen infers Scala target and writes types 1`] = `
"// This file was automatically generated and should not be edited.


object SimpleQueryQuery extends com.apollographql.scalajs.GraphQLQuery {
val operationString =
\\"query SimpleQuery {\\" +
\\" hello\\" +
\\"}\\"
val operation = com.apollographql.scalajs.gql(operationString)

type Variables = Unit

case class Data(hello: String) {
}

object Data {
val possibleTypes = scala.collection.Set(\\"Query\\")
}
}"
`;

exports[`successful codegen infers Swift target and writes types 1`] = `
"// This file was automatically generated and should not be edited.

import Apollo

public final class SimpleQueryQuery: GraphQLQuery {
public let operationDefinition =
\\"query SimpleQuery {\\\\n hello\\\\n}\\"

public init() {
}

public struct Data: GraphQLSelectionSet {
public static let possibleTypes = [\\"Query\\"]

public static let selections: [GraphQLSelection] = [
GraphQLField(\\"hello\\", type: .nonNull(.scalar(String.self))),
]

public private(set) var resultMap: ResultMap

public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}

public init(hello: String) {
self.init(unsafeResultMap: [\\"__typename\\": \\"Query\\", \\"hello\\": hello])
}

public var hello: String {
get {
return resultMap[\\"hello\\"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: \\"hello\\")
}
}
}
}"
`;

exports[`successful codegen infers TypeScript target and writes types 1`] = `
"

/* tslint:disable */
// This file was automatically generated and should not be edited.

// ====================================================
// GraphQL query operation: SimpleQuery
// ====================================================

export interface SimpleQuery {
hello: string;
}

/* tslint:disable */
// This file was automatically generated and should not be edited.

//==============================================================
// START Enums and Input Objects
//==============================================================

//==============================================================
// END Enums and Input Objects
//=============================================================="
`;

exports[`successful codegen writes Flow types next to sources when no output is set 1`] = `
"

/* @flow */
/* eslint-disable */
// This file was automatically generated and should not be edited.

// ====================================================
// GraphQL query operation: SimpleQuery
// ====================================================

export type SimpleQuery = {
hello: string
};

/* @flow */
/* eslint-disable */
// This file was automatically generated and should not be edited.

//==============================================================
// START Enums and Input Objects
//==============================================================

//==============================================================
// END Enums and Input Objects
//=============================================================="
`;

exports[`successful codegen writes TypeScript types next to sources when no output is set 1`] = `
"

/* tslint:disable */
// This file was automatically generated and should not be edited.

// ====================================================
// GraphQL query operation: SimpleQuery
// ====================================================

export interface SimpleQuery {
hello: string;
}

/* tslint:disable */
// This file was automatically generated and should not be edited.

//==============================================================
// START Enums and Input Objects
//==============================================================

//==============================================================
// END Enums and Input Objects
//=============================================================="
`;
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
query SimpleQuery {
hello
}
150 changes: 150 additions & 0 deletions packages/apollo-cli/src/commands/codegen/__tests__/generate.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
jest.mock(
"apollo-codegen-core/lib/localfs",
() => {
return require("../../../__mocks__/localfs");
}
);

// this is because of herkou-cli-utils hacky mocking system on their console logger
import { stdout, mockConsole } from "heroku-cli-util";
import * as path from "path";
import * as fs from "fs";
import { test as setup } from "apollo-cli-test";
import { introspectionQuery, print, execute, buildSchema } from "graphql";
import gql from "graphql-tag";
import { fs as mockFS, vol } from "apollo-codegen-core/lib/localfs";

const test = setup.do(() => mockConsole());
const fullSchema = execute(
buildSchema(
fs.readFileSync(path.resolve(__dirname, "../../schema/__tests__/fixtures/schema.graphql"), {
encoding: "utf-8",
})
),
gql(introspectionQuery)
).data;

const simpleQuery = fs.readFileSync(path.resolve(__dirname, "./fixtures/simpleQuery.graphql"));

beforeEach(() => {
vol.reset();
})

jest.setTimeout(15000);
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

was this timeout increase due to the new fs mocks?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The tests were failing randomly, so I did this to make Travis more consistent.


describe("successful codegen", () => {
test
.stdout()
.do(() => {
vol.fromJSON({
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

okay this is killer

"schema.json": JSON.stringify(fullSchema.__schema),
"queryOne.graphql": simpleQuery.toString()
});
})
.command(["codegen:generate", "--schema=schema.json", "API.swift"])
.it("infers Swift target and writes types", () => {
expect(mockFS.readFileSync("API.swift").toString()).toMatchSnapshot();
});

test
.stdout()
.do(() => {
vol.fromJSON({
"schema.json": JSON.stringify(fullSchema.__schema),
"queryOne.graphql": simpleQuery.toString()
});
})
.command(["codegen:generate", "--schema=schema.json", "API.scala"])
.it("infers Scala target and writes types", () => {
expect(mockFS.readFileSync("API.scala").toString()).toMatchSnapshot();
});

test
.stdout()
.do(() => {
vol.fromJSON({
"schema.json": JSON.stringify(fullSchema.__schema),
"queryOne.graphql": simpleQuery.toString()
});
})
.command(["codegen:generate", "--schema=schema.json", "API.ts"])
.it("infers TypeScript target and writes types", () => {
expect(mockFS.readFileSync("API.ts").toString()).toMatchSnapshot();
});

test
.stdout()
.do(() => {
vol.fromJSON({
"schema.json": JSON.stringify(fullSchema.__schema),
"queryOne.graphql": simpleQuery.toString()
});
})
.command(["codegen:generate", "--schema=schema.json", "API.js"])
.it("infers Flow target and writes types", () => {
expect(mockFS.readFileSync("API.js").toString()).toMatchSnapshot();
});

test
.stdout()
.do(() => {
vol.fromJSON({
"schema.json": JSON.stringify(fullSchema.__schema),
"queryOne.graphql": simpleQuery.toString()
});
})
.command(["codegen:generate", "--schema=schema.json", "operations.json"])
.it("infers JSON target and writes operations", () => {
expect(mockFS.readFileSync("operations.json").toString()).toMatchSnapshot();
});

test
.stdout()
.do(() => {
vol.fromJSON({
"schema.json": JSON.stringify(fullSchema.__schema),
"directory/component.tsx": `
gql\`
query SimpleQuery {
hello
}
\`;
`
});
})
.command(["codegen:generate", "--schema=schema.json", "--queries=**/*.tsx", "--target=typescript"])
.it("writes TypeScript types next to sources when no output is set", () => {
expect(mockFS.readFileSync("directory/SimpleQuery.ts").toString()).toMatchSnapshot();
});

test
.stdout()
.do(() => {
vol.fromJSON({
"schema.json": JSON.stringify(fullSchema.__schema),
"directory/component.jsx": `
gql\`
query SimpleQuery {
hello
}
\`;
`
});
})
.command(["codegen:generate", "--schema=schema.json", "--queries=**/*.jsx", "--target=flow"])
.it("writes Flow types next to sources when no output is set", () => {
expect(mockFS.readFileSync("directory/SimpleQuery.js").toString()).toMatchSnapshot();
});
});

describe("error handling", () => {
test
.command(["codegen:generate", "--target=foobar"])
.catch(err => expect(err.message).toMatch(/Unsupported target: foobar/))
.it("errors with an unsupported target");

test
.command(["codegen:generate", "--target=swift"])
.catch(err => expect(err.message).toMatch(/The output path must be specified/))
.it("errors when no output file is provided");
});
Loading