Revamping to matrix style

This commit is contained in:
2026-02-16 16:37:35 -05:00
parent 71852ec99a
commit 9d0e3938e4
14958 changed files with 2089572 additions and 114 deletions

View File

@@ -0,0 +1 @@
export {};

View File

@@ -0,0 +1,60 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/*---------------------------------------------------------------------------------------------
* Copyright (c) Red Hat. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
const arrUtils_1 = require("../src/languageservice/utils/arrUtils");
const assert = require("assert");
describe('Array Utils Tests', () => {
describe('Server - Array Utils', function () {
describe('getLineOffsets', function () {
it('No offset', () => {
const offsets = (0, arrUtils_1.getLineOffsets)('');
assert.equal(offsets.length, 0);
});
it('One offset', () => {
const offsets = (0, arrUtils_1.getLineOffsets)('test_offset');
assert.equal(offsets.length, 1);
assert.equal(offsets[0], 0);
});
it('One offset with \\r\\n', () => {
const offsets = (0, arrUtils_1.getLineOffsets)('first_offset\r\n');
assert.equal(offsets.length, 2);
assert.equal(offsets[0], 0);
});
it('Multiple offsets', () => {
const offsets = (0, arrUtils_1.getLineOffsets)('first_offset\n second_offset\n third_offset');
assert.equal(offsets.length, 3);
assert.equal(offsets[0], 0);
assert.equal(offsets[1], 13);
assert.equal(offsets[2], 29);
});
});
describe('removeDuplicatesObj', function () {
it('Remove one duplicate with property', () => {
const obj1 = {
test_key: 'test_value',
};
const obj2 = {
test_key: 'test_value',
};
const arr = [obj1, obj2];
const result = (0, arrUtils_1.removeDuplicatesObj)(arr);
assert.equal(result.length, 1);
});
it('Does not remove anything unneccessary', () => {
const obj1 = {
test_key: 'test_value',
};
const obj2 = {
other_key: 'test_value',
};
const arr = [obj1, obj2];
const result = (0, arrUtils_1.removeDuplicatesObj)(arr);
assert.equal(result.length, 2);
});
});
});
});
//# sourceMappingURL=arrUtils.test.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"arrUtils.test.js","sourceRoot":"","sources":["../../../test/arrUtils.test.ts"],"names":[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AK,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;gBAC7B,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;YAC/B,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;QAEH,QAAQ,CAAC,qBAAqB,EAAE;YAC9B,EAAE,CAAC,oCAAoC,EAAE,GAAG,EAAE;gBAC5C,MAAM,IAAI,GAAG;oBACX,QAAQ,EAAE,YAAY;iBACvB,CAAC;gBAEF,MAAM,IAAI,GAAG;oBACX,QAAQ,EAAE,YAAY;iBACvB,CAAC;gBAEF,MAAM,GAAG,GAAG,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;gBACzB,MAAM,MAAM,GAAG,IAAA,8BAAmB,EAAC,GAAG,CAAC,CAAC;gBACxC,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;YACjC,CAAC,CAAC,CAAC;YAEH,EAAE,CAAC,uCAAuC,EAAE,GAAG,EAAE;gBAC/C,MAAM,IAAI,GAAG;oBACX,QAAQ,EAAE,YAAY;iBACvB,CAAC;gBAEF,MAAM,IAAI,GAAG;oBACX,SAAS,EAAE,YAAY;iBACxB,CAAC;gBAEF,MAAM,GAAG,GAAG,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;gBAEzB,MAAM,MAAM,GAAG,IAAA,8BAAmB,EAAC,GAAG,CAAC,CAAC;gBACxC,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;YACjC,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"}

View File

@@ -0,0 +1 @@
export {};

View File

@@ -0,0 +1,79 @@
"use strict";
/*---------------------------------------------------------------------------------------------
* Copyright (c) Red Hat. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
const chai = require("chai");
const yaml_1 = require("yaml");
const yaml_documents_1 = require("../src/languageservice/parser/yaml-documents");
const astUtils_1 = require("../src/languageservice/utils/astUtils");
const textBuffer_1 = require("../src/languageservice/utils/textBuffer");
const testHelper_1 = require("./utils/testHelper");
const expect = chai.expect;
describe('AST Utils Tests', () => {
let documents;
beforeEach(() => {
documents = new yaml_documents_1.YamlDocuments();
});
describe('Get Parent Node', () => {
it('get key parent', () => {
const doc = (0, testHelper_1.setupTextDocument)('foo: bar');
const yamlDoc = documents.getYamlDocument(doc);
const [node] = yamlDoc.documents[0].getNodeFromPosition(2, new textBuffer_1.TextBuffer(doc));
const result = (0, astUtils_1.getParent)(yamlDoc.documents[0].internalDocument, node);
expect(result).is.not.undefined;
expect((0, yaml_1.isPair)(result)).is.true;
expect(result.key).property('value', 'foo');
});
it('get value parent', () => {
const doc = (0, testHelper_1.setupTextDocument)('foo: bar');
const yamlDoc = documents.getYamlDocument(doc);
const [node] = yamlDoc.documents[0].getNodeFromPosition(6, new textBuffer_1.TextBuffer(doc));
const result = (0, astUtils_1.getParent)(yamlDoc.documents[0].internalDocument, node);
expect(result).is.not.undefined;
expect((0, yaml_1.isPair)(result)).is.true;
expect(result.value).property('value', 'bar');
});
it('get root map parent', () => {
const doc = (0, testHelper_1.setupTextDocument)('foo: bar');
const yamlDoc = documents.getYamlDocument(doc);
const [node] = yamlDoc.documents[0].getNodeFromPosition(4, new textBuffer_1.TextBuffer(doc));
const result = (0, astUtils_1.getParent)(yamlDoc.documents[0].internalDocument, node);
expect(result).is.undefined;
});
it('get array parent', () => {
const doc = (0, testHelper_1.setupTextDocument)('foo:\n - bar');
const yamlDoc = documents.getYamlDocument(doc);
const [node] = yamlDoc.documents[0].getNodeFromPosition(10, new textBuffer_1.TextBuffer(doc));
const result = (0, astUtils_1.getParent)(yamlDoc.documents[0].internalDocument, node);
expect(result).is.not.undefined;
expect((0, yaml_1.isSeq)(result)).is.true;
expect(result.items[0]).property('value', 'bar');
});
it('get pair parent', () => {
const doc = (0, testHelper_1.setupTextDocument)('foo:\n - bar');
const yamlDoc = documents.getYamlDocument(doc);
const [node] = yamlDoc.documents[0].getNodeFromPosition(7, new textBuffer_1.TextBuffer(doc));
const result = (0, astUtils_1.getParent)(yamlDoc.documents[0].internalDocument, node);
expect(result).is.not.undefined;
expect((0, yaml_1.isPair)(result)).is.true;
expect(result.key).property('value', 'foo');
});
});
describe('Is Offset in comment', () => {
it('should detect that offset in comment', () => {
const doc = (0, testHelper_1.setupTextDocument)('#some comment\nfoo: bar');
const yamlDoc = documents.getYamlDocument(doc);
const result = (0, astUtils_1.isInComment)(yamlDoc.tokens, 4);
expect(result).to.be.true;
});
it('should detect that comment inside object', () => {
const doc = (0, testHelper_1.setupTextDocument)('obj:\n#some comment\n foo: bar');
const yamlDoc = documents.getYamlDocument(doc);
const result = (0, astUtils_1.isInComment)(yamlDoc.tokens, 12);
expect(result).to.be.true;
});
});
});
//# sourceMappingURL=astUtils.test.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"astUtils.test.js","sourceRoot":"","sources":["../../../test/astUtils.test.ts"],"names":[],"mappings":";AAAA;;;gGAGgG;;AAEhG,6BAA6B;AAC7B,+BAAoD;AACpD,iFAA6E;AAC7E,oEAA+E;AAC/E,wEAAqE;AACrE,mDAAuD;AACvD,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC;AAE3B,QAAQ,CAAC,iBAAiB,EAAE,GAAG,EAAE;IAC/B,IAAI,SAAwB,CAAC;IAC7B,UAAU,CAAC,GAAG,EAAE;QACd,SAAS,GAAG,IAAI,8BAAa,EAAE,CAAC;IAClC,CAAC,CAAC,CAAC;IACH,QAAQ,CAAC,iBAAiB,EAAE,GAAG,EAAE;QAC/B,EAAE,CAAC,gBAAgB,EAAE,GAAG,EAAE;YACxB,MAAM,GAAG,GAAG,IAAA,8BAAiB,EAAC,UAAU,CAAC,CAAC;YAC1C,MAAM,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AAC;QAC5B,CAAC,CAAC,CAAC;QAEH,EAAE,CAAC,0CAA0C,EAAE,GAAG,EAAE;YAClD,MAAM,GAAG,GAAG,IAAA,8BAAiB,EAAC,iCAAiC,CAAC,CAAC;YACjE,MAAM,OAAO,GAAG,SAAS,CAAC,eAAe,CAAC,GAAG,CAAC,CAAC;YAC/C,MAAM,MAAM,GAAG,IAAA,sBAAW,EAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;YAC/C,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,IAAI,CAAC;QAC5B,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"}

View File

@@ -0,0 +1 @@
export {};

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
export {};

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
export {};

View File

@@ -0,0 +1,89 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/*---------------------------------------------------------------------------------------------
* Copyright (c) Red Hat. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
const testHelper_1 = require("./utils/testHelper");
const serviceSetup_1 = require("./utils/serviceSetup");
const vscode_languageserver_1 = require("vscode-languageserver");
const chai_1 = require("chai");
const yamlSettings_1 = require("../src/yamlSettings");
const yamlCodeActions_1 = require("../src/languageservice/services/yamlCodeActions");
describe('Schema Errors Code Action Tests', () => {
let languageSettingsSetup;
let validationHandler;
let yamlSettings;
let schemaProvider;
before(() => {
languageSettingsSetup = new serviceSetup_1.ServiceSetup().withValidate();
const { validationHandler: valHandler, yamlSettings: settings, schemaProvider: testSchemaProvider, } = (0, testHelper_1.setupLanguageService)(languageSettingsSetup.languageSettings);
validationHandler = valHandler;
yamlSettings = settings;
schemaProvider = testSchemaProvider;
});
function parseSetup(content, customSchemaID) {
const testTextDocument = (0, testHelper_1.setupSchemaIDTextDocument)(content, customSchemaID);
yamlSettings.documents = new yamlSettings_1.TextDocumentTestManager();
yamlSettings.documents.set(testTextDocument);
return testTextDocument;
}
afterEach(() => {
schemaProvider.deleteSchema(testHelper_1.SCHEMA_ID);
});
describe('Convert value code action tests', () => {
it('Should provide convert to boolean action for false', async () => {
schemaProvider.addSchema(testHelper_1.SCHEMA_ID, {
type: 'object',
properties: {
analytics: {
type: 'boolean',
},
},
});
const content = 'analytics: "false"';
const doc = parseSetup(content);
const diagnostics = await validationHandler.validateTextDocument(doc);
const params = {
context: vscode_languageserver_1.CodeActionContext.create(diagnostics),
range: undefined,
textDocument: vscode_languageserver_1.TextDocumentIdentifier.create(testHelper_1.TEST_URI),
};
const actions = new yamlCodeActions_1.YamlCodeActions({});
const result = actions.getCodeAction(doc, params);
(0, chai_1.expect)(result.length).to.be.equal(1);
(0, chai_1.expect)(result[0].title).to.be.equal('Convert to boolean');
(0, chai_1.expect)(result[0].edit.changes[doc.uri]).to.exist;
const edit = result[0].edit.changes[doc.uri];
(0, chai_1.expect)(edit.length).to.be.equal(1);
(0, chai_1.expect)(edit[0]).deep.equal(vscode_languageserver_1.TextEdit.replace(vscode_languageserver_1.Range.create(0, 11, 0, 18), 'false'));
});
it('Should provide convert to boolean action for true', async () => {
schemaProvider.addSchema(testHelper_1.SCHEMA_ID, {
type: 'object',
properties: {
analytics: {
type: 'boolean',
},
},
});
const content = "analytics: 'true'";
const doc = parseSetup(content);
const diagnostics = await validationHandler.validateTextDocument(doc);
const params = {
context: vscode_languageserver_1.CodeActionContext.create(diagnostics),
range: undefined,
textDocument: vscode_languageserver_1.TextDocumentIdentifier.create(testHelper_1.TEST_URI),
};
const actions = new yamlCodeActions_1.YamlCodeActions({});
const result = actions.getCodeAction(doc, params);
(0, chai_1.expect)(result.length).to.be.equal(1);
(0, chai_1.expect)(result[0].title).to.be.equal('Convert to boolean');
(0, chai_1.expect)(result[0].edit.changes[doc.uri]).to.exist;
const edit = result[0].edit.changes[doc.uri];
(0, chai_1.expect)(edit.length).to.be.equal(1);
(0, chai_1.expect)(edit[0]).deep.equal(vscode_languageserver_1.TextEdit.replace(vscode_languageserver_1.Range.create(0, 11, 0, 17), 'true'));
});
});
});
//# sourceMappingURL=code-action-schema.test.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"code-action-schema.test.js","sourceRoot":"","sources":["../../../test/code-action-schema.test.ts"],"names":[],"mappings":";;AAAA;;;gGAGgG;AAChG,mDAM4B;AAC5B,uDAAoD;AACpD,iEAAqH;AACrH,+BAA8B;AAC9B,sDAA6E;AAE7E,qFAAkF;AAGlF,QAAQ,CAAC,iCAAiC,EAAE,GAAG,EAAE;IAC/C,IAAI,qBAAmC,CAAC;IACxC,IAAI,iBAAoC,CAAC;IACzC,IAAI,YAA2B,CAAC;IAChC,IAAI,cAAwC,CAAC;IAE7C,MAAM,CAAC,GAAG,EAAE;QACV,qBAAqB,GAAG,IAAI,2BAAY,EAAE,CAAC,YAAY,EAAE,CAAC;QAC1D,MAAM,EACJ,iBAAiB,EAAE,UAAU,EAC7B,YAAY,EAAE,QAAQ,EACtB,cAAc,EAAE,kBAAkB,GACnC,GAAG,IAAA,iCAAoB,EAAC,qBAAqB,CAAC,gBAAgB,CAAC,CAAC;QACjE,iBAAiB,GAAG,UAAU,CAAC;QAC/B,YAAY,GAAG,QAAQ,CAAC;QACxB,cAAc,GAAG,kBAAkB,CAAC;IACtC,CAAC,CAAC,CAAC;IAEH,SAAS,UAAU,CAAC,OAAe,EAAE,cAAuB;QAC1D,MAAM,gBAAgB,GAAG,IAAA,sCAAyB,EAAC,OAAO,EAAE,cAAc,CAAC,CAAC;QAC5E,YAAY,CAAC,SAAS,GAAG,IAAI,sCAAuB,EAAE,CAAC;QACtD,YAAY,CAAC,SAAqC,CAAC,GAAG,CAAC,gBAAgB,CAAC,CAAC;QAC1E,OAAO,gBAAgB,CAAC;IAC1B,CAAC;IAED,SAAS,CAAC,GAAG,EAAE;QACb,cAAc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AAM,EAAC,MAAM,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,KAAK,CAAC,oBAAoB,CAAC,CAAC;YAC1D,IAAA,aAAM,EAAC,MAAM,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC;YACjD,MAAM,IAAI,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;YAC7C,IAAA,aAAM,EAAC,IAAI,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;YACnC,IAAA,aAAM,EAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,gCAAQ,CAAC,OAAO,CAAC,6BAAK,CAAC,MAAM,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;QACnF,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"}

View File

@@ -0,0 +1 @@
export {};

View File

@@ -0,0 +1,88 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/*---------------------------------------------------------------------------------------------
* Copyright (c) Red Hat. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
const testHelper_1 = require("./utils/testHelper");
const serviceSetup_1 = require("./utils/serviceSetup");
const verifyError_1 = require("./utils/verifyError");
const assert = require("assert");
// Defines a Mocha test describe to group tests of similar kind together
describe('Custom Tag tests Tests', () => {
let languageSettingsSetup;
let languageService;
let validationHandler;
before(() => {
languageSettingsSetup = new serviceSetup_1.ServiceSetup().withValidate();
const { languageService: langService, validationHandler: valHandler } = (0, testHelper_1.setupLanguageService)(languageSettingsSetup.languageSettings);
validationHandler = valHandler;
languageService = langService;
});
function parseSetup(content, customTags) {
const testTextDocument = (0, testHelper_1.setupTextDocument)(content);
languageSettingsSetup.languageSettings.customTags = customTags;
languageService.configure(languageSettingsSetup.languageSettings);
return validationHandler.validateTextDocument(testTextDocument);
}
describe('Test that validation does not throw errors', function () {
it('Custom Tags without type not specified', (done) => {
const content = 'scalar_test: !Test test_example';
const validator = parseSetup(content, ['!Test']);
validator
.then(function (result) {
assert.equal(result.length, 0);
})
.then(done, done);
});
it('Custom Tags with one type', (done) => {
const content = 'resolvers: !Ref\n - test';
const validator = parseSetup(content, ['!Ref sequence']);
validator
.then(function (result) {
assert.equal(result.length, 0);
})
.then(done, done);
});
it('Custom Tags with multiple types', (done) => {
const content = 'resolvers: !Ref\n - test';
const validator = parseSetup(content, ['!Ref sequence', '!Ref mapping', '!Ref scalar']);
validator
.then(function (result) {
assert.equal(result.length, 0);
})
.then(done, done);
});
it('Allow multiple different custom tag types with different use', (done) => {
const content = '!test\nhello: !test\n world';
const validator = parseSetup(content, ['!test scalar', '!test mapping']);
validator
.then(function (result) {
assert.equal(result.length, 0);
})
.then(done, done);
});
it('Allow multiple different custom tag types with multiple different uses', (done) => {
const content = '!test\nhello: !test\n world\nsequence: !ref\n - item1';
const validator = parseSetup(content, ['!test scalar', '!test mapping', '!ref sequence', '!ref mapping']);
validator
.then(function (result) {
assert.equal(result.length, 0);
})
.then(done, done);
});
});
describe('Test that validation does throw errors', function () {
it('Error when custom tag is not available', (done) => {
const content = '!test';
const validator = parseSetup(content, []);
validator
.then(function (result) {
assert.equal(result.length, 1);
assert.deepEqual(result[0], (0, verifyError_1.createExpectedError)('Unresolved tag: !test', 0, 0, 0, 5));
})
.then(done, done);
});
});
});
//# sourceMappingURL=customTags.test.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"customTags.test.js","sourceRoot":"","sources":["../../../test/customTags.test.ts"],"names":[],"mappings":";;AAAA;;;gGAGgG;AAChG,mDAA6E;AAC7E,uD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G,yDAAyD,CAAC;YAC1E,MAAM,SAAS,GAAG,UAAU,CAAC,OAAO,EAAE,CAAC,cAAc,EAAE,eAAe,EAAE,eAAe,EAAE,cAAc,CAAC,CAAC,CAAC;YAC1G,SAAS;iBACN,IAAI,CAAC,UAAU,MAAM;gBACpB,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;YACjC,CAAC,CAAC;iBACD,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;QACtB,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;IAEH,QAAQ,CAAC,wCAAwC,EAAE;QACjD,EAAE,CAAC,wCAAwC,EAAE,CAAC,IAAI,EAAE,EAAE;YACpD,MAAM,OAAO,GAAG,OAAO,CAAC;YACxB,MAAM,SAAS,GAAG,UAAU,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;YAC1C,SAAS;iBACN,IAAI,CAAC,UAAU,MAAM;gBACpB,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;gBAC/B,MAAM,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,IAAA,iCAAmB,EAAC,uBAAuB,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;YACxF,CAAC,CAAC;iBACD,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;QACtB,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"}

View File

@@ -0,0 +1 @@
export {};

View File

@@ -0,0 +1,384 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/*---------------------------------------------------------------------------------------------
* Copyright (c) Red Hat. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
const testHelper_1 = require("./utils/testHelper");
const assert = require("assert");
const path = require("path");
const serviceSetup_1 = require("./utils/serviceSetup");
const yamlSettings_1 = require("../src/yamlSettings");
const chai_1 = require("chai");
describe('Default Snippet Tests', () => {
let languageHandler;
let yamlSettings;
before(() => {
const uri = (0, testHelper_1.toFsPath)(path.join(__dirname, './fixtures/defaultSnippets.json'));
const fileMatch = ['*.yml', '*.yaml'];
const languageSettingsSetup = new serviceSetup_1.ServiceSetup().withCompletion().withSchemaFileMatch({
fileMatch,
uri,
});
const { languageHandler: langHandler, yamlSettings: settings } = (0, testHelper_1.setupLanguageService)(languageSettingsSetup.languageSettings);
languageHandler = langHandler;
yamlSettings = settings;
});
describe('Snippet Tests', function () {
/**
* Generates a completion list for the given document and caret (cursor) position.
* @param content The content of the document.
* @param position The position of the caret in the document.
* Alternatively, `position` can be omitted if the caret is located in the content using `|` bookends.
* For example, `content = 'ab|c|d'` places the caret over the `'c'`, at `position = 2`
* @returns A list of valid completions.
*/
function parseSetup(content, position) {
if (typeof position === 'undefined') {
({ content, position } = (0, testHelper_1.caretPosition)(content));
}
const testTextDocument = (0, testHelper_1.setupSchemaIDTextDocument)(content);
yamlSettings.documents = new yamlSettings_1.TextDocumentTestManager();
yamlSettings.documents.set(testTextDocument);
return languageHandler.completionHandler({
position: testTextDocument.positionAt(position),
textDocument: testTextDocument,
});
}
it('Snippet in array schema should autocomplete with -', (done) => {
const content = 'array:\n - '; // len: 11
const completion = parseSetup(content, 11);
completion
.then(function (result) {
assert.equal(result.items.length, 1);
assert.equal(result.items[0].insertText, 'item1: $1\n item2: $2');
assert.equal(result.items[0].label, 'My array item');
})
.then(done, done);
});
it('Snippet in array schema should autocomplete with - if none is present', (done) => {
const content = 'array:\n '; // len: 9
const completion = parseSetup(content, 9);
completion
.then(function (result) {
assert.equal(result.items.length, 1);
assert.equal(result.items[0].insertText, '- item1: $1\n item2: $2');
assert.equal(result.items[0].label, 'My array item');
})
.then(done, done);
});
it('Snippet in array schema should autocomplete on same line as array', (done) => {
const content = 'array: | |'; // len: 8, pos: 7
const completion = parseSetup(content);
completion
.then(function (result) {
assert.equal(result.items.length, 1);
assert.equal(result.items[0].insertText, '\n - item1: $1\n item2: $2');
assert.equal(result.items[0].label, 'My array item');
})
.then(done, done);
});
it('Snippet in array schema should autocomplete correctly on array level ', (done) => {
const content = 'array:\n - item1: asd\n item2: asd\n ';
const completion = parseSetup(content, content.length);
completion
.then(function (result) {
assert.equal(result.items.length, 1);
assert.equal(result.items[0].insertText, '- item1: $1\n item2: $2');
assert.equal(result.items[0].label, 'My array item');
})
.then(done, done);
});
it('Snippet in array schema should suggest nothing inside array item if YAML already contains all props', (done) => {
const content = 'array:\n - item1: asd\n item2: asd\n ';
const completion = parseSetup(content, content.length);
completion
.then(function (result) {
assert.equal(result.items.length, 0);
})
.then(done, done);
});
it('Snippet in array schema should suggest only some of the props inside an array item if YAML already contains some of the props', (done) => {
const content = 'array:\n - item1: asd\n ';
const completion = parseSetup(content, content.length);
completion
.then(function (result) {
assert.equal(result.items.length, 1);
assert.equal(result.items[0].insertText, 'item2: $2');
assert.equal(result.items[0].label, 'My array item');
})
.then(done, done);
});
it('Snippet in anyOf array schema should autocomplete correctly with "-" symbol', (done) => {
const content = 'anyOf_arrayObj:\n ';
const completion = parseSetup(content, content.length);
completion
.then(function (result) {
assert.equal(result.items.length, 1);
assert.equal(result.items[0].insertText, '- key: ');
})
.then(done, done);
});
it('Snippet custom suggestionKind', (done) => {
const content = 'anyOf_arrayObj:\n ';
const completion = parseSetup(content, content.length);
completion
.then(function (result) {
assert.strictEqual(result.items.length, 1);
assert.strictEqual(result.items[0].kind, 9);
})
.then(done, done);
});
it('Snippet custom sort', (done) => {
const content = 'arrayNestedObjectSnippet:\n ';
const completion = parseSetup(content, content.length);
completion
.then(function (result) {
assert.strictEqual(result.items.length, 1);
assert.strictEqual(result.items[0].sortText, 'custom');
})
.then(done, done);
});
it('Snippet in object schema should autocomplete on next line ', (done) => {
const content = 'object:\n '; // len: 10
const completion = parseSetup(content, 11);
completion
.then(function (result) {
assert.equal(result.items.length, 2);
assert.equal(result.items[0].insertText, 'key1: $1\nkey2: $2');
assert.equal(result.items[0].label, 'Object item');
assert.equal(result.items[1].insertText, 'key:\n ');
assert.equal(result.items[1].label, 'key');
})
.then(done, done);
});
it('Snippet in object schema should autocomplete on next line with depth', (done) => {
const content = 'object:\n key:\n '; // len: 19
const completion = parseSetup(content, 20);
completion
.then(function (result) {
assert.notEqual(result.items.length, 0);
assert.equal(result.items[0].insertText, 'key1: $1\nkey2: $2');
assert.equal(result.items[0].label, 'Object item');
assert.equal(result.items[1].insertText, 'key:\n ');
assert.equal(result.items[1].label, 'key');
})
.then(done, done);
});
it('Snippet in object schema should suggest some of the snippet props because some of them are already in the YAML', (done) => {
const content = 'object:\n key:\n key2: value\n ';
const completion = parseSetup(content, content.length);
completion
.then(function (result) {
assert.notEqual(result.items.length, 0);
assert.equal(result.items[0].insertText, 'key1: ');
assert.equal(result.items[0].label, 'Object item');
assert.equal(result.items[1].insertText, 'key:\n ');
assert.equal(result.items[1].label, 'key');
})
.then(done, done);
});
it('Snippet in object schema should not suggest snippet props because all of them are already in the YAML', (done) => {
const content = 'object:\n key:\n key1: value\n key2: value\n ';
const completion = parseSetup(content, content.length);
completion
.then(function (result) {
assert.equal(result.items.length, 1);
assert.equal(result.items[0].insertText, 'key:\n ');
assert.equal(result.items[0].label, 'key');
})
.then(done, done);
});
it('Snippet in object schema should autocomplete on same line', (done) => {
const content = 'object: '; // len: 9
const completion = parseSetup(content, 8);
completion
.then(function (result) {
assert.equal(result.items.length, 1);
})
.then(done, done);
});
it('Snippet in object schema should not autocomplete on children', (done) => {
const content = 'object_any:\n someProp: ';
const completion = parseSetup(content, content.length);
completion
.then(function (result) {
assert.equal(result.items.length, 0);
})
.then(done, done);
});
it('Snippet in string schema should autocomplete on same line', (done) => {
const content = 'string: | |'; // len: 9, pos: 8
const completion = parseSetup(content);
completion
.then(function (result) {
assert.notEqual(result.items.length, 0);
assert.equal(result.items[0].insertText, 'test ');
assert.equal(result.items[0].label, 'My string item');
})
.then(done, done);
});
it('Snippet in boolean schema should autocomplete on same line', (done) => {
const content = 'boolean: | |'; // len: 10, pos: 9
const completion = parseSetup(content);
completion
.then(function (result) {
assert.notEqual(result.items.length, 0);
assert.equal(result.items[0].label, 'My boolean item');
assert.equal(result.items[0].insertText, 'false');
})
.then(done, done);
});
it('Snippet in longSnipet schema should autocomplete on same line', (done) => {
const content = 'longSnippet: | |'; // len: 14, pos: 13
const completion = parseSetup(content);
completion
.then(function (result) {
assert.equal(result.items.length, 1);
assert.equal(result.items[0].label, 'apply-manifests');
// eslint-disable-next-line
assert.equal(result.items[0].insertText, '\n name: $1\n taskRef:\n name: apply-manifests\n resources:\n inputs:\n - name: source\n resource: $3\n params:\n - name: manifest_dir\n value: $2');
})
.then(done, done);
});
it('Snippet in short snippet schema should autocomplete on same line', (done) => {
const content = 'lon| | '; // len: 5, pos: 3
const completion = parseSetup(content);
completion
.then(function (result) {
assert.equal(result.items.length, 15); // This is just checking the total number of snippets in the defaultSnippets.json
assert.equal(result.items[4].label, 'longSnippet');
// eslint-disable-next-line
assert.equal(result.items[4].insertText, 'longSnippet:\n name: $1\n taskRef:\n name: apply-manifests\n resources:\n inputs:\n - name: source\n resource: $3\n params:\n - name: manifest_dir\n value: $2');
})
.then(done, done);
});
it('Test array of arrays on properties completion', (done) => {
const content = 'arrayArrayS| | '; // len: 13, pos: 11
const completion = parseSetup(content);
completion
.then(function (result) {
assert.equal(result.items[5].label, 'arrayArraySnippet');
assert.equal(result.items[5].insertText, 'arrayArraySnippet:\n apple:\n - - name: source\n resource: $3');
})
.then(done, done);
});
it('Test array of arrays on value completion', (done) => {
const content = 'arrayArraySnippet: '; // len: 19
const completion = parseSetup(content, 20);
completion
.then(function (result) {
assert.equal(result.items.length, 1);
assert.equal(result.items[0].label, 'Array Array Snippet');
assert.equal(result.items[0].insertText, '\n apple:\n - - name: source\n resource: $3');
})
.then(done, done);
});
it('Test array of arrays on indented completion', (done) => {
const content = 'arrayArraySnippet:\n '; // len: 21
const completion = parseSetup(content, 21);
completion
.then(function (result) {
assert.equal(result.items.length, 1);
assert.equal(result.items[0].label, 'Array Array Snippet');
assert.equal(result.items[0].insertText, 'apple:\n - - name: source\n resource: $3');
})
.then(done, done);
});
it('Test array of strings', (done) => {
const content = 'arrayStringSnippet:\n ';
const completion = parseSetup(content, content.length);
completion
.then(function (result) {
assert.equal(result.items.length, 1);
assert.equal(result.items[0].insertText, 'fruits:\n - banana\n - orange');
})
.then(done, done);
});
it('Test array nested object indented completion', (done) => {
const content = 'arrayNestedObjectSnippet:\n ';
const completion = parseSetup(content, content.length);
completion
.then(function (result) {
assert.equal(result.items.length, 1);
assert.equal(result.items[0].insertText, 'apple:\n - name: source\n resource:\n prop1: value1\n prop2: value2');
})
.then(done, done);
});
it('Test snippet in array indented completion', (done) => {
const content = 'arrayWithSnippet:\n - ';
const completion = parseSetup(content, content.length);
completion
.then(function (result) {
assert.equal(result.items.length, 2);
assert.equal(result.items[0].insertText, 'item1: $1\n item2: $2');
assert.equal(result.items[1].insertText, '\n item1: $1\n item2: $2');
})
.then(done, done);
});
it('Test array of objects extra new line', (done) => {
const content = 'arrayObjectSnippet:\n ';
const completion = parseSetup(content, content.length);
completion
.then(function (result) {
assert.equal(result.items.length, 1);
assert.equal(result.items[0].insertText, 'apple:\n - name: source\n - name: source2');
})
.then(done, done);
});
it('Test string with boolean in string should insert string', (done) => {
const content = 'simpleBooleanString: '; // len: 21
const completion = parseSetup(content, 21);
completion
.then(function (result) {
assert.equal(result.items.length, 1);
assert.equal(result.items[0].label, 'Simple boolean string');
assert.equal(result.items[0].insertText, '\n test: "true"');
})
.then(done, done);
});
it('Test string with boolean NOT in string should insert boolean', (done) => {
const content = 'simpleBoolean: '; // len: 15
const completion = parseSetup(content, 15);
completion
.then(function (result) {
assert.equal(result.items.length, 1);
assert.equal(result.items[0].label, 'Simple string');
assert.equal(result.items[0].insertText, '\n test: true');
})
.then(done, done);
});
it('should preserve space after ":" with prefix', async () => {
const content = 'boolean: |t|r\n'; // len: 12, pos: 9
const result = await parseSetup(content);
assert.notEqual(result.items.length, 0);
assert.equal(result.items[0].label, 'My boolean item');
const textEdit = result.items[0].textEdit;
assert.equal(textEdit.newText, 'false');
assert.equal(textEdit.range.start.line, 0);
assert.equal(textEdit.range.start.character, 9);
assert.equal(textEdit.range.end.line, 0);
assert.equal(textEdit.range.end.character, 11);
});
it('should preserve space after ":"', async () => {
const content = 'boolean: '; // len: 9
const result = await parseSetup(content, 9);
assert.notEqual(result.items.length, 0);
assert.equal(result.items[0].label, 'My boolean item');
const textEdit = result.items[0].textEdit;
assert.equal(textEdit.newText, 'false');
assert.equal(textEdit.range.start.line, 0);
assert.equal(textEdit.range.start.character, 9);
assert.equal(textEdit.range.end.line, 0);
assert.equal(textEdit.range.end.character, 9);
});
it('should add space before value on root node', async () => {
const content = 'name|\n|'; // len: 5, pos: 4
const result = await parseSetup(content);
const item = result.items.find((i) => i.label === 'name');
(0, chai_1.expect)(item).is.not.undefined;
(0, chai_1.expect)(item.textEdit.newText).to.be.equal('name: some');
});
});
});
//# sourceMappingURL=defaultSnippets.test.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
export {};

View File

@@ -0,0 +1,69 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/*---------------------------------------------------------------------------------------------
* Copyright (c) Red Hat. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
const documentPositionCalculator_1 = require("../src/languageservice/utils/documentPositionCalculator");
const assert = require("assert");
describe('DocumentPositionCalculator Tests', () => {
describe('binarySearch', function () {
it('Binary Search where we are looking for element to the left of center', () => {
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const find = 2;
const result = (0, documentPositionCalculator_1.binarySearch)(arr, find);
assert.equal(result, 1);
});
it('Binary Search where we are looking for element to the right of center', () => {
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const find = 8;
const result = (0, documentPositionCalculator_1.binarySearch)(arr, find);
assert.equal(result, 7);
});
it('Binary Search found at first check', () => {
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const find = 5;
const result = (0, documentPositionCalculator_1.binarySearch)(arr, find);
assert.equal(result, 4);
});
it('Binary Search item not found', () => {
const arr = [1];
const find = 5;
const result = (0, documentPositionCalculator_1.binarySearch)(arr, find);
assert.equal(result, -2);
});
});
describe('getLineStartPositions', function () {
it('getLineStartPositions with windows newline', () => {
const test_str = 'test: test\r\ntest: test';
const result = (0, documentPositionCalculator_1.getLineStartPositions)(test_str);
assert.equal(result[0], 0);
assert.equal(result[1], 12);
});
it('getLineStartPositions with normal newline', () => {
const test_str = 'test: test\ntest: test';
const result = (0, documentPositionCalculator_1.getLineStartPositions)(test_str);
assert.equal(result[0], 0);
assert.equal(result[1], 11);
});
});
describe('getPosition', function () {
it('getPosition', () => {
const test_str = 'test: test\r\ntest: test';
const startPositions = (0, documentPositionCalculator_1.getLineStartPositions)(test_str);
const result = (0, documentPositionCalculator_1.getPosition)(0, startPositions);
assert.notEqual(result, undefined);
assert.equal(result.line, 0);
assert.equal(result.character, 0);
});
it('getPosition when not found', () => {
const test_str = 'test: test\ntest: test';
const startPositions = (0, documentPositionCalculator_1.getLineStartPositions)(test_str);
const result = (0, documentPositionCalculator_1.getPosition)(5, startPositions);
assert.notEqual(result, undefined);
assert.equal(result.line, 0);
assert.equal(result.character, 5);
});
});
});
//# sourceMappingURL=documentPositionCalculator.test.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"documentPositionCalculator.test.js","sourceRoot":"","sources":["../../../test/documentPositionCalculator.test.ts"],"names":[],"mappings":";;AAAA;;;gGAGgG;AAChG,wGAA2H;AAC3H,iCAAiC;AAEjC,QAAQ,CAAC,kCAAkC,EAAE,GAAG,EAAE;IAChD,QAAQ,CAAC,cAAc,EAAE;QACvB,EAAE,CAAC,sEAAsE,EAAE,GAAG,EAAE;YAC9E,MAAM,GAAG,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,C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,KAAK,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC;YAC7B,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC;QACpC,CAAC,CAAC,CAAC;QAEH,EAAE,CAAC,4BAA4B,EAAE,GAAG,EAAE;YACpC,MAAM,QAAQ,GAAG,wBAAwB,CAAC;YAE1C,MAAM,cAAc,GAAG,IAAA,kDAAqB,EAAC,QAAQ,CAAC,CAAC;YACvD,MAAM,MAAM,GAAG,IAAA,wCAAW,EAAC,CAAC,EAAE,cAAc,CAAC,CAAC;YAC9C,MAAM,CAAC,QAAQ,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC;YACnC,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC;YAC7B,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC;QACpC,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"}

View File

@@ -0,0 +1 @@
export {};

View File

@@ -0,0 +1,267 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/*---------------------------------------------------------------------------------------------
* Copyright (c) Red Hat. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
const testHelper_1 = require("./utils/testHelper");
const verifyError_1 = require("./utils/verifyError");
const vscode_languageserver_types_1 = require("vscode-languageserver-types");
const assert = require("assert");
const serviceSetup_1 = require("./utils/serviceSetup");
const yamlSettings_1 = require("../src/yamlSettings");
describe('Document Symbols Tests', () => {
let languageHandler;
let yamlSettings;
const limitContent = `
a: [1, 2, 3]
b: [4, 5, 6]
`;
before(() => {
const languageSettingsSetup = new serviceSetup_1.ServiceSetup();
const { languageHandler: langHandler, yamlSettings: settings } = (0, testHelper_1.setupLanguageService)(languageSettingsSetup.languageSettings);
languageHandler = langHandler;
yamlSettings = settings;
});
afterEach(() => {
yamlSettings.maxItemsComputed = 5000;
});
function assertLimitWarning() {
const warnings = languageHandler.pendingLimitExceededWarnings;
assert.deepEqual(Object.keys(warnings), [testHelper_1.TEST_URI]);
assert.deepEqual(warnings[testHelper_1.TEST_URI].features, { 'document symbols': 'document symbols' });
assert(warnings[testHelper_1.TEST_URI].timeout);
}
describe('Document Symbols Tests (Non Hierarchical)', function () {
function parseNonHierarchicalSetup(content) {
const testTextDocument = (0, testHelper_1.setupTextDocument)(content);
yamlSettings.documents = new yamlSettings_1.TextDocumentTestManager();
yamlSettings.documents.set(testTextDocument);
return languageHandler.documentSymbolHandler({
textDocument: testTextDocument,
});
}
it('Document is empty', (done) => {
const content = '';
const symbols = parseNonHierarchicalSetup(content);
assert.deepStrictEqual(symbols, []);
done();
});
it('Simple document symbols', () => {
const content = 'cwd: test';
const symbols = parseNonHierarchicalSetup(content);
assert.equal(symbols.length, 1);
assert.deepEqual(symbols[0], (0, verifyError_1.createExpectedSymbolInformation)('cwd', 15, '', testHelper_1.TEST_URI, 0, 0, 0, 9));
});
it('Document Symbols with number', () => {
const content = 'node1: 10000';
const symbols = parseNonHierarchicalSetup(content);
assert.equal(symbols.length, 1);
assert.deepEqual(symbols[0], (0, verifyError_1.createExpectedSymbolInformation)('node1', 16, '', testHelper_1.TEST_URI, 0, 0, 0, 12));
});
it('Document Symbols with boolean', () => {
const content = 'node1: False';
const symbols = parseNonHierarchicalSetup(content);
assert.equal(symbols.length, 1);
assert.deepEqual(symbols[0], (0, verifyError_1.createExpectedSymbolInformation)('node1', 17, '', testHelper_1.TEST_URI, 0, 0, 0, 12));
});
it('Document Symbols with object', () => {
const content = 'scripts:\n node1: test\n node2: test';
const symbols = parseNonHierarchicalSetup(content);
assert.equal(symbols.length, 3);
assert.deepEqual(symbols[0], (0, verifyError_1.createExpectedSymbolInformation)('scripts', 2, '', testHelper_1.TEST_URI, 0, 0, 2, 13));
assert.deepEqual(symbols[1], (0, verifyError_1.createExpectedSymbolInformation)('node1', 15, 'scripts', testHelper_1.TEST_URI, 1, 2, 1, 13));
assert.deepEqual(symbols[2], (0, verifyError_1.createExpectedSymbolInformation)('node2', 15, 'scripts', testHelper_1.TEST_URI, 2, 2, 2, 13));
});
it('Document Symbols with null', () => {
const content = 'apiVersion: null';
const symbols = parseNonHierarchicalSetup(content);
assert.equal(symbols.length, 1);
assert.deepEqual(symbols[0], (0, verifyError_1.createExpectedSymbolInformation)('apiVersion', vscode_languageserver_types_1.SymbolKind.Variable, '', testHelper_1.TEST_URI, 0, 0, 0, 16));
});
it('Document Symbols with array of strings', () => {
const content = 'items:\n - test\n - test';
const symbols = parseNonHierarchicalSetup(content);
assert.equal(symbols.length, 1);
assert.deepEqual(symbols[0], (0, verifyError_1.createExpectedSymbolInformation)('items', vscode_languageserver_types_1.SymbolKind.Array, '', testHelper_1.TEST_URI, 0, 0, 2, 8));
});
it('Document Symbols with array', () => {
const content = 'authors:\n - name: Josh\n - email: jp';
const symbols = parseNonHierarchicalSetup(content);
assert.equal(symbols.length, 3);
assert.deepEqual(symbols[0], (0, verifyError_1.createExpectedSymbolInformation)('authors', 18, '', testHelper_1.TEST_URI, 0, 0, 2, 13));
assert.deepEqual(symbols[1], (0, verifyError_1.createExpectedSymbolInformation)('name', 15, 'authors', testHelper_1.TEST_URI, 1, 4, 1, 14));
assert.deepEqual(symbols[2], (0, verifyError_1.createExpectedSymbolInformation)('email', 15, 'authors', testHelper_1.TEST_URI, 2, 4, 2, 13));
});
it('Document Symbols with object and array', () => {
const content = 'scripts:\n node1: test\n node2: test\nauthors:\n - name: Josh\n - email: jp';
const symbols = parseNonHierarchicalSetup(content);
assert.equal(symbols.length, 6);
// Sort the items first so they have predictable order in the array
symbols.sort((a, b) => {
return a.name.localeCompare(b.name);
});
assert.deepEqual(symbols[0], (0, verifyError_1.createExpectedSymbolInformation)('authors', 18, '', testHelper_1.TEST_URI, 3, 0, 5, 13));
assert.deepEqual(symbols[1], (0, verifyError_1.createExpectedSymbolInformation)('email', 15, 'authors', testHelper_1.TEST_URI, 5, 4, 5, 13));
assert.deepEqual(symbols[2], (0, verifyError_1.createExpectedSymbolInformation)('name', 15, 'authors', testHelper_1.TEST_URI, 4, 4, 4, 14));
assert.deepEqual(symbols[3], (0, verifyError_1.createExpectedSymbolInformation)('node1', 15, 'scripts', testHelper_1.TEST_URI, 1, 2, 1, 13));
assert.deepEqual(symbols[4], (0, verifyError_1.createExpectedSymbolInformation)('node2', 15, 'scripts', testHelper_1.TEST_URI, 2, 2, 2, 13));
assert.deepEqual(symbols[5], (0, verifyError_1.createExpectedSymbolInformation)('scripts', 2, '', testHelper_1.TEST_URI, 0, 0, 2, 13));
});
it('Document Symbols with multi documents', () => {
const content = '---\nanalytics: true\n...\n---\njson: test\n...';
const symbols = parseNonHierarchicalSetup(content);
assert.equal(symbols.length, 2);
assert.deepEqual(symbols[0], (0, verifyError_1.createExpectedSymbolInformation)('analytics', 17, '', testHelper_1.TEST_URI, 1, 0, 1, 15));
assert.deepEqual(symbols[1], (0, verifyError_1.createExpectedSymbolInformation)('json', 15, '', testHelper_1.TEST_URI, 4, 0, 4, 10));
});
it('Document symbols with a limit', () => {
yamlSettings.maxItemsComputed = 1;
const symbols = parseNonHierarchicalSetup(limitContent);
assert.equal(symbols.length, 1);
assert.deepEqual(symbols[0], (0, verifyError_1.createExpectedSymbolInformation)('a', vscode_languageserver_types_1.SymbolKind.Array, '', testHelper_1.TEST_URI, 1, 4, 1, 16));
assertLimitWarning();
});
});
describe('Document Symbols Tests (Hierarchical)', function () {
function parseHierarchicalSetup(content) {
const testTextDocument = (0, testHelper_1.setupTextDocument)(content);
yamlSettings.hierarchicalDocumentSymbolSupport = true;
yamlSettings.documents = new yamlSettings_1.TextDocumentTestManager();
yamlSettings.documents.set(testTextDocument);
return languageHandler.documentSymbolHandler({
textDocument: testTextDocument,
});
}
it('Document is empty', (done) => {
const content = '';
const symbols = parseHierarchicalSetup(content);
assert.deepStrictEqual(symbols, []);
done();
});
it('Simple document symbols', () => {
const content = 'cwd: test';
const symbols = parseHierarchicalSetup(content);
assert.equal(symbols.length, 1);
assert.deepEqual(symbols[0], (0, verifyError_1.createExpectedDocumentSymbol)('cwd', 15, 0, 0, 0, 9, 0, 0, 0, 3, [], 'test'));
});
it('Document Symbols with number', () => {
const content = 'node1: 10000';
const symbols = parseHierarchicalSetup(content);
assert.equal(symbols.length, 1);
assert.deepEqual(symbols[0], (0, verifyError_1.createExpectedDocumentSymbol)('node1', 16, 0, 0, 0, 12, 0, 0, 0, 5, [], '10000'));
});
it('Document Symbols with boolean', () => {
const content = 'node1: False';
const symbols = parseHierarchicalSetup(content);
assert.equal(symbols.length, 1);
assert.deepEqual(symbols[0], (0, verifyError_1.createExpectedDocumentSymbol)('node1', 17, 0, 0, 0, 12, 0, 0, 0, 5, [], 'false'));
});
it('Document Symbols with object', () => {
const content = 'scripts:\n node1: test\n node2: test';
const symbols = parseHierarchicalSetup(content);
assert.equal(symbols.length, 1);
const child1 = (0, verifyError_1.createExpectedDocumentSymbol)('node1', vscode_languageserver_types_1.SymbolKind.String, 1, 2, 1, 13, 1, 2, 1, 7, [], 'test');
const child2 = (0, verifyError_1.createExpectedDocumentSymbol)('node2', vscode_languageserver_types_1.SymbolKind.String, 2, 2, 2, 13, 2, 2, 2, 7, [], 'test');
const children = [child1, child2];
assert.deepEqual(symbols[0], (0, verifyError_1.createExpectedDocumentSymbol)('scripts', vscode_languageserver_types_1.SymbolKind.Module, 0, 0, 2, 13, 0, 0, 0, 7, children));
});
it('Document Symbols with null', () => {
const content = 'apiVersion: null';
const symbols = parseHierarchicalSetup(content);
assert.equal(symbols.length, 1);
assert.deepEqual(symbols[0], (0, verifyError_1.createExpectedDocumentSymbol)('apiVersion', vscode_languageserver_types_1.SymbolKind.Variable, 0, 0, 0, 16, 0, 0, 0, 10, [], 'null'));
});
it('Document Symbols with array of strings', () => {
const content = 'items:\n - test\n - test';
const symbols = parseHierarchicalSetup(content);
assert.equal(symbols.length, 1);
const child1 = (0, verifyError_1.createExpectedDocumentSymbolNoDetail)('0', vscode_languageserver_types_1.SymbolKind.String, 1, 4, 1, 8, 1, 4, 1, 8);
const child2 = (0, verifyError_1.createExpectedDocumentSymbolNoDetail)('1', vscode_languageserver_types_1.SymbolKind.String, 2, 4, 2, 8, 2, 4, 2, 8);
const children = [child1, child2];
assert.deepEqual(symbols[0], (0, verifyError_1.createExpectedDocumentSymbol)('items', vscode_languageserver_types_1.SymbolKind.Array, 0, 0, 2, 8, 0, 0, 0, 5, children));
});
it('Document Symbols with array', () => {
const content = 'authors:\n - name: Josh\n - email: jp';
const symbols = parseHierarchicalSetup(content);
const object1 = (0, verifyError_1.createExpectedDocumentSymbol)('name', vscode_languageserver_types_1.SymbolKind.String, 1, 4, 1, 14, 1, 4, 1, 8, [], 'Josh');
const arrayChild1 = (0, verifyError_1.createExpectedDocumentSymbolNoDetail)('0', vscode_languageserver_types_1.SymbolKind.Module, 1, 4, 1, 14, 1, 4, 1, 14, [object1]);
const object2 = (0, verifyError_1.createExpectedDocumentSymbol)('email', vscode_languageserver_types_1.SymbolKind.String, 2, 4, 2, 13, 2, 4, 2, 9, [], 'jp');
const arrayChild2 = (0, verifyError_1.createExpectedDocumentSymbolNoDetail)('1', vscode_languageserver_types_1.SymbolKind.Module, 2, 4, 2, 13, 2, 4, 2, 13, [object2]);
const children = [arrayChild1, arrayChild2];
assert.deepEqual(symbols[0], (0, verifyError_1.createExpectedDocumentSymbol)('authors', vscode_languageserver_types_1.SymbolKind.Array, 0, 0, 2, 13, 0, 0, 0, 7, children));
});
it('Document Symbols with object and array', () => {
const content = 'scripts:\n node1: test\n node2: test\nauthors:\n - name: Josh\n - email: jp';
const symbols = parseHierarchicalSetup(content);
assert.equal(symbols.length, 2);
const child1 = (0, verifyError_1.createExpectedDocumentSymbol)('node1', vscode_languageserver_types_1.SymbolKind.String, 1, 2, 1, 13, 1, 2, 1, 7, [], 'test');
const child2 = (0, verifyError_1.createExpectedDocumentSymbol)('node2', vscode_languageserver_types_1.SymbolKind.String, 2, 2, 2, 13, 2, 2, 2, 7, [], 'test');
const children = [child1, child2];
assert.deepEqual(symbols[0], (0, verifyError_1.createExpectedDocumentSymbol)('scripts', vscode_languageserver_types_1.SymbolKind.Module, 0, 0, 2, 13, 0, 0, 0, 7, children));
const object1 = (0, verifyError_1.createExpectedDocumentSymbol)('name', vscode_languageserver_types_1.SymbolKind.String, 4, 4, 4, 14, 4, 4, 4, 8, [], 'Josh');
const arrayChild1 = (0, verifyError_1.createExpectedDocumentSymbolNoDetail)('0', vscode_languageserver_types_1.SymbolKind.Module, 4, 4, 4, 14, 4, 4, 4, 14, [object1]);
const object2 = (0, verifyError_1.createExpectedDocumentSymbol)('email', vscode_languageserver_types_1.SymbolKind.String, 5, 4, 5, 13, 5, 4, 5, 9, [], 'jp');
const arrayChild2 = (0, verifyError_1.createExpectedDocumentSymbolNoDetail)('1', vscode_languageserver_types_1.SymbolKind.Module, 5, 4, 5, 13, 5, 4, 5, 13, [object2]);
const children2 = [arrayChild1, arrayChild2];
assert.deepEqual(symbols[1], (0, verifyError_1.createExpectedDocumentSymbol)('authors', vscode_languageserver_types_1.SymbolKind.Array, 3, 0, 5, 13, 3, 0, 3, 7, children2));
});
it('Document Symbols with multi documents', () => {
const content = '---\nanalytics: true\n...\n---\njson: test\n...';
const symbols = parseHierarchicalSetup(content);
assert.equal(symbols.length, 2);
assert.deepEqual(symbols[0], (0, verifyError_1.createExpectedDocumentSymbol)('analytics', vscode_languageserver_types_1.SymbolKind.Boolean, 1, 0, 1, 15, 1, 0, 1, 9, [], 'true'));
assert.deepEqual(symbols[1], (0, verifyError_1.createExpectedDocumentSymbol)('json', vscode_languageserver_types_1.SymbolKind.String, 4, 0, 4, 10, 4, 0, 4, 4, [], 'test'));
});
it('Document Symbols with complex mapping and aliases', () => {
const content = `
version: 0.0.1
structure:
? &root root
:
element: div
conditions:
? *root
:
style:
height: 41`;
const symbols = parseHierarchicalSetup(content);
assert.equal(symbols.length, 3);
assert.deepEqual(symbols[0], (0, verifyError_1.createExpectedDocumentSymbol)('version', vscode_languageserver_types_1.SymbolKind.String, 1, 12, 1, 26, 1, 12, 1, 19, [], '0.0.1'));
const element = (0, verifyError_1.createExpectedDocumentSymbol)('element', vscode_languageserver_types_1.SymbolKind.String, 5, 16, 5, 28, 5, 16, 5, 23, [], 'div');
const root1 = (0, verifyError_1.createExpectedDocumentSymbol)('root', vscode_languageserver_types_1.SymbolKind.Module, 3, 22, 5, 28, 3, 22, 3, 26, [element]);
const height = (0, verifyError_1.createExpectedDocumentSymbol)('height', vscode_languageserver_types_1.SymbolKind.Number, 10, 18, 10, 28, 10, 18, 10, 24, [], '41');
const style = (0, verifyError_1.createExpectedDocumentSymbol)('style', vscode_languageserver_types_1.SymbolKind.Module, 9, 16, 10, 28, 9, 16, 9, 21, [height]);
const root2 = (0, verifyError_1.createExpectedDocumentSymbol)('root', vscode_languageserver_types_1.SymbolKind.Module, 7, 16, 10, 28, 7, 16, 7, 21, [style]);
assert.deepEqual(symbols[1], (0, verifyError_1.createExpectedDocumentSymbol)('structure', vscode_languageserver_types_1.SymbolKind.Module, 2, 12, 5, 28, 2, 12, 2, 21, [root1]));
assert.deepEqual(symbols[2], (0, verifyError_1.createExpectedDocumentSymbol)('conditions', vscode_languageserver_types_1.SymbolKind.Module, 6, 12, 10, 28, 6, 12, 6, 22, [root2]));
});
it('Document symbols with a limit', () => {
yamlSettings.maxItemsComputed = 3;
const symbols = parseHierarchicalSetup(limitContent);
assert.equal(symbols.length, 2);
assert.equal(symbols[0].children.length, 1);
assert.equal(symbols[1].children.length, 0);
const el = (0, verifyError_1.createExpectedDocumentSymbolNoDetail)('0', vscode_languageserver_types_1.SymbolKind.Number, 1, 8, 1, 9, 1, 8, 1, 9, []);
const root = (0, verifyError_1.createExpectedDocumentSymbol)('a', vscode_languageserver_types_1.SymbolKind.Array, 1, 4, 1, 16, 1, 4, 1, 5, [el]);
assert.deepEqual(symbols[0], root);
assertLimitWarning();
});
it('Document Symbols with numbers as keys', () => {
const content = 'items:\n 1: test\n 2: test';
const symbols = parseHierarchicalSetup(content);
assert.equal(symbols.length, 1);
const child1 = (0, verifyError_1.createExpectedDocumentSymbol)('1', vscode_languageserver_types_1.SymbolKind.String, 1, 2, 1, 9, 1, 2, 1, 3, undefined, 'test');
const child2 = (0, verifyError_1.createExpectedDocumentSymbol)('2', vscode_languageserver_types_1.SymbolKind.String, 2, 2, 2, 9, 2, 2, 2, 3, undefined, 'test');
const children = [child1, child2];
assert.deepEqual(symbols[0], (0, verifyError_1.createExpectedDocumentSymbol)('items', vscode_languageserver_types_1.SymbolKind.Module, 0, 0, 2, 9, 0, 0, 0, 5, children));
});
it('Document Symbols with mapping as keys', () => {
const content = '{foo: bar}: foo';
const symbols = parseHierarchicalSetup(content);
assert.equal(symbols.length, 1);
assert.deepEqual(symbols[0], (0, verifyError_1.createExpectedDocumentSymbol)('{}', vscode_languageserver_types_1.SymbolKind.String, 0, 0, 0, 15, 0, 0, 0, 10, [], 'foo'));
});
});
});
//# sourceMappingURL=documentSymbols.test.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
export {};

View File

@@ -0,0 +1,58 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/*---------------------------------------------------------------------------------------------
* Copyright (c) Red Hat. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
const testHelper_1 = require("./utils/testHelper");
const assert = require("assert");
const serviceSetup_1 = require("./utils/serviceSetup");
const yamlSettings_1 = require("../src/yamlSettings");
describe('Find Links Tests', () => {
let languageHandler;
let yamlSettings;
before(() => {
const languageSettingsSetup = new serviceSetup_1.ServiceSetup();
const { languageHandler: langHandler, yamlSettings: settings } = (0, testHelper_1.setupLanguageService)(languageSettingsSetup.languageSettings);
languageHandler = langHandler;
yamlSettings = settings;
});
function findLinks(content) {
const testTextDocument = (0, testHelper_1.setupTextDocument)(content);
yamlSettings.documents = new yamlSettings_1.TextDocumentTestManager();
yamlSettings.documents.set(testTextDocument);
return languageHandler.documentLinkHandler({
textDocument: testTextDocument,
});
}
describe('Jump to definition', function () {
it('Find source definition', (done) => {
const content = "definitions:\n link:\n type: string\ntype: object\nproperties:\n uri:\n $ref: '#/definitions/link'\n";
const definitions = findLinks(content);
definitions
.then(function (results) {
assert.equal(results.length, 1);
assert.deepEqual(results[0].range, {
start: {
line: 6,
character: 11,
},
end: {
line: 6,
character: 29,
},
});
assert.deepEqual(results[0].target, 'file://~/Desktop/vscode-k8s/test.yaml#3,5');
})
.then(done, done);
});
});
describe('Bug fixes', () => {
it('should work with flow map', async () => {
const content = 'f: {ffff: fff, aa: [ddd, drr: {}]}';
const results = await findLinks(content);
assert.equal(results.length, 0);
});
});
});
//# sourceMappingURL=findLinks.test.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"findLinks.test.js","sourceRoot":"","sources":["../../../test/findLinks.test.ts"],"names":[],"mappings":";;AAAA;;;gGAGgG;AAChG,mDAA6E;AAC7E,iCAAkC;AAClC,uDAAoD;AAEpD,sDAA6E;AAG7E,QAAQ,CAAC,kBAAkB,EAAE,GAAG,EAAE;IAChC,IAAI,eAAiC,CAAC;IACtC,IAAI,YAA2B,CAAC;IAEhC,MAAM,CAAC,GAAG,EAAE;QACV,MAAM,qBAAqB,GAAG,IAAI,2BAAY,EAAE,CAAC;QACjD,MAAM,EAAE,eAAe,EAAE,WAAW,EAAE,YAAY,EAAE,QAAQ,EAAE,GAAG,IAAA,iCAAoB,EAAC,qBAAqB,CAAC,gBAAgB,CAAC,CAAC;QAC9H,eAAe,GAAG,WAAW,CAAC;QAC9B,YAAY,GAAG,QAAQ,CAAC;IAC1B,CAAC,CAAC,CAAC;IAEH,SAAS,SAAS,CAAC,OAAe;QAChC,MAAM,gBAAgB,GAAG,IAAA,8BAAiB,EAAC,OAAO,CAAC,CAAC;QACpD,YAAY,CAAC,SAAS,GAAG,IAAI,sCAAuB,EAAE,CAAC;QACtD,YAAY,CAAC,SAAqC,CAA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};

View File

@@ -0,0 +1,79 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const chai_1 = require("chai");
const yaml_documents_1 = require("../src/languageservice/parser/yaml-documents");
const flow_style_rewriter_1 = require("../src/languageservice/utils/flow-style-rewriter");
const testHelper_1 = require("./utils/testHelper");
describe('Flow style rewriter', () => {
let writer;
let documents;
const indentation = ' ';
beforeEach(() => {
documents = new yaml_documents_1.YamlDocuments();
writer = new flow_style_rewriter_1.FlowStyleRewriter(indentation);
});
it('should return null if node is not flow style', () => {
const doc = (0, testHelper_1.setupTextDocument)('foo: bar');
const yamlDoc = documents.getYamlDocument(doc);
const node = yamlDoc.documents[0].getNodeFromOffset(1);
const result = writer.write(node);
(0, chai_1.expect)(result).to.be.null;
});
it('should rewrite flow style map to block', () => {
const doc = (0, testHelper_1.setupTextDocument)('datacenter: { location: canada, cab: 15}');
const yamlDoc = documents.getYamlDocument(doc);
const node = yamlDoc.documents[0].getNodeFromOffset(13);
const result = writer.write(node);
(0, chai_1.expect)(result).not.to.be.null;
(0, chai_1.expect)(result).to.deep.equals(`\n${indentation}location: canada\n${indentation}cab: 15`);
});
it('should rewrite flow style map and preserve space ', () => {
const doc = (0, testHelper_1.setupTextDocument)('datacenter: { location: canada, cab: 15}');
const yamlDoc = documents.getYamlDocument(doc);
const node = yamlDoc.documents[0].getNodeFromOffset(13);
const result = writer.write(node);
(0, chai_1.expect)(result).not.to.be.null;
(0, chai_1.expect)(result).to.deep.equals(`\n${indentation}location: canada\n${indentation}cab: 15`);
});
it('should rewrite flow style map with null ', () => {
const doc = (0, testHelper_1.setupTextDocument)('datacenter: { "explicit": "entry",\n "implicit": "entry",\n null: null }');
const yamlDoc = documents.getYamlDocument(doc);
const node = yamlDoc.documents[0].getNodeFromOffset(13);
const result = writer.write(node);
(0, chai_1.expect)(result).not.to.be.null;
(0, chai_1.expect)(result).to.deep.equals(`\n${indentation}"explicit": "entry"\n${indentation}"implicit": "entry"\n${indentation}null: null `);
});
it('should rewrite flow style map with explicit entry', () => {
const doc = (0, testHelper_1.setupTextDocument)('datacenter: { "foo bar": "baz" }');
const yamlDoc = documents.getYamlDocument(doc);
const node = yamlDoc.documents[0].getNodeFromOffset(13);
const result = writer.write(node);
(0, chai_1.expect)(result).not.to.be.null;
(0, chai_1.expect)(result).to.deep.equals(`\n${indentation}"foo bar": "baz" `);
});
it('should rewrite flow style sequence', () => {
const doc = (0, testHelper_1.setupTextDocument)('animals: [dog , cat , mouse] ');
const yamlDoc = documents.getYamlDocument(doc);
const node = yamlDoc.documents[0].getNodeFromOffset(9);
const result = writer.write(node);
(0, chai_1.expect)(result).not.to.be.null;
(0, chai_1.expect)(result).to.deep.equals(`\n${indentation}- dog \n${indentation}- cat \n${indentation}- mouse`);
});
it('should rewrite flow style for mixed sequence and map', () => {
const doc = (0, testHelper_1.setupTextDocument)('animals: [ { "foo": "bar" } ]');
const yamlDoc = documents.getYamlDocument(doc);
const node = yamlDoc.documents[0].getNodeFromOffset(9);
const result = writer.write(node);
(0, chai_1.expect)(result).not.to.be.null;
(0, chai_1.expect)(result).to.deep.equals(`\n${indentation}- { "foo": "bar" } `);
});
it('should rewrite flow style when parent is sequence', () => {
const doc = (0, testHelper_1.setupTextDocument)(`items:\n${indentation}- { location: some }`);
const yamlDoc = documents.getYamlDocument(doc);
const node = yamlDoc.documents[0].getNodeFromOffset(13);
const result = writer.write(node);
(0, chai_1.expect)(result).not.to.be.null;
(0, chai_1.expect)(result).to.deep.equals(` location: some `);
});
});
//# sourceMappingURL=flow-style-rewriter.test.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"flow-style-rewriter.test.js","sourceRoot":"","sources":["../../../test/flow-style-rewriter.test.ts"],"names":[],"mappings":";;AAAA,+BAA8B;AAC9B,iFAA6E;AAC7E,0FAAqF;AACrF,mDAAuD;AAEvD,QAAQ,CAAC,qBAAqB,EAAE,GAAG,EAAE;IACnC,IAAI,MAAyB,CAAC;IAC9B,IAAI,SAAwB,CAAC;IAC7B,MAAM,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e,CAAC,GAAG,CAAC,CAAC;QAE/C,MAAM,IAAI,GAAG,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC;QACvD,MAAM,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QAClC,IAAA,aAAM,EAAC,MAAM,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,CAAC,IAAI,CAAC;QAC9B,IAAA,aAAM,EAAC,MAAM,CAAC,CAAC,EAAE,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,WAAW,qBAAqB,CAAC,CAAC;IACvE,CAAC,CAAC,CAAC;IACH,EAAE,CAAC,mDAAmD,EAAE,GAAG,EAAE;QAC3D,MAAM,GAAG,GAAG,IAAA,8BAAiB,EAAC,WAAW,WAAW,uBAAuB,CAAC,CAAC;QAC7E,MAAM,OAAO,GAAG,SAAS,CAAC,eAAe,CAAC,GAAG,CAAC,CAAC;QAE/C,MAAM,IAAI,GAAG,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,iBAAiB,CAAC,EAAE,CAAC,CAAC;QACxD,MAAM,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QAClC,IAAA,aAAM,EAAC,MAAM,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,CAAC,IAAI,CAAC;QAC9B,IAAA,aAAM,EAAC,MAAM,CAAC,CAAC,EAAE,CAAC,IAAI,CAAC,MAAM,CAAC,mBAAmB,CAAC,CAAC;IACrD,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"}

View File

@@ -0,0 +1 @@
export {};

View File

@@ -0,0 +1,119 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/*---------------------------------------------------------------------------------------------
* Copyright (c) Red Hat. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
const testHelper_1 = require("./utils/testHelper");
const serviceSetup_1 = require("./utils/serviceSetup");
const assert = require("assert");
const yamlSettings_1 = require("../src/yamlSettings");
describe('Formatter Tests', () => {
let languageHandler;
let yamlSettings;
before(() => {
const languageSettingsSetup = new serviceSetup_1.ServiceSetup().withFormat();
const { languageHandler: langHandler, yamlSettings: settings } = (0, testHelper_1.setupLanguageService)(languageSettingsSetup.languageSettings);
languageHandler = langHandler;
yamlSettings = settings;
});
// Tests for formatter
describe('Formatter', function () {
describe('Test that formatter works with custom tags', function () {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function parseSetup(content, options = {}) {
const testTextDocument = (0, testHelper_1.setupTextDocument)(content);
yamlSettings.documents = new yamlSettings_1.TextDocumentTestManager();
yamlSettings.documents.set(testTextDocument);
yamlSettings.yamlFormatterSettings = options;
return languageHandler.formatterHandler({
options,
textDocument: testTextDocument,
});
}
it('Formatting works without custom tags', () => {
const content = 'cwd: test';
const edits = parseSetup(content);
assert.notEqual(edits.length, 0);
assert.equal(edits[0].newText, 'cwd: test\n');
});
it('Formatting works with custom tags', () => {
const content = 'cwd: !Test test';
const edits = parseSetup(content);
assert.notEqual(edits.length, 0);
assert.equal(edits[0].newText, 'cwd: !Test test\n');
});
it('Formatting wraps text', () => {
const content = `comments: >
test test test test test test test test test test test test`;
const edits = parseSetup(content, {
printWidth: 20,
proseWrap: 'always',
});
assert.equal(edits[0].newText, 'comments: >\n test test test\n test test test\n test test test\n test test test\n');
});
it('Formatting uses tabSize', () => {
const content = `map:
k1: v1
k2: v2
list:
- item1
- item2
`;
const edits = parseSetup(content, {
tabSize: 5,
});
const expected = `map:
k1: v1
k2: v2
list:
- item1
- item2
`;
assert.equal(edits[0].newText, expected);
});
it('Formatting uses tabWidth', () => {
const content = `map:
k1: v1
k2: v2
list:
- item1
- item2
`;
const edits = parseSetup(content, {
tabWidth: 5,
});
const expected = `map:
k1: v1
k2: v2
list:
- item1
- item2
`;
assert.equal(edits[0].newText, expected);
});
it('Formatting uses tabWidth over tabSize', () => {
const content = `map:
k1: v1
k2: v2
list:
- item1
- item2
`;
const edits = parseSetup(content, {
tabSize: 3,
tabWidth: 5,
});
const expected = `map:
k1: v1
k2: v2
list:
- item1
- item2
`;
assert.equal(edits[0].newText, expected);
});
});
});
});
//# sourceMappingURL=formatter.test.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"formatter.test.js","sourceRoot":"","sources":["../../../test/formatter.test.ts"],"names":[],"mappings":";;AAAA;;;gGAGgG;AAChG,mDAA6E;AAC7E,uDAAoD;AACpD,iCAAiC;AAEjC,sDAA6E;AAG7E,QAAQ,CAAC,iBAAiB,EAAE,GAAG,EAAE;IAC/B,IAAI,eAAiC,CAAC;IACtC,IAAI,YAA2B,CAAC;IAEhC,MAAM,CAAC,GAAG,EAAE;QACV,MAAM,qBAAqB,GAAG,IAAI,2BAAY,EAAE,CAAC,UAAU,EAAE,CAAC;QAC9D,MAAM,EAAE,eAAe,EAAE,WAAW,EAAE,YAAY,EAAE,QAAQ,EAAE,GAAG,IAAA,iCAAoB,EAAC,qBAAqB,CAAC,gBAAgB,CAAC,CAAC;QAC9H,eAAe,GAAG,WAAW,CAAC;QAC9B,YAAY,GAAG,QAAQ,CAAC;IAC1B,CAAC,CAAC,CAAC;IAEH,sBAAsB;IACtB,QAAQ,CAAC,WAAW,EAAE;QACpB,QAAQ,CAAC,4CAA4C,EAAE;YACrD,8DAA8D;YAC9D,SAAS,UAAU,CAAC,OAAe,EAAE,UAAe,EAAE;gBACpD,MAAM,gBAAgB,GAAG,IAAA,8BAAiB,EAAC,OAAO,CAAC,CAAC;gBACpD,YAAY,CAAC,SAAS,GAAG,IAAI,sCAAuB,EAAE,CAAC;gBACtD,YAAY,CAAC,SAAqC,CAAC,GAAG,CAAC,gBAAgB,CAAC,CAAC;gBAC1E,YAAY,CAAC,qBAAqB,GAAG,OAAO,CAAC;gBAC7C,OAAO,eAAe,CAAC,gBAAgB,CAAC;oBACtC,OAAO;oBACP,YAAY,EAAE,gBAAgB;iBAC/B,CAAC,C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MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;YAC3C,CAAC,CAAC,CAAC;YAEH,EAAE,CAAC,0BAA0B,EAAE,GAAG,EAAE;gBAClC,MAAM,OAAO,GAAG;;;;;;CAMvB,CAAC;gBAEM,MAAM,KAAK,GAAG,UAAU,CAAC,OAAO,EAAE;oBAChC,QAAQ,EAAE,CAAC;iBACZ,CAAC,CAAC;gBAEH,MAAM,QAAQ,GAAG;;;;;;CAMxB,CAAC;gBACM,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;YAC3C,CAAC,CAAC,CAAC;YAEH,EAAE,CAAC,uCAAuC,EAAE,GAAG,EAAE;gBAC/C,MAAM,OAAO,GAAG;;;;;;CAMvB,CAAC;gBAEM,MAAM,KAAK,GAAG,UAAU,CAAC,OAAO,EAAE;oBAChC,OAAO,EAAE,CAAC;oBACV,QAAQ,EAAE,CAAC;iBACZ,CAAC,CAAC;gBAEH,MAAM,QAAQ,GAAG;;;;;;CAMxB,CAAC;gBACM,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;YAC3C,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"}

View File

@@ -0,0 +1 @@
export {};

View File

@@ -0,0 +1,646 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/*---------------------------------------------------------------------------------------------
* Copyright (c) Red Hat. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
const serviceSetup_1 = require("./utils/serviceSetup");
const testHelper_1 = require("./utils/testHelper");
const assert = require("assert");
const vscode_languageserver_types_1 = require("vscode-languageserver-types");
const yamlSettings_1 = require("../src/yamlSettings");
const chai_1 = require("chai");
describe('Hover Tests', () => {
let languageSettingsSetup;
let languageHandler;
let yamlSettings;
let telemetry;
let schemaProvider;
before(() => {
languageSettingsSetup = new serviceSetup_1.ServiceSetup().withHover().withSchemaFileMatch({
uri: 'http://google.com',
fileMatch: ['bad-schema.yaml'],
});
const { languageHandler: langHandler, yamlSettings: settings, telemetry: testTelemetry, schemaProvider: testSchemaProvider, } = (0, testHelper_1.setupLanguageService)(languageSettingsSetup.languageSettings);
languageHandler = langHandler;
yamlSettings = settings;
telemetry = testTelemetry;
schemaProvider = testSchemaProvider;
});
afterEach(() => {
schemaProvider.deleteSchema(testHelper_1.SCHEMA_ID);
});
/**
* Generates hover information for the given document and caret (cursor) position.
* @param content The content of the document.
* @param position The position of the caret in the document.
* Alternatively, `position` can be omitted if the caret is located in the content using `|` bookends.
* For example, `content = 'ab|c|d'` places the caret over the `'c'`, at `position = 2`
* @returns An instance of `Hover`.
*/
function parseSetup(content, position) {
if (typeof position === 'undefined') {
({ content, position } = (0, testHelper_1.caretPosition)(content));
}
const testTextDocument = (0, testHelper_1.setupSchemaIDTextDocument)(content);
yamlSettings.documents = new yamlSettings_1.TextDocumentTestManager();
yamlSettings.documents.set(testTextDocument);
return languageHandler.hoverHandler({
position: testTextDocument.positionAt(position),
textDocument: testTextDocument,
});
}
describe('Hover', function () {
it('Hover on key on root', async () => {
schemaProvider.addSchema(testHelper_1.SCHEMA_ID, {
type: 'object',
properties: {
cwd: {
type: 'string',
description: 'The directory from which bower should run. All relative paths will be calculated according to this setting.',
},
},
});
const content = 'c|w|d: test'; // len: 9, pos: 1
const hover = await parseSetup(content);
assert.strictEqual(vscode_languageserver_types_1.MarkupContent.is(hover.contents), true);
assert.strictEqual(hover.contents.kind, 'markdown');
assert.strictEqual(hover.contents.value, `The directory from which bower should run\\. All relative paths will be calculated according to this setting\\.\n\nSource: [${testHelper_1.SCHEMA_ID}](file:///${testHelper_1.SCHEMA_ID})`);
});
it('Hover on value on root', async () => {
schemaProvider.addSchema(testHelper_1.SCHEMA_ID, {
type: 'object',
properties: {
cwd: {
type: 'string',
description: 'The directory from which bower should run. All relative paths will be calculated according to this setting.',
},
},
});
const content = 'cwd: t|e|st'; // len: 9, pos: 6
const result = await parseSetup(content);
assert.strictEqual(vscode_languageserver_types_1.MarkupContent.is(result.contents), true);
assert.strictEqual(result.contents.kind, 'markdown');
assert.strictEqual(result.contents.value, `The directory from which bower should run\\. All relative paths will be calculated according to this setting\\.\n\nSource: [${testHelper_1.SCHEMA_ID}](file:///${testHelper_1.SCHEMA_ID})`);
});
it('Hover on key with depth', async () => {
schemaProvider.addSchema(testHelper_1.SCHEMA_ID, {
type: 'object',
properties: {
scripts: {
type: 'object',
properties: {
postinstall: {
type: 'string',
description: 'A script to run after install',
},
},
},
},
});
const content = 'scripts:\n post|i|nstall: test'; // len: 28, pos: 15
const result = await parseSetup(content);
assert.strictEqual(vscode_languageserver_types_1.MarkupContent.is(result.contents), true);
assert.strictEqual(result.contents.kind, 'markdown');
assert.strictEqual(result.contents.value, `A script to run after install\n\nSource: [${testHelper_1.SCHEMA_ID}](file:///${testHelper_1.SCHEMA_ID})`);
});
it('Hover on value with depth', async () => {
schemaProvider.addSchema(testHelper_1.SCHEMA_ID, {
type: 'object',
properties: {
scripts: {
type: 'object',
properties: {
postinstall: {
type: 'string',
description: 'A script to run after install',
},
},
},
},
});
const content = 'scripts:\n postinstall: te|s|t'; // len: 28, pos: 26
const result = await parseSetup(content);
assert.strictEqual(vscode_languageserver_types_1.MarkupContent.is(result.contents), true);
assert.strictEqual(result.contents.kind, 'markdown');
assert.strictEqual(result.contents.value, `A script to run after install\n\nSource: [${testHelper_1.SCHEMA_ID}](file:///${testHelper_1.SCHEMA_ID})`);
});
it('Hover works on both root node and child nodes works', async () => {
schemaProvider.addSchema(testHelper_1.SCHEMA_ID, {
type: 'object',
properties: {
scripts: {
type: 'object',
properties: {
postinstall: {
type: 'string',
description: 'A script to run after install',
},
},
description: 'Contains custom hooks used to trigger other automated tools',
},
},
});
const content1 = 'scr|i|pts:\n postinstall: test'; // len: 28, pos: 3
const firstHover = await parseSetup(content1);
assert.strictEqual(vscode_languageserver_types_1.MarkupContent.is(firstHover.contents), true);
assert.strictEqual(firstHover.contents.kind, 'markdown');
assert.strictEqual(firstHover.contents.value, `Contains custom hooks used to trigger other automated tools\n\nSource: [${testHelper_1.SCHEMA_ID}](file:///${testHelper_1.SCHEMA_ID})`);
const content2 = 'scripts:\n post|i|nstall: test'; // len: 28, pos: 15
const secondHover = await parseSetup(content2);
assert.strictEqual(vscode_languageserver_types_1.MarkupContent.is(secondHover.contents), true);
assert.strictEqual(secondHover.contents.value, `A script to run after install\n\nSource: [${testHelper_1.SCHEMA_ID}](file:///${testHelper_1.SCHEMA_ID})`);
});
it('Hover does not show results when there isnt description field', async () => {
schemaProvider.addSchema(testHelper_1.SCHEMA_ID, {
type: 'object',
properties: {
analytics: {
type: 'boolean',
},
},
});
const content = 'ana|l|ytics: true'; // len: 15, pos: 3
const result = await parseSetup(content);
assert.strictEqual(vscode_languageserver_types_1.MarkupContent.is(result.contents), true);
assert.strictEqual(result.contents.value, '');
});
it('Hover on first document in multi document', async () => {
schemaProvider.addSchema(testHelper_1.SCHEMA_ID, {
type: 'object',
properties: {
analytics: {
type: 'boolean',
},
},
});
const content = '---\nanalytics: true\n...\n---\njson: test\n...';
const result = await parseSetup(content, 10);
assert.strictEqual(vscode_languageserver_types_1.MarkupContent.is(result.contents), true);
assert.strictEqual(result.contents.value, '');
});
it('Hover on second document in multi document', async () => {
schemaProvider.addSchema(testHelper_1.SCHEMA_ID, {
type: 'object',
properties: {
analytics: {
type: 'boolean',
},
json: {
type: 'string',
description: 'A file path to the configuration file',
},
},
});
const content = '---\nanalytics: true\n...\n---\njs|o|n: test\n...'; // len: 42, pos: 30
const result = await parseSetup(content);
assert.strictEqual(vscode_languageserver_types_1.MarkupContent.is(result.contents), true);
assert.strictEqual(result.contents.value, `A file path to the configuration file\n\nSource: [${testHelper_1.SCHEMA_ID}](file:///${testHelper_1.SCHEMA_ID})`);
});
it('Hover should not return anything on key', async () => {
schemaProvider.addSchema(testHelper_1.SCHEMA_ID, {
type: 'object',
properties: {},
});
const content = 'm|y|_unknown_hover: test'; // len: 22, pos: 1
const result = await parseSetup(content);
assert.strictEqual(vscode_languageserver_types_1.MarkupContent.is(result.contents), true);
assert.strictEqual(result.contents.value, '');
});
it('Hover should not return anything on value', async () => {
schemaProvider.addSchema(testHelper_1.SCHEMA_ID, {
type: 'object',
properties: {},
});
const content = 'my_unknown_hover: tes|t|'; // len: 22, pos: 21
const result = await parseSetup(content);
assert.strictEqual(vscode_languageserver_types_1.MarkupContent.is(result.contents), true);
assert.strictEqual(result.contents.value, '');
});
it('Hover works on array nodes', async () => {
schemaProvider.addSchema(testHelper_1.SCHEMA_ID, {
type: 'object',
properties: {
authors: {
type: 'array',
items: {
type: 'object',
properties: {
name: {
type: 'string',
description: 'Full name of the author.',
},
},
},
},
},
});
const content = 'authors:\n - n|a|me: Josh'; // len: 23, pos: 14
const result = await parseSetup(content);
assert.strictEqual(vscode_languageserver_types_1.MarkupContent.is(result.contents), true);
assert.strictEqual(result.contents.value, `Full name of the author\\.\n\nSource: [${testHelper_1.SCHEMA_ID}](file:///${testHelper_1.SCHEMA_ID})`);
});
it('Hover works on additional array nodes', async () => {
schemaProvider.addSchema(testHelper_1.SCHEMA_ID, {
type: 'object',
properties: {
authors: {
type: 'array',
items: {
type: 'object',
properties: {
name: {
type: 'string',
description: 'Full name of the author.',
},
email: {
type: 'string',
description: 'Email address of the author.',
},
},
},
},
},
});
const content = 'authors:\n - name: Josh\n - |e|mail: jp'; // len: 37, pos: 28
const result = await parseSetup(content);
assert.strictEqual(vscode_languageserver_types_1.MarkupContent.is(result.contents), true);
assert.strictEqual(result.contents.value, `Email address of the author\\.\n\nSource: [${testHelper_1.SCHEMA_ID}](file:///${testHelper_1.SCHEMA_ID})`);
});
it('Hover works on oneOf reference array nodes', async () => {
schemaProvider.addSchema(testHelper_1.SCHEMA_ID, {
type: 'object',
definitions: {
stringoptions: {
$id: '#/definitions/stringoptions',
type: 'array',
additionalItems: false,
uniqueItems: true,
minItems: 1,
items: {
oneOf: [
{
type: 'string',
},
],
},
},
},
properties: {
ignition: {
type: 'object',
properties: {
proxy: {
type: 'object',
properties: {
no_proxy: {
$ref: '#/definitions/stringoptions',
title: 'no_proxy (list of strings):',
description: 'Specifies a list of strings to hosts that should be excluded from proxying. Each value is represented by an IP address prefix (1.2.3.4), an IP address prefix in CIDR notation (1.2.3.4/8), a domain name, or a special DNS label (*). An IP address prefix and domain name can also include a literal port number (1.2.3.4:80). A domain name matches that name and all subdomains. A domain name with a leading . matches subdomains only. For example foo.com matches foo.com and bar.foo.com; .y.com matches x.y.com but not y.com. A single asterisk (*) indicates that no proxying should be done.',
},
},
},
},
},
storage: {
type: 'object',
properties: {
raid: {
type: 'array',
items: {
oneOf: [
{
properties: {
name: {
type: 'string',
title: 'name (string):',
description: 'The name to use for the resulting md device.',
},
devices: {
$ref: '#/definitions/stringoptions',
title: 'devices (list of strings):',
description: 'The list of devices (referenced by their absolute path) in the array.',
},
options: {
$ref: '#/definitions/stringoptions',
title: 'options (list of strings):',
description: 'Any additional options to be passed to mdadm.',
},
},
},
],
},
},
},
},
},
});
const content1 = `ignition:
proxy:
no_proxy:
- 10|.|10.10.10
- service.local
storage:
raid:
- name: Raid
devices:
- /dev/disk/by-id/ata-WDC_WD10SPZX-80Z10T2_WD-WX41A49H9FT4
- /dev/disk/by-id/ata-WDC_WD10SPZX-80Z10T2_WD-WXL1A49KPYFD`; // len: 257, pos: 43
let result = await parseSetup(content1);
assert.strictEqual(vscode_languageserver_types_1.MarkupContent.is(result.contents), true);
assert.strictEqual(result.contents.value, `#### no\\_proxy \\(list of strings\\):\n\nSource: [${testHelper_1.SCHEMA_ID}](file:///${testHelper_1.SCHEMA_ID})`);
const content2 = `ignition:
proxy:
no_proxy:
- 10.10.10.10
- service.local
storage:
raid:
- name: Raid
devices:
- /dev/disk/by-id/ata-WDC_WD|1|0SPZX-80Z10T2_WD-WX41A49H9FT4
- /dev/disk/by-id/ata-WDC_WD10SPZX-80Z10T2_WD-WXL1A49KPYFD`; // len: 257, pos: 160
result = await parseSetup(content2);
assert.strictEqual(vscode_languageserver_types_1.MarkupContent.is(result.contents), true);
assert.strictEqual(result.contents.value, `#### devices \\(list of strings\\):\n\nSource: [${testHelper_1.SCHEMA_ID}](file:///${testHelper_1.SCHEMA_ID})`);
});
it('Hover on refs node', async () => {
schemaProvider.addSchema(testHelper_1.SCHEMA_ID, {
type: 'object',
additionalProperties: false,
properties: {
title: {
type: 'string',
description: 'Title of this file',
},
refs: {
type: 'object',
},
users: {
type: 'array',
items: {
type: 'object',
properties: {
name: {
type: 'string',
description: 'Name of the user',
},
place: {
type: 'string',
description: 'Place of residence',
},
},
},
},
},
});
const content = `title: meetup
refs:
place: &default_place NYC
users:
- name: foo
place: SFC
- name: bar
|p|lace: *default_place`;
const result = await parseSetup(content);
assert.strictEqual(vscode_languageserver_types_1.MarkupContent.is(result.contents), true);
assert.strictEqual(result.contents.value, `Place of residence\n\nSource: [${testHelper_1.SCHEMA_ID}](file:///${testHelper_1.SCHEMA_ID})`);
});
it('Hover on null property', async () => {
schemaProvider.addSchema(testHelper_1.SCHEMA_ID, {
type: 'object',
properties: {
childObject: {
type: 'object',
description: 'should return this description',
},
},
});
const content = 'c|h|ildObject: \n'; // len: 14, pos: 1
const result = await parseSetup(content);
assert.strictEqual(vscode_languageserver_types_1.MarkupContent.is(result.contents), true);
assert.strictEqual(result.contents.value, `should return this description\n\nSource: [${testHelper_1.SCHEMA_ID}](file:///${testHelper_1.SCHEMA_ID})`);
});
it('hover on value and its description has multiline, indentation and special string', async () => {
(() => {
languageSettingsSetup = new serviceSetup_1.ServiceSetup()
.withHover()
.withIndentation(' ')
.withSchemaFileMatch({
uri: 'http://google.com',
fileMatch: ['bad-schema.yaml'],
});
const { languageHandler: langHandler, yamlSettings: settings, telemetry: testTelemetry, schemaProvider: testSchemaProvider, } = (0, testHelper_1.setupLanguageService)(languageSettingsSetup.languageSettings);
languageHandler = langHandler;
yamlSettings = settings;
telemetry = testTelemetry;
schemaProvider = testSchemaProvider;
})();
//https://github.com/redhat-developer/vscode-yaml/issues/886
schemaProvider.addSchema(testHelper_1.SCHEMA_ID, {
type: 'object',
title: 'Person',
properties: {
firstName: {
type: 'string',
description: 'At the top level my_var is shown properly.\n\n Issue with my_var2\n here my_var3',
},
},
});
const content = 'fi|r|stName: '; // len: 12, pos: 1
const result = await parseSetup(content);
assert.strictEqual(vscode_languageserver_types_1.MarkupContent.is(result.contents), true);
assert.strictEqual(result.contents.value, `#### Person\n\nAt the top level my\\_var is shown properly\\.\n\n  Issue with my\\_var2\n\n   here my\\_var3\n\nSource: [${testHelper_1.SCHEMA_ID}](file:///${testHelper_1.SCHEMA_ID})`);
});
it('Hover displays enum descriptions if present', async () => {
schemaProvider.addSchema(testHelper_1.SCHEMA_ID, {
type: 'object',
properties: {
animal: {
type: 'string',
description: 'should return this description',
enum: ['cat', 'dog', 'non'],
enumDescriptions: ['', 'Canis familiaris'],
},
},
});
const content = 'animal:\n ca|t|'; // len: 13, pos: 12
const result = await parseSetup(content);
assert.strictEqual(vscode_languageserver_types_1.MarkupContent.is(result.contents), true);
assert.strictEqual(result.contents.kind, 'markdown');
assert.strictEqual(result.contents.value, `should return this description
Allowed Values:
* \`cat\`
* \`dog\`: Canis familiaris
* \`non\`
Source: [${testHelper_1.SCHEMA_ID}](file:///${testHelper_1.SCHEMA_ID})`);
});
it('Hover works on examples', async () => {
schemaProvider.addSchema(testHelper_1.SCHEMA_ID, {
type: 'object',
properties: {
animal: {
type: 'string',
description: 'should return this description',
enum: ['cat', 'dog'],
examples: [
'cat',
{
animal: {
type: 'dog',
},
},
],
},
},
});
const content = 'animal:\n ca|t|'; // len: 13, pos: 12
const result = await parseSetup(content);
assert.strictEqual(vscode_languageserver_types_1.MarkupContent.is(result.contents), true);
assert.strictEqual(result.contents.kind, 'markdown');
assert.strictEqual(result.contents.value, `should return this description
Allowed Values:
* \`cat\`
* \`dog\`
Example:
\`\`\`yaml
cat
\`\`\`
Example:
\`\`\`yaml
animal:
type: dog
\`\`\`
Source: [${testHelper_1.SCHEMA_ID}](file:///${testHelper_1.SCHEMA_ID})`);
});
it('Hover on property next value on null', async () => {
schemaProvider.addSchema(testHelper_1.SCHEMA_ID, {
type: 'object',
properties: {
childObject: {
type: 'object',
description: 'childObject description',
properties: {
prop: {
type: 'string',
description: 'should return this description',
},
},
},
},
});
const content = 'childObject:\r\n |p|rop:\r\n '; // len: 25, pos: 16
const result = await parseSetup(content);
assert.strictEqual(vscode_languageserver_types_1.MarkupContent.is(result.contents), true);
assert.strictEqual(result.contents.value, `should return this description\n\nSource: [${testHelper_1.SCHEMA_ID}](file:///${testHelper_1.SCHEMA_ID})`);
});
it('should work with bad schema', async () => {
const doc = (0, testHelper_1.setupSchemaIDTextDocument)('foo:\n bar', 'bad-schema.yaml');
yamlSettings.documents = new yamlSettings_1.TextDocumentTestManager();
yamlSettings.documents.set(doc);
const result = await languageHandler.hoverHandler({
position: vscode_languageserver_types_1.Position.create(0, 1),
textDocument: doc,
});
(0, chai_1.expect)(result).to.be.null;
});
});
describe('Hover on anyOf', () => {
it('should show all matched schemas in anyOf', async () => {
schemaProvider.addSchema(testHelper_1.SCHEMA_ID, {
title: 'The Root',
description: 'Root Object',
type: 'object',
properties: {
child: {
title: 'Child',
anyOf: [
{
$ref: '#/definitions/FirstChoice',
},
{
$ref: '#/definitions/SecondChoice',
},
],
},
},
required: ['child'],
additionalProperties: false,
definitions: {
FirstChoice: {
title: 'FirstChoice',
description: 'The first choice',
type: 'object',
properties: {
choice: {
title: 'Choice',
default: 'first',
enum: ['first'],
type: 'string',
},
property_a: {
title: 'Property A',
type: 'string',
},
},
required: ['property_a'],
},
SecondChoice: {
title: 'SecondChoice',
description: 'The second choice',
type: 'object',
properties: {
choice: {
title: 'Choice',
default: 'second',
enum: ['second'],
type: 'string',
},
property_b: {
title: 'Property B',
type: 'string',
},
},
required: ['property_b'],
},
},
});
let content = 'ch|i|ld:';
let result = await parseSetup(content);
assert.strictEqual(vscode_languageserver_types_1.MarkupContent.is(result.contents), true);
assert.strictEqual(result.contents.value, `#### FirstChoice || SecondChoice\n\nThe first choice || The second choice\n\nSource: [${testHelper_1.SCHEMA_ID}](file:///${testHelper_1.SCHEMA_ID})`);
(0, chai_1.expect)(telemetry.messages).to.be.empty;
//use case 1:
content = 'ch|i|ld: \n property_a: test';
result = await parseSetup(content);
assert.strictEqual(vscode_languageserver_types_1.MarkupContent.is(result.contents), true);
assert.strictEqual(result.contents.value, `#### FirstChoice\n\nThe first choice\n\nSource: [${testHelper_1.SCHEMA_ID}](file:///${testHelper_1.SCHEMA_ID})`);
(0, chai_1.expect)(telemetry.messages).to.be.empty;
//use case 2:
content = 'ch|i|ld: \n property_b: test';
result = await parseSetup(content);
assert.strictEqual(vscode_languageserver_types_1.MarkupContent.is(result.contents), true);
assert.strictEqual(result.contents.value, `#### SecondChoice\n\nThe second choice\n\nSource: [${testHelper_1.SCHEMA_ID}](file:///${testHelper_1.SCHEMA_ID})`);
(0, chai_1.expect)(telemetry.messages).to.be.empty;
});
});
describe('Bug fixes', () => {
it('should convert binary data correctly', async () => {
const content = 'foo: [ !!binary R0lG|O|DlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5OTk6enp56enmleECcgggoBADs= ]\n'; // len: 107, pos: 20
const result = await parseSetup(content);
(0, chai_1.expect)(telemetry.messages).to.be.empty;
(0, chai_1.expect)(result).to.be.null;
});
});
});
//# sourceMappingURL=hover.test.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
export {};

View File

@@ -0,0 +1,293 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/*---------------------------------------------------------------------------------------------
* Copyright (c) Red Hat. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
const testHelper_1 = require("./utils/testHelper");
const assert = require("assert");
const vscode_languageserver_types_1 = require("vscode-languageserver-types");
const serviceSetup_1 = require("./utils/serviceSetup");
const yamlSettings_1 = require("../src/yamlSettings");
// Defines a Mocha test describe to group tests of similar kind together
describe('Kubernetes Integration Tests', () => {
let languageSettingsSetup;
let languageHandler;
let validationHandler;
let yamlSettings;
before(() => {
const uri = 'https://raw.githubusercontent.com/yannh/kubernetes-json-schema/master/v1.22.4-standalone-strict/all.json';
const fileMatch = ['*.yml', '*.yaml'];
languageSettingsSetup = new serviceSetup_1.ServiceSetup()
.withHover()
.withValidate()
.withCompletion()
.withSchemaFileMatch({
fileMatch,
uri,
})
.withKubernetes();
const { validationHandler: valHandler, languageHandler: langHandler, yamlSettings: settings, } = (0, testHelper_1.setupLanguageService)(languageSettingsSetup.languageSettings);
validationHandler = valHandler;
languageHandler = langHandler;
yamlSettings = settings;
});
// Tests for validator
describe('Yaml Validation with kubernetes', function () {
function parseSetup(content) {
const testTextDocument = (0, testHelper_1.setupTextDocument)(content);
yamlSettings.documents = new yamlSettings_1.TextDocumentTestManager();
yamlSettings.documents.set(testTextDocument);
yamlSettings.specificValidatorPaths = ['*.yml', '*.yaml'];
return validationHandler.validateTextDocument(testTextDocument);
}
//Validating basic nodes
describe('Test that validation does not throw errors', function () {
it('Basic test', (done) => {
const content = 'apiVersion: v1';
const validator = parseSetup(content);
validator
.then(function (result) {
assert.equal(result.length, 0);
})
.then(done, done);
});
it('Basic test on nodes with children', (done) => {
const content = 'metadata:\n name: hello';
const validator = parseSetup(content);
validator
.then(function (result) {
assert.equal(result.length, 0);
})
.then(done, done);
});
it('Advanced test on nodes with children', (done) => {
const content = 'apiVersion: v1\nmetadata:\n name: test1';
const validator = parseSetup(content);
validator
.then(function (result) {
assert.equal(result.length, 0);
})
.then(done, done);
});
it('Type string validates under children', (done) => {
const content = 'apiVersion: v1\nkind: Pod\nmetadata:\n resourceVersion: test';
const validator = parseSetup(content);
validator
.then(function (result) {
assert.equal(result.length, 0);
})
.then(done, done);
});
describe('Type tests', function () {
it('Type String does not error on valid node', (done) => {
const content = 'apiVersion: v1';
const validator = parseSetup(content);
validator
.then(function (result) {
assert.equal(result.length, 0);
})
.then(done, done);
});
it('Type Boolean does not error on valid node', (done) => {
const content = 'readOnlyRootFilesystem: false';
const validator = parseSetup(content);
validator
.then(function (result) {
assert.equal(result.length, 0);
})
.then(done, done);
});
it('Type Number does not error on valid node', (done) => {
const content = 'generation: 5';
const validator = parseSetup(content);
validator
.then(function (result) {
assert.equal(result.length, 0);
})
.then(done, done);
});
it('Type Object does not error on valid node', (done) => {
const content = 'metadata:\n clusterName: tes';
const validator = parseSetup(content);
validator
.then(function (result) {
assert.equal(result.length, 0);
})
.then(done, done);
});
it('Type Array does not error on valid node', (done) => {
const content = 'items:\n - apiVersion: v1';
const validator = parseSetup(content);
validator
.then(function (result) {
assert.equal(result.length, 0);
})
.then(done, done);
});
});
});
/**
* Removed these tests because the schema pulled in from
* https://github.com/redhat-developer/yaml-language-server/pull/108
* No longer has those types of validation
*/
// describe('Test that validation DOES throw errors', function () {
// it('Error when theres no value for a node', done => {
// const content = 'apiVersion:';
// const validator = parseSetup(content);
// validator.then(function (result){
// assert.notEqual(result.length, 0);
// }).then(done, done);
// });
// it('Error on incorrect value type (number)', done => {
// const content = 'apiVersion: 1000';
// const validator = parseSetup(content);
// validator.then(function (result){
// assert.notEqual(result.length, 0);
// }).then(done, done);
// });
// it('Error on incorrect value type (boolean)', done => {
// const content = 'apiVersion: False';
// const validator = parseSetup(content);
// validator.then(function (result){
// assert.notEqual(result.length, 0);
// }).then(done, done);
// });
// it('Error on incorrect value type (string)', done => {
// const content = 'isNonResourceURL: hello_world';
// const validator = parseSetup(content);
// validator.then(function (result){
// assert.notEqual(result.length, 0);
// }).then(done, done);
// });
// it('Error on incorrect value type (object)', done => {
// const content = 'apiVersion: v1\nkind: Pod\nmetadata:\n name: False';
// const validator = parseSetup(content);
// validator.then(function (result){
// assert.notEqual(result.length, 0);
// }).then(done, done);
// });
// it('Error on incorrect value type in multiple yaml documents', done => {
// const content = '---\napiVersion: v1\n...\n---\napiVersion: False\n...';
// const validator = parseSetup(content);
// validator.then(function (result){
// assert.notEqual(result.length, 0);
// }).then(done, done);
// });
// it('Property error message should be \"Property unknown_node is not allowed.\" when property is not allowed ', done => {
// const content = 'unknown_node: test';
// const validator = parseSetup(content);
// validator.then(function (result){
// assert.equal(result.length, 1);
// assert.equal(result[0].message, 'Property unknown_node is not allowed.');
// }).then(done, done);
// });
// });
});
describe('yamlCompletion with kubernetes', function () {
describe('doComplete', function () {
function parseSetup(content, position) {
const testTextDocument = (0, testHelper_1.setupTextDocument)(content);
yamlSettings.documents = new yamlSettings_1.TextDocumentTestManager();
yamlSettings.documents.set(testTextDocument);
return languageHandler.completionHandler({
position: testTextDocument.positionAt(position),
textDocument: testTextDocument,
});
}
/**
* Known issue: https://github.com/redhat-developer/yaml-language-server/issues/51
*/
// it('Autocomplete on root node without word', done => {
// const content = '';
// const completion = parseSetup(content, 0);
// completion.then(function (result){
// assert.notEqual(result.items.length, 0);
// }).then(done, done);
// });
// it('Autocomplete on root node with word', done => {
// const content = 'api';
// const completion = parseSetup(content, 6);
// completion.then(function (result){
// assert.notEqual(result.items.length, 0);
// }).then(done, done);
// });
/**
* Removed these tests because the schema pulled in from
* https://github.com/redhat-developer/yaml-language-server/pull/108
* No longer has those types of completion
*/
// it('Autocomplete on default value (without value content)', done => {
// const content = 'apiVersion: ';
// const completion = parseSetup(content, 10);
// completion.then(function (result){
// assert.notEqual(result.items.length, 0);
// }).then(done, done);
// });
it('Autocomplete on default value (with value content)', (done) => {
const content = 'apiVersion: v1\nkind: Depl';
const completion = parseSetup(content, 19);
completion
.then(function (result) {
assert.notEqual(result.items.length, 0);
})
.then(done, done);
});
it('Autocomplete on boolean value (without value content)', (done) => {
const content = 'spec:\n allowPrivilegeEscalation: ';
const completion = parseSetup(content, 38);
completion
.then(function (result) {
assert.equal(result.items.length, 2);
})
.then(done, done);
});
it('Autocomplete on boolean value (with value content)', (done) => {
const content = 'spec:\n allowPrivilegeEscalation: fal';
const completion = parseSetup(content, 43);
completion
.then(function (result) {
assert.equal(result.items.length, 2);
})
.then(done, done);
});
it('Autocomplete key in middle of file', (done) => {
const content = 'metadata:\n nam';
const completion = parseSetup(content, 14);
completion
.then(function (result) {
assert.notEqual(result.items.length, 0);
})
.then(done, done);
});
it('Autocomplete key in middle of file 2', (done) => {
const content = 'metadata:\n name: test\n cluster';
const completion = parseSetup(content, 31);
completion
.then(function (result) {
assert.notEqual(result.items.length, 0);
})
.then(done, done);
});
});
});
describe('yamlHover with kubernetes', function () {
function parseSetup(content, offset) {
const testTextDocument = (0, testHelper_1.setupTextDocument)(content);
yamlSettings.documents = new yamlSettings_1.TextDocumentTestManager();
yamlSettings.documents.set(testTextDocument);
return languageHandler.hoverHandler({
position: testTextDocument.positionAt(offset),
textDocument: testTextDocument,
});
}
it('Hover on incomplete kubernetes document', async () => {
const content = 'apiVersion: v1\nmetadata:\n name: test\nkind: Deployment\nspec:\n ';
const hover = await parseSetup(content, 58);
assert.strictEqual(vscode_languageserver_types_1.MarkupContent.is(hover?.contents), true);
assert.strictEqual((hover?.contents).value, '');
});
});
});
//# sourceMappingURL=integration.test.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
export {};

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
export {};

View File

@@ -0,0 +1,117 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/*---------------------------------------------------------------------------------------------
* Copyright (c) Red Hat. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
const path = require("path");
const testHelper_1 = require("./utils/testHelper");
const assert = require("assert");
const serviceSetup_1 = require("./utils/serviceSetup");
const vscode_languageserver_types_1 = require("vscode-languageserver-types");
const yamlSettings_1 = require("../src/yamlSettings");
/**
* Setup the schema we are going to use with the language settings
*/
// Defines a Mocha test describe to group tests of similar kind together
describe('Multiple Documents Validation Tests', () => {
let languageSettingsSetup;
let languageHandler;
let validationHandler;
let languageService;
let yamlSettings;
before(() => {
const uri = (0, testHelper_1.toFsPath)(path.join(__dirname, './fixtures/customMultipleSchemaSequences.json'));
const fileMatch = ['*.yml', '*.yaml'];
languageSettingsSetup = new serviceSetup_1.ServiceSetup()
.withHover()
.withIndentation(' ')
.withValidate()
.withSchemaFileMatch({
fileMatch,
uri,
})
.withCustomTags(['!Test', '!Ref sequence']);
const { languageService: langService, validationHandler: valHandler, languageHandler: langHandler, yamlSettings: settings, } = (0, testHelper_1.setupLanguageService)(languageSettingsSetup.languageSettings);
languageService = langService;
validationHandler = valHandler;
languageHandler = langHandler;
yamlSettings = settings;
});
describe('Multiple Documents Validation', function () {
function validatorSetup(content) {
const testTextDocument = (0, testHelper_1.setupTextDocument)(content);
languageService.configure(languageSettingsSetup.languageSettings);
return validationHandler.validateTextDocument(testTextDocument);
}
function hoverSetup(content, position) {
const testTextDocument = (0, testHelper_1.setupTextDocument)(content);
languageService.configure(languageSettingsSetup.languageSettings);
yamlSettings.documents = new yamlSettings_1.TextDocumentTestManager();
yamlSettings.documents.set(testTextDocument);
return languageHandler.hoverHandler({
position: testTextDocument.positionAt(position),
textDocument: testTextDocument,
});
}
it('Should validate multiple documents', (done) => {
const content = `
name: jack
age: 22
---
cwd: test
`;
const validator = validatorSetup(content);
validator
.then((result) => {
assert.equal(result.length, 0);
})
.then(done, done);
});
it('Should find errors in both documents', (done) => {
const content = `name1: jack
age: asd
---
cwd: False`;
const validator = validatorSetup(content);
validator
.then(function (result) {
assert.equal(result.length, 3);
})
.then(done, done);
});
it('Should find errors in first document', (done) => {
const content = `name: jack
age: age
---
cwd: test`;
const validator = validatorSetup(content);
validator
.then(function (result) {
assert.equal(result.length, 1);
})
.then(done, done);
});
it('Should find errors in second document', (done) => {
const content = `name: jack
age: 22
---
cwd: False
`;
const validator = validatorSetup(content);
validator
.then(function (result) {
assert.equal(result.length, 1);
})
.then(done, done);
});
it('Should hover in first document', async () => {
const content = 'name: jack\nage: 22\n---\ncwd: False';
const result = await hoverSetup(content, 1 + content.indexOf('age'));
assert.strictEqual(vscode_languageserver_types_1.MarkupContent.is(result.contents), true);
assert.strictEqual(result.contents.kind, 'markdown');
assert.strictEqual(result.contents.value, 'The age of this person');
});
});
});
//# sourceMappingURL=multipleDocuments.test.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"multipleDocuments.test.js","sourceRoot":"","sources":["../../../test/multipleDocuments.test.ts"],"names":[],"mappings":";;AAAA;;;gGAGgG;AAChG,6BAA6B;AAC7B,mDAAuF;AACvF,iCAAiC;AACjC,uDAAoD;AACpD,6EAA+E;AAC/E,sDAA6E;AAK7E;;GAEG;AAEH,wEAAwE;AACxE,QAAQ,CAAC,qCAAqC,EAAE,GAAG,EAAE;IACnD,IAAI,qBAAmC,CAAC;IACxC,IAAI,eAAiC,CAAC;IACtC,IAAI,iBAAoC,CAAC;IACzC,IAAI,eAAgC,CAAC;IACrC,IAAI,YAA2B,CAAC;IAEhC,MAAM,CAAC,GAAG,EAAE;QACV,MAAM,GAAG,GAAG,IAAA,qBAAQ,EAAC,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,+CAA+C,CAAC,CAAC,CAAC;QAC5F,MAAM,SAAS,GAAG,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;QACtC,qBAAqB,GAAG,IAAI,2BAAY,EAAE;aACvC,SAAS,EAAE;aACX,eAAe,CAAC,IAAI,CAAC;aACrB,YAAY,EAAE;aACd,mBAAmB,CAAC;YACnB,SAAS;YACT,GAAG;SACJ,CAAC;aACD,cAAc,CAAC,CAAC,OAAO,EAAE,eAAe,CAAC,CAAC,CAAC;QAC9C,MAAM,EACJ,eAAe,EAAE,WAAW,EAC5B,iBAAiB,EAAE,UAAU,EAC7B,eAAe,EAAE,WAAW,EAC5B,YAAY,EAAE,QAAQ,GACvB,GAAG,IAAA,iCAAoB,EAAC,q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CAAC,OAAO,EAAE,CAAC,GAAG,OAAO,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC;YAErE,MAAM,CAAC,WAAW,CAAC,2CAAa,CAAC,EAAE,CAAC,MAAM,CAAC,QAAQ,CAAC,EAAE,IAAI,CAAC,CAAC;YAC5D,MAAM,CAAC,WAAW,CAAE,MAAM,CAAC,QAA0B,CAAC,IAAI,EAAE,UAAU,CAAC,CAAC;YACxE,MAAM,CAAC,WAAW,CAAE,MAAM,CAAC,QAA0B,CAAC,KAAK,EAAE,wBAAwB,CAAC,CAAC;QACzF,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"}

View File

@@ -0,0 +1 @@
export {};

View File

@@ -0,0 +1,110 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/*---------------------------------------------------------------------------------------------
* Copyright (c) Red Hat. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
const objects_1 = require("../src/languageservice/utils/objects");
const assert = require("assert");
describe('Object Equals Tests', () => {
describe('Equals', function () {
it('Both are null', () => {
const one = null;
const other = null;
const result = (0, objects_1.equals)(one, other);
assert.equal(result, true);
});
it('One is null the other is true', () => {
const one = null;
const other = true;
const result = (0, objects_1.equals)(one, other);
assert.equal(result, false);
});
it('One is string the other is boolean', () => {
const one = 'test';
const other = false;
const result = (0, objects_1.equals)(one, other);
assert.equal(result, false);
});
it('One is not object', () => {
const one = 'test';
const other = false;
const result = (0, objects_1.equals)(one, other);
assert.equal(result, false);
});
it('One is array the other is not', () => {
const one = new Proxy([], {});
const other = Object.keys({
1: '2',
2: '3',
});
const result = (0, objects_1.equals)(one, other);
assert.equal(result, false);
});
it('Both are arrays of different length', () => {
const one = [1, 2, 3];
const other = [1, 2, 3, 4];
const result = (0, objects_1.equals)(one, other);
assert.equal(result, false);
});
it('Both are arrays of same elements but in different order', () => {
const one = [1, 2, 3];
const other = [3, 2, 1];
const result = (0, objects_1.equals)(one, other);
assert.equal(result, false);
});
it('Arrays that are equal', () => {
const one = [1, 2, 3];
const other = [1, 2, 3];
const result = (0, objects_1.equals)(one, other);
assert.equal(result, true);
});
it('Objects that are equal', () => {
const one = {
test: 1,
};
const other = {
test: 1,
};
const result = (0, objects_1.equals)(one, other);
assert.equal(result, true);
});
it('Objects that have same keys but different values', () => {
const one = {
test: 1,
};
const other = {
test: 5,
};
const result = (0, objects_1.equals)(one, other);
assert.equal(result, false);
});
it('Objects that have different keys', () => {
const one = {
test_one: 1,
};
const other = {
test_other: 1,
};
const result = (0, objects_1.equals)(one, other);
assert.equal(result, false);
});
});
});
describe('Telemetry message conversion test', () => {
it('null values should not cause problems', () => {
assert.doesNotThrow(() => (0, objects_1.convertErrorToTelemetryMsg)(null));
});
it('should convert errors with stack correctly', () => {
const e = new Error('Test message');
const msg = (0, objects_1.convertErrorToTelemetryMsg)(e);
assert.equal(msg, e.stack);
});
it('should convert errors with no stack correctly', () => {
const e = new Error('Test message');
e.stack = null;
const msg = (0, objects_1.convertErrorToTelemetryMsg)(e);
assert.equal(msg, e.toString());
});
});
//# sourceMappingURL=objects.test.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"objects.test.js","sourceRoot":"","sources":["../../../test/objects.test.ts"],"names":[],"mappings":";;AAAA;;;gGAGgG;AAChG,kEAA0F;AAC1F,iCAAiC;AAEjC,QAAQ,CAAC,qBAAqB,EAAE,GAAG,EAAE;IACnC,QAAQ,CAAC,QAAQ,EAAE;QACjB,EAAE,CAAC,eAAe,EAAE,GAAG,EAAE;YACvB,MAAM,GAAG,GAAG,IAAI,CAAC;YACjB,MAAM,KAAK,GAAG,IAAI,CAAC;YAEnB,MAAM,MAAM,GAAG,IAAA,gBAAM,EAAC,GAAG,EAAE,KAAK,CAAC,CAAC;YAClC,MAAM,CAAC,KAAK,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;QAC7B,CAAC,CAAC,CAAC;QAEH,EAAE,CAAC,+BAA+B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,CAAC,KAAK,CAAC,CAAC;IAC7B,CAAC,CAAC,CAAC;IAEH,EAAE,CAAC,+CAA+C,EAAE,GAAG,EAAE;QACvD,MAAM,CAAC,GAAU,IAAI,KAAK,CAAC,cAAc,CAAC,CAAC;QAC3C,CAAC,CAAC,KAAK,GAAG,IAAI,CAAC;QACf,MAAM,GAAG,GAAG,IAAA,oCAA0B,EAAC,CAAC,CAAC,CAAC;QAC1C,MAAM,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,CAAC,QAAQ,EAAE,CAAC,CAAC;IAClC,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"}

View File

@@ -0,0 +1 @@
export {};

View File

@@ -0,0 +1,223 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const assert = require("assert");
const path_1 = require("path");
const paths_1 = require("../src/languageservice/utils/paths");
const vscode_uri_1 = require("vscode-uri");
class TestWorkspace {
constructor(workspaceFolders, workspaceRoot) {
this.folders = workspaceFolders;
this.root = vscode_uri_1.URI.parse(workspaceRoot);
}
resolve(relPath) {
return (0, paths_1.relativeToAbsolutePath)(this.folders, this.root, relPath);
}
}
const ws1 = new TestWorkspace([
{
uri: 'file:///home/aFolder/',
name: 'aFolder',
},
], 'file:///home/aFolder/');
const ws2 = new TestWorkspace([
{
uri: 'file:///usr/testuser/projects/workspace/folder-1/',
name: 'folder-1',
},
{
uri: 'file:///usr/testuser/projects/workspace/folder-2/',
name: 'folder-2',
},
{
uri: 'file:///usr/testuser/projects/workspace/folder-3/',
name: 'folder-3',
},
], 'file:///usr/testuser/projects/workspace/');
const ws3 = new TestWorkspace([
{
uri: 'file:///c%3A/Users/testuser/dev/carrots',
name: 'carrots',
},
{
uri: 'file:///c%3A/Users/testuser/dev/potatoes',
name: 'potatoes',
},
], 'file:///c%3A/Users/testuser/dev/potatoes');
const ws4 = new TestWorkspace([
{
uri: 'file:///c%3A/Users/testuser/dev/test',
name: 'test',
},
{
uri: 'file:///c%3A/Users/testuser/dev/test2',
name: 'test2',
},
], 'file:///c%3A/Users/testuser/dev/test2');
const checkBadPath = (path) => {
it('Rejects "' + path + '"', () => {
assert(!(0, paths_1.isRelativePath)(path));
});
};
const checkGoodPath = (path, expect1, expect2, expect3) => {
describe('Relative path = "' + path + '"', () => {
it('Recognises relative path', () => {
assert((0, paths_1.isRelativePath)(path));
});
it('Resolves relative path in single-root workspace', () => {
assert.equal(ws1.resolve(path), expect1);
});
it('Resolves relative path in multi-root workspace', () => {
assert.equal(ws2.resolve(path), expect2);
});
it('Resolves relative path in multi-root nested workspace', () => {
assert.equal(ws3.resolve(path), expect3);
});
});
};
describe('File path tests', () => {
describe('Recognises not relative paths', () => {
checkBadPath((0, path_1.join)('/', 'file.json'));
checkBadPath((0, path_1.join)('/', 'absolutepath', 'file.json.'));
checkBadPath((0, path_1.join)('//', 'notrelativepath', 'file.json'));
checkBadPath((0, path_1.join)('C:', 'notrelativepath', 'file.json'));
checkBadPath((0, path_1.join)('directory.json', '/'));
checkBadPath((0, path_1.join)('.', 'dir', 'subdir', '/'));
});
describe('Recognises and correctly resolves relative paths', () => {
checkGoodPath('file.json', 'file:///home/aFolder/file.json', 'file:///usr/testuser/projects/workspace/file.json', 'file:///c%3A/Users/testuser/dev/potatoes/file.json');
checkGoodPath('file.long.extension.json', 'file:///home/aFolder/file.long.extension.json', 'file:///usr/testuser/projects/workspace/file.long.extension.json', 'file:///c%3A/Users/testuser/dev/potatoes/file.long.extension.json');
checkGoodPath((0, path_1.join)('.', 'file.json'), 'file:///home/aFolder/file.json', 'file:///usr/testuser/projects/workspace/file.json', 'file:///c%3A/Users/testuser/dev/potatoes/file.json');
checkGoodPath((0, path_1.join)('.', 'folder', 'file.json'), 'file:///home/aFolder/folder/file.json', 'file:///usr/testuser/projects/workspace/folder/file.json', 'file:///c%3A/Users/testuser/dev/potatoes/folder/file.json');
checkGoodPath((0, path_1.join)('.', 'long', 'path', 'to', 'file.json'), 'file:///home/aFolder/long/path/to/file.json', 'file:///usr/testuser/projects/workspace/long/path/to/file.json', 'file:///c%3A/Users/testuser/dev/potatoes/long/path/to/file.json');
checkGoodPath((0, path_1.join)('..', 'file.json'), 'file:///home/file.json', 'file:///usr/testuser/projects/file.json', 'file:///c%3A/Users/testuser/dev/file.json');
checkGoodPath((0, path_1.join)('.', 'relativepath', '..', 'file.json'), 'file:///home/aFolder/file.json', 'file:///usr/testuser/projects/workspace/file.json', 'file:///c%3A/Users/testuser/dev/potatoes/file.json');
checkGoodPath((0, path_1.join)('..', '..', 'relative', 'path', 'file.json'), 'file:///relative/path/file.json', 'file:///usr/testuser/relative/path/file.json', 'file:///c%3A/Users/testuser/relative/path/file.json');
checkGoodPath((0, path_1.join)('..', '..', 'relative', '@path', 'file.json'), 'file:///relative/%40path/file.json', 'file:///usr/testuser/relative/%40path/file.json', 'file:///c%3A/Users/testuser/relative/%40path/file.json');
describe('Relative path = a workspace folder', () => {
const path1 = (0, path_1.join)('aFolder', 'file.json');
const path2 = (0, path_1.join)('folder-2', 'file.json');
const path3 = (0, path_1.join)('carrots', 'file.json');
const path4 = (0, path_1.join)('test', 'test.json');
it('Recognises relative path "' + path1 + '"', () => {
assert((0, paths_1.isRelativePath)(path1));
});
it('Resolves "' + path1 + '" in single-root workspace', () => {
assert.equal(ws1.resolve(path1), 'file:///home/aFolder/file.json');
});
it('Resolves "' + path2 + '" in multi-root workspace', () => {
assert.equal(ws2.resolve(path2), 'file:///usr/testuser/projects/workspace/folder-2/file.json');
});
it('Resolves "' + path3 + '" in multi-root nested workspace', () => {
assert.equal(ws3.resolve(path3), 'file:///c%3A/Users/testuser/dev/carrots/file.json');
});
it('Resolves "' + path4 + '" in multi-root nested workspace', () => {
assert.equal(ws4.resolve(path4), 'file:///c%3A/Users/testuser/dev/test/test.json');
});
});
describe('Path with mixed delimiters (Windows only)', () => {
const path = 'some/strange\\but/functional\\path\\file.json';
it('Recognises relative path "' + path + '"', function () {
if (process.platform !== 'win32') {
this.skip();
}
else {
assert((0, paths_1.isRelativePath)(path));
}
});
it('Resolves "' + path + '" in single-root workspace', function () {
if (process.platform !== 'win32') {
this.skip();
}
else {
assert.equal(ws1.resolve(path), 'file:///home/aFolder/some/strange/but/functional/path/file.json');
}
});
it('Resolves "' + path + '" in multi-root workspace', function () {
if (process.platform !== 'win32') {
this.skip();
}
else {
assert.equal(ws2.resolve(path), 'file:///usr/testuser/projects/workspace/some/strange/but/functional/path/file.json');
}
});
it('Resolves "' + path + '" in multi-root nested workspace', function () {
if (process.platform !== 'win32') {
this.skip();
}
else {
assert.equal(ws3.resolve(path), 'file:///c%3A/Users/testuser/dev/potatoes/some/strange/but/functional/path/file.json');
}
});
});
describe('Tests for workspaceFoldersChanged', () => {
it('workspaceFolders are added correctly', () => {
const newWorkspaceFolders = (0, paths_1.workspaceFoldersChanged)(ws2.folders, {
added: [
{
name: 'folder-4',
uri: 'file:///usr/testuser/projects/workspace/folder-4/',
},
],
removed: [],
});
assert.equal(newWorkspaceFolders.length, 4);
assert.equal(newWorkspaceFolders[0].name, 'folder-1');
assert.equal(newWorkspaceFolders[0].uri, 'file:///usr/testuser/projects/workspace/folder-1/');
assert.equal(newWorkspaceFolders[1].name, 'folder-2');
assert.equal(newWorkspaceFolders[1].uri, 'file:///usr/testuser/projects/workspace/folder-2/');
assert.equal(newWorkspaceFolders[2].name, 'folder-3');
assert.equal(newWorkspaceFolders[2].uri, 'file:///usr/testuser/projects/workspace/folder-3/');
assert.equal(newWorkspaceFolders[3].name, 'folder-4');
assert.equal(newWorkspaceFolders[3].uri, 'file:///usr/testuser/projects/workspace/folder-4/');
});
it('workspaceFolders are not added if duplicate uri', () => {
const newWorkspaceFolders = (0, paths_1.workspaceFoldersChanged)(ws2.folders, {
added: [
{
name: 'folder-3',
uri: 'file:///usr/testuser/projects/workspace/folder-3/',
},
],
removed: [],
});
assert.equal(newWorkspaceFolders.length, 3);
assert.equal(newWorkspaceFolders[0].name, 'folder-1');
assert.equal(newWorkspaceFolders[0].uri, 'file:///usr/testuser/projects/workspace/folder-1/');
assert.equal(newWorkspaceFolders[1].name, 'folder-2');
assert.equal(newWorkspaceFolders[1].uri, 'file:///usr/testuser/projects/workspace/folder-2/');
assert.equal(newWorkspaceFolders[2].name, 'folder-3');
assert.equal(newWorkspaceFolders[2].uri, 'file:///usr/testuser/projects/workspace/folder-3/');
});
it('workspaceFolders are removed correctly', () => {
const newWorkspaceFolders = (0, paths_1.workspaceFoldersChanged)(ws2.folders, {
added: [],
removed: [
{
name: 'folder-3',
uri: 'file:///usr/testuser/projects/workspace/folder-3/',
},
],
});
assert.equal(newWorkspaceFolders.length, 2);
assert.equal(newWorkspaceFolders[0].name, 'folder-1');
assert.equal(newWorkspaceFolders[0].uri, 'file:///usr/testuser/projects/workspace/folder-1/');
assert.equal(newWorkspaceFolders[1].name, 'folder-2');
assert.equal(newWorkspaceFolders[1].uri, 'file:///usr/testuser/projects/workspace/folder-2/');
});
it('workspaceFolders empty event does nothing', () => {
const newWorkspaceFolders = (0, paths_1.workspaceFoldersChanged)(ws2.folders, {
added: [],
removed: [],
});
assert.equal(newWorkspaceFolders.length, 3);
assert.equal(newWorkspaceFolders[0].name, 'folder-1');
assert.equal(newWorkspaceFolders[0].uri, 'file:///usr/testuser/projects/workspace/folder-1/');
assert.equal(newWorkspaceFolders[1].name, 'folder-2');
assert.equal(newWorkspaceFolders[1].uri, 'file:///usr/testuser/projects/workspace/folder-2/');
assert.equal(newWorkspaceFolders[2].name, 'folder-3');
assert.equal(newWorkspaceFolders[2].uri, 'file:///usr/testuser/projects/workspace/folder-3/');
});
});
});
});
//# sourceMappingURL=paths.test.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
export {};

View File

@@ -0,0 +1,660 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const assert = require("assert");
const parser = require("../src/languageservice/parser/yamlParser07");
const SchemaService = require("../src/languageservice/services/yamlSchemaService");
const url = require("url");
const path = require("path");
const request_light_1 = require("request-light");
const yamlSchemaService_1 = require("../src/languageservice/services/yamlSchemaService");
const schemaUrls_1 = require("../src/languageservice/utils/schemaUrls");
const chai_1 = require("chai");
const serviceSetup_1 = require("./utils/serviceSetup");
const testHelper_1 = require("./utils/testHelper");
const src_1 = require("../src");
const vscode_languageserver_types_1 = require("vscode-languageserver-types");
const yaml_1 = require("yaml");
const modelineUtil_1 = require("../src/languageservice/services/modelineUtil");
const requestServiceMock = function (uri) {
return Promise.reject(`Resource ${uri} not found.`);
};
const workspaceContext = {
resolveRelativePath: (relativePath, resource) => {
return url.resolve(resource, relativePath);
},
};
const schemaRequestServiceForURL = (uri) => {
const headers = { 'Accept-Encoding': 'gzip, deflate' };
return (0, request_light_1.xhr)({ url: uri, followRedirects: 5, headers }).then((response) => {
return response.responseText;
}, (error) => {
return Promise.reject(error.responseText || error.toString());
});
};
describe('JSON Schema', () => {
let languageSettingsSetup;
let languageService;
beforeEach(() => {
languageSettingsSetup = new serviceSetup_1.ServiceSetup()
.withValidate()
.withCustomTags(['!Test', '!Ref sequence'])
.withSchemaFileMatch({ uri: schemaUrls_1.KUBERNETES_SCHEMA_URL, fileMatch: ['.drone.yml'] })
.withSchemaFileMatch({ uri: 'https://json.schemastore.org/drone', fileMatch: ['.drone.yml'] })
.withSchemaFileMatch({ uri: schemaUrls_1.KUBERNETES_SCHEMA_URL, fileMatch: ['test.yml'] })
.withSchemaFileMatch({ uri: 'https://json.schemastore.org/composer', fileMatch: ['test.yml'] });
const { languageService: langService } = (0, testHelper_1.setupLanguageService)(languageSettingsSetup.languageSettings);
languageService = langService;
});
it('Resolving $refs', function (testDone) {
const service = new SchemaService.YAMLSchemaService(requestServiceMock, workspaceContext);
service.setSchemaContributions({
schemas: {
'https://myschemastore/main': {
id: 'https://myschemastore/main',
type: 'object',
properties: {
child: {
$ref: 'https://myschemastore/child',
},
},
},
'https://myschemastore/child': {
id: 'https://myschemastore/child',
type: 'bool',
description: 'Test description',
},
},
});
service
.getResolvedSchema('https://myschemastore/main')
.then((solvedSchema) => {
assert.deepEqual(solvedSchema.schema.properties['child'], {
id: 'https://myschemastore/child',
type: 'bool',
description: 'Test description',
_$ref: 'https://myschemastore/child',
url: 'https://myschemastore/child',
});
})
.then(() => {
return testDone();
}, (error) => {
testDone(error);
});
});
it('Resolving $refs 2', function (testDone) {
const service = new SchemaService.YAMLSchemaService(requestServiceMock, workspaceContext);
service.setSchemaContributions({
schemas: {
'https://json.schemastore.org/swagger-2.0': {
id: 'https://json.schemastore.org/swagger-2.0',
type: 'object',
properties: {
responseValue: {
$ref: '#/definitions/jsonReference',
},
},
definitions: {
jsonReference: {
type: 'object',
required: ['$ref'],
properties: {
$ref: {
type: 'string',
},
},
},
},
},
},
});
service
.getResolvedSchema('https://json.schemastore.org/swagger-2.0')
.then((fs) => {
assert.deepEqual(fs.schema.properties['responseValue'], {
type: 'object',
required: ['$ref'],
properties: { $ref: { type: 'string' } },
_$ref: '#/definitions/jsonReference',
});
})
.then(() => {
return testDone();
}, (error) => {
testDone(error);
});
});
it('Resolving $refs 3', function (testDone) {
const service = new SchemaService.YAMLSchemaService(requestServiceMock, workspaceContext);
service.setSchemaContributions({
schemas: {
'https://myschemastore/main/schema1.json': {
id: 'https://myschemastore/schema1.json',
type: 'object',
properties: {
p1: {
$ref: 'schema2.json#/definitions/hello',
},
p2: {
$ref: './schema2.json#/definitions/hello',
},
p3: {
$ref: '/main/schema2.json#/definitions/hello',
},
},
},
'https://myschemastore/main/schema2.json': {
id: 'https://myschemastore/main/schema2.json',
definitions: {
hello: {
type: 'string',
enum: ['object'],
},
},
},
},
});
service
.getResolvedSchema('https://myschemastore/main/schema1.json')
.then((fs) => {
assert.deepEqual(fs.schema.properties['p1'], {
type: 'string',
enum: ['object'],
_$ref: 'schema2.json#/definitions/hello',
url: 'https://myschemastore/main/schema2.json',
});
assert.deepEqual(fs.schema.properties['p2'], {
type: 'string',
enum: ['object'],
_$ref: './schema2.json#/definitions/hello',
url: 'https://myschemastore/main/schema2.json',
});
assert.deepEqual(fs.schema.properties['p3'], {
type: 'string',
enum: ['object'],
_$ref: '/main/schema2.json#/definitions/hello',
url: 'https://myschemastore/main/schema2.json',
});
})
.then(() => {
return testDone();
}, (error) => {
testDone(error);
});
});
it('FileSchema', function (testDone) {
const service = new SchemaService.YAMLSchemaService(requestServiceMock, workspaceContext);
service.setSchemaContributions({
schemas: {
main: {
id: 'main',
type: 'object',
properties: {
child: {
type: 'object',
properties: {
grandchild: {
type: 'number',
description: 'Meaning of Life',
},
},
},
},
},
},
});
service
.getResolvedSchema('main')
.then((fs) => {
const section = fs.getSection(['child', 'grandchild']);
assert.equal(section.description, 'Meaning of Life');
})
.then(() => {
return testDone();
}, (error) => {
testDone(error);
});
});
it('Array FileSchema', function (testDone) {
const service = new SchemaService.YAMLSchemaService(requestServiceMock, workspaceContext);
service.setSchemaContributions({
schemas: {
main: {
id: 'main',
type: 'object',
properties: {
child: {
type: 'array',
items: {
type: 'object',
properties: {
grandchild: {
type: 'number',
description: 'Meaning of Life',
},
},
},
},
},
},
},
});
service
.getResolvedSchema('main')
.then((fs) => {
const section = fs.getSection(['child', '0', 'grandchild']);
assert.equal(section.description, 'Meaning of Life');
})
.then(() => {
return testDone();
}, (error) => {
testDone(error);
});
});
it('Missing subschema', function (testDone) {
const service = new SchemaService.YAMLSchemaService(requestServiceMock, workspaceContext);
service.setSchemaContributions({
schemas: {
main: {
id: 'main',
type: 'object',
properties: {
child: {
type: 'object',
},
},
},
},
});
service
.getResolvedSchema('main')
.then((fs) => {
const section = fs.getSection(['child', 'grandchild']);
assert.strictEqual(section, undefined);
})
.then(() => {
return testDone();
}, (error) => {
testDone(error);
});
});
it('Preloaded Schema', function (testDone) {
const service = new SchemaService.YAMLSchemaService(requestServiceMock, workspaceContext);
const id = 'https://myschemastore/test1';
const schema = {
type: 'object',
properties: {
child: {
type: 'object',
properties: {
grandchild: {
type: 'number',
description: 'Meaning of Life',
},
},
},
},
};
service.registerExternalSchema(id, ['*.json'], schema);
service
.getSchemaForResource('test.json', undefined)
.then((schema) => {
const section = schema.getSection(['child', 'grandchild']);
assert.equal(section.description, 'Meaning of Life');
})
.then(() => {
return testDone();
}, (error) => {
testDone(error);
});
});
it('Schema has url', async () => {
const service = new SchemaService.YAMLSchemaService(requestServiceMock, workspaceContext);
const id = 'https://myschemastore/test1';
const schema = {
type: 'object',
properties: {
child: {
type: 'object',
properties: {
grandchild: {
type: 'number',
description: 'Meaning of Life',
},
},
},
},
};
service.registerExternalSchema(id, ['*.json'], schema);
const result = await service.getSchemaForResource('test.json', undefined);
(0, chai_1.expect)(result.schema.url).equal(id);
});
it('Null Schema', function (testDone) {
const service = new SchemaService.YAMLSchemaService(requestServiceMock, workspaceContext);
service
.getSchemaForResource('test.json', undefined)
.then((schema) => {
assert.equal(schema, null);
})
.then(() => {
return testDone();
}, (error) => {
testDone(error);
});
});
it('Schema not found', function (testDone) {
const service = new SchemaService.YAMLSchemaService(requestServiceMock, workspaceContext);
service
.loadSchema('test.json')
.then((schema) => {
assert.notEqual(schema.errors.length, 0);
})
.then(() => {
return testDone();
}, (error) => {
testDone(error);
});
});
it('Schema with non uri registers correctly', function (testDone) {
const service = new SchemaService.YAMLSchemaService(requestServiceMock, workspaceContext);
const non_uri = 'non_uri';
service.registerExternalSchema(non_uri, ['*.yml', '*.yaml'], {
properties: {
test_node: {
description: 'my test_node description',
enum: ['test 1', 'test 2'],
},
},
});
service.getResolvedSchema(non_uri).then((schema) => {
assert.notEqual(schema, undefined);
testDone();
});
});
it('Modifying schema', async () => {
const service = new SchemaService.YAMLSchemaService(requestServiceMock, workspaceContext);
service.setSchemaContributions({
schemas: {
'https://myschemastore/main/schema1.json': {
type: 'object',
properties: {
apiVersion: {
type: 'string',
enum: ['v1'],
},
kind: {
type: 'string',
enum: ['Pod'],
},
},
},
},
});
await service.addContent({
action: yamlSchemaService_1.MODIFICATION_ACTIONS.add,
path: 'properties/apiVersion',
key: 'enum',
content: ['v2', 'v3'],
schema: 'https://myschemastore/main/schema1.json',
});
const fs = await service.getResolvedSchema('https://myschemastore/main/schema1.json');
assert.deepEqual(fs.schema.properties['apiVersion'], {
type: 'string',
enum: ['v2', 'v3'],
});
assert.deepEqual(fs.schema.properties['kind'], {
type: 'string',
enum: ['Pod'],
});
});
it('Deleting schema', async () => {
const service = new SchemaService.YAMLSchemaService(requestServiceMock, workspaceContext);
service.setSchemaContributions({
schemas: {
'https://myschemastore/main/schema1.json': {
type: 'object',
properties: {
apiVersion: {
type: 'string',
enum: ['v1'],
},
kind: {
type: 'string',
enum: ['Pod'],
},
},
},
},
});
await service.deleteContent({
action: yamlSchemaService_1.MODIFICATION_ACTIONS.delete,
path: 'properties',
key: 'apiVersion',
schema: 'https://myschemastore/main/schema1.json',
});
const fs = await service.getResolvedSchema('https://myschemastore/main/schema1.json');
assert.notDeepEqual(fs.schema.properties['apiVersion'], {
type: 'string',
enum: ['v2', 'v3'],
});
assert.equal(fs.schema.properties['apiVersion'], undefined);
assert.deepEqual(fs.schema.properties['kind'], {
type: 'string',
enum: ['Pod'],
});
});
it('Deleting schemas', async () => {
const service = new SchemaService.YAMLSchemaService(requestServiceMock, workspaceContext);
service.setSchemaContributions({
schemas: {
'https://myschemastore/main/schema1.json': {
type: 'object',
},
},
});
await service.deleteSchemas({
action: yamlSchemaService_1.MODIFICATION_ACTIONS.deleteAll,
schemas: ['https://myschemastore/main/schema1.json'],
});
const fs = await service.getResolvedSchema('https://myschemastore/main/schema1.json');
assert.equal(fs, undefined);
});
it('Modifying schema works with kubernetes resolution', async () => {
const service = new SchemaService.YAMLSchemaService(schemaRequestServiceForURL, workspaceContext);
service.registerExternalSchema(schemaUrls_1.KUBERNETES_SCHEMA_URL);
await service.addContent({
action: yamlSchemaService_1.MODIFICATION_ACTIONS.add,
path: 'oneOf/1/properties/kind',
key: 'enum',
content: ['v2', 'v3'],
schema: schemaUrls_1.KUBERNETES_SCHEMA_URL,
});
const fs = await service.getResolvedSchema(schemaUrls_1.KUBERNETES_SCHEMA_URL);
assert.deepEqual(fs.schema.oneOf[1].properties['kind']['enum'], ['v2', 'v3']);
});
it('Deleting schema works with Kubernetes resolution', async () => {
const service = new SchemaService.YAMLSchemaService(schemaRequestServiceForURL, workspaceContext);
service.registerExternalSchema(schemaUrls_1.KUBERNETES_SCHEMA_URL);
await service.deleteContent({
action: yamlSchemaService_1.MODIFICATION_ACTIONS.delete,
path: 'oneOf/1/properties/kind',
key: 'enum',
schema: schemaUrls_1.KUBERNETES_SCHEMA_URL,
});
const fs = await service.getResolvedSchema(schemaUrls_1.KUBERNETES_SCHEMA_URL);
assert.equal(fs.schema.oneOf[1].properties['kind']['enum'], undefined);
});
it('Adding a brand new schema', async () => {
const service = new SchemaService.YAMLSchemaService(schemaRequestServiceForURL, workspaceContext);
service.saveSchema('hello_world', {
enum: ['test1', 'test2'],
});
const hello_world_schema = await service.getResolvedSchema('hello_world');
assert.deepEqual(hello_world_schema.schema.enum, ['test1', 'test2']);
});
it('Deleting an existing schema', async () => {
const service = new SchemaService.YAMLSchemaService(schemaRequestServiceForURL, workspaceContext);
service.saveSchema('hello_world', {
enum: ['test1', 'test2'],
});
await service.deleteSchema('hello_world');
const hello_world_schema = await service.getResolvedSchema('hello_world');
assert.equal(hello_world_schema, null);
});
describe('Test schema priority', function () {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const schemaAssociationSample = require(path.join(__dirname, './fixtures/sample-association.json'));
// eslint-disable-next-line @typescript-eslint/no-var-requires
const schemaStoreSample = require(path.join(__dirname, './fixtures/sample-schemastore.json'));
// eslint-disable-next-line @typescript-eslint/no-var-requires
const schemaSettingsSample = require(path.join(__dirname, './fixtures/sample-settings.json'));
// eslint-disable-next-line @typescript-eslint/no-var-requires
const schemaModelineSample = path.join(__dirname, './fixtures/sample-modeline.json');
// eslint-disable-next-line @typescript-eslint/no-var-requires
const schemaDefaultSnippetSample = require(path.join(__dirname, './fixtures/defaultSnippets-const-if-else.json'));
const languageSettingsSetup = new serviceSetup_1.ServiceSetup().withCompletion();
it('Modeline Schema takes precendence over all other schema APIs', async () => {
languageSettingsSetup
.withSchemaFileMatch({
fileMatch: ['test.yaml'],
uri: testHelper_1.TEST_URI,
priority: src_1.SchemaPriority.SchemaStore,
schema: schemaStoreSample,
})
.withSchemaFileMatch({
fileMatch: ['test.yaml'],
uri: testHelper_1.TEST_URI,
priority: src_1.SchemaPriority.SchemaAssociation,
schema: schemaAssociationSample,
})
.withSchemaFileMatch({
fileMatch: ['test.yaml'],
uri: testHelper_1.TEST_URI,
priority: src_1.SchemaPriority.Settings,
schema: schemaSettingsSample,
});
languageService.configure(languageSettingsSetup.languageSettings);
languageService.registerCustomSchemaProvider((uri) => Promise.resolve(uri));
const testTextDocument = (0, testHelper_1.setupTextDocument)(`# yaml-language-server: $schema=${schemaModelineSample}\n\n`);
const result = await languageService.doComplete(testTextDocument, vscode_languageserver_types_1.Position.create(1, 0), false);
assert.strictEqual(result.items.length, 1);
assert.strictEqual(result.items[0].label, 'modeline');
});
it('Manually setting schema takes precendence over all other lower priority schemas', async () => {
languageSettingsSetup
.withSchemaFileMatch({
fileMatch: ['test.yaml'],
uri: testHelper_1.TEST_URI,
priority: src_1.SchemaPriority.SchemaStore,
schema: schemaStoreSample,
})
.withSchemaFileMatch({
fileMatch: ['test.yaml'],
uri: testHelper_1.TEST_URI,
priority: src_1.SchemaPriority.SchemaAssociation,
schema: schemaAssociationSample,
})
.withSchemaFileMatch({
fileMatch: ['test.yaml'],
uri: testHelper_1.TEST_URI,
priority: src_1.SchemaPriority.Settings,
schema: schemaSettingsSample,
});
languageService.configure(languageSettingsSetup.languageSettings);
const testTextDocument = (0, testHelper_1.setupTextDocument)('');
const result = await languageService.doComplete(testTextDocument, vscode_languageserver_types_1.Position.create(0, 0), false);
assert.strictEqual(result.items.length, 1);
assert.strictEqual(result.items[0].label, 'settings');
});
it('SchemaAssociation takes precendence over SchemaStore', async () => {
languageSettingsSetup
.withSchemaFileMatch({
fileMatch: ['test.yaml'],
uri: testHelper_1.TEST_URI,
priority: src_1.SchemaPriority.SchemaStore,
schema: schemaStoreSample,
})
.withSchemaFileMatch({
fileMatch: ['test.yaml'],
uri: testHelper_1.TEST_URI,
priority: src_1.SchemaPriority.SchemaAssociation,
schema: schemaAssociationSample,
});
languageService.configure(languageSettingsSetup.languageSettings);
const testTextDocument = (0, testHelper_1.setupTextDocument)('');
const result = await languageService.doComplete(testTextDocument, vscode_languageserver_types_1.Position.create(0, 0), false);
assert.strictEqual(result.items.length, 1);
assert.strictEqual(result.items[0].label, 'association');
});
it('SchemaStore is highest priority if nothing else is available', async () => {
languageSettingsSetup.withSchemaFileMatch({
fileMatch: ['test.yaml'],
uri: testHelper_1.TEST_URI,
priority: src_1.SchemaPriority.SchemaStore,
schema: schemaStoreSample,
});
languageService.configure(languageSettingsSetup.languageSettings);
const testTextDocument = (0, testHelper_1.setupTextDocument)('');
const result = await languageService.doComplete(testTextDocument, vscode_languageserver_types_1.Position.create(0, 0), false);
assert.strictEqual(result.items.length, 1);
assert.strictEqual(result.items[0].label, 'schemastore');
});
it('Default snippet with description', async () => {
languageSettingsSetup.withSchemaFileMatch({
fileMatch: ['test.yaml'],
uri: testHelper_1.TEST_URI,
priority: src_1.SchemaPriority.SchemaStore,
schema: schemaDefaultSnippetSample,
});
languageService.configure(languageSettingsSetup.languageSettings);
const testTextDocument = (0, testHelper_1.setupTextDocument)('foo: ');
const result = await languageService.doComplete(testTextDocument, vscode_languageserver_types_1.Position.create(0, 5), false);
assert.strictEqual(result.items.length, 2);
assert.notStrictEqual(result.items[0].documentation, undefined);
assert.notStrictEqual(result.items[1].documentation, undefined);
assert.strictEqual(result.items[0].documentation.value, '# FooBar\n```Foo Bar```');
assert.strictEqual(result.items[1].documentation.value, '# FooBaz\n```Foo Baz```');
});
});
describe('Test getSchemaFromModeline', function () {
it('simple case', async () => {
checkReturnSchemaUrl('# yaml-language-server: $schema=expectedUrl', 'expectedUrl');
});
it('with several spaces between # and yaml-language-server', async () => {
checkReturnSchemaUrl('# yaml-language-server: $schema=expectedUrl', 'expectedUrl');
});
it('with several spaces between yaml-language-server and :', async () => {
checkReturnSchemaUrl('# yaml-language-server : $schema=expectedUrl', 'expectedUrl');
});
it('with several spaces between : and $schema', async () => {
checkReturnSchemaUrl('# yaml-language-server: $schema=expectedUrl', 'expectedUrl');
});
it('with several spaces at the end', async () => {
checkReturnSchemaUrl('# yaml-language-server: $schema=expectedUrl ', 'expectedUrl');
});
it('with several spaces at several places', async () => {
checkReturnSchemaUrl('# yaml-language-server : $schema=expectedUrl ', 'expectedUrl');
});
it('with several attributes', async () => {
checkReturnSchemaUrl('# yaml-language-server: anotherAttribute=test $schema=expectedUrl aSecondAttribtute=avalue', 'expectedUrl');
});
it('with tabs', async () => {
checkReturnSchemaUrl('#\tyaml-language-server:\t$schema=expectedUrl', 'expectedUrl');
});
it('with several $schema - pick the first', async () => {
checkReturnSchemaUrl('# yaml-language-server: $schema=url1 $schema=url2', 'url1');
});
it('no schema returned if not yaml-language-server', async () => {
checkReturnSchemaUrl('# somethingelse: $schema=url1', undefined);
});
it('no schema returned if not $schema', async () => {
checkReturnSchemaUrl('# yaml-language-server: $notschema=url1', undefined);
});
function checkReturnSchemaUrl(modeline, expectedResult) {
const yamlDoc = new parser.SingleYAMLDocument(new yaml_1.LineCounter());
yamlDoc.lineComments = [modeline];
assert.strictEqual((0, modelineUtil_1.getSchemaFromModeline)(yamlDoc), expectedResult);
}
});
});
//# sourceMappingURL=schema.test.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
export {};

View File

@@ -0,0 +1,48 @@
"use strict";
/*---------------------------------------------------------------------------------------------
* Copyright (c) Red Hat. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
const schemaRequestHandler_1 = require("../src/languageservice/services/schemaRequestHandler");
const sinon = require("sinon");
const vscode_uri_1 = require("vscode-uri");
const chai = require("chai");
const sinonChai = require("sinon-chai");
const expect = chai.expect;
chai.use(sinonChai);
const testHelper_1 = require("./utils/testHelper");
describe('Schema Request Handler Tests', () => {
describe('schemaRequestHandler', () => {
const sandbox = sinon.createSandbox();
let readFileStub;
beforeEach(() => {
readFileStub = sandbox.stub(testHelper_1.testFileSystem, 'readFile');
readFileStub.returns(Promise.resolve('{some: "json"}'));
});
afterEach(() => {
sandbox.restore();
});
it('Should care Win URI', async () => {
const connection = {};
const resultPromise = (0, schemaRequestHandler_1.schemaRequestHandler)(connection, 'c:\\some\\window\\path\\scheme.json', [], vscode_uri_1.URI.parse(''), false, testHelper_1.testFileSystem);
expect(readFileStub).calledOnceWith('c:\\some\\window\\path\\scheme.json');
const result = await resultPromise;
expect(result).to.be.equal('{some: "json"}');
});
it('UNIX URI should works', async () => {
const connection = {};
const resultPromise = (0, schemaRequestHandler_1.schemaRequestHandler)(connection, '/some/unix/path/', [], vscode_uri_1.URI.parse(''), false, testHelper_1.testFileSystem);
const result = await resultPromise;
expect(result).to.be.equal('{some: "json"}');
});
it('should handle not valid Windows path', async () => {
const connection = {};
const resultPromise = (0, schemaRequestHandler_1.schemaRequestHandler)(connection, 'A:/some/window/path/scheme.json', [], vscode_uri_1.URI.parse(''), false, testHelper_1.testFileSystem);
expect(readFileStub).calledOnceWith(vscode_uri_1.URI.file('a:/some/window/path/scheme.json').fsPath);
const result = await resultPromise;
expect(result).to.be.equal('{some: "json"}');
});
});
});
//# sourceMappingURL=schemaRequestHandler.test.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"schemaRequestHandler.test.js","sourceRoot":"","sources":["../../../test/schemaRequestHandler.test.ts"],"names":[],"mappings":";AAAA;;;gGAGgG;;AAEhG,+FAA4F;AAC5F,+BAA+B;AAE/B,2CAAiC;AACjC,6BAA6B;AAC7B,wCAAwC;AAExC,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC;AAC3B,IAAI,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;AACpB,mDAAoD;AAEpD,QAAQ,CAAC,8BAA8B,EAAE,GAAG,EAAE;IAC5C,QAAQ,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,gBAAgB,CAAC,CAAC;QAC/C,CAAC,CAAC,CAAC;QAEH,EAAE,CAAC,sCAAsC,EAAE,KAAK,IAAI,EAAE;YACpD,MAAM,UAAU,GAAe,EAAE,CAAC;YAClC,MAAM,aAAa,GAAG,IAAA,2CAAoB,EACxC,UAAU,EACV,iCAAiC,EACjC,EAAE,EACF,gBAAG,CAAC,KAAK,CAAC,EAAE,CAAC,EACb,KAAK,EACL,2BAAc,CACf,CAAC;YACF,MAAM,CAAC,YAAY,CAAC,CAAC,cAAc,CAAC,gBAAG,CAAC,IAAI,CAAC,iCAAiC,CAAC,CAAC,MAAM,CAAC,CAAC;YACxF,MAAM,MAAM,GAAG,MAAM,aAAa,CAAC;YACnC,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,KAAK,CAAC,gBAAgB,CAAC,CAAC;QAC/C,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"}

View File

@@ -0,0 +1 @@
export {};

View File

@@ -0,0 +1,99 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/*---------------------------------------------------------------------------------------------
* Copyright (c) Red Hat, Inc. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
const sinon = require("sinon");
const chai = require("chai");
const sinonChai = require("sinon-chai");
const schemaSelectionHandlers_1 = require("../src/languageserver/handlers/schemaSelectionHandlers");
const yamlSchemaService_1 = require("../src/languageservice/services/yamlSchemaService");
const yamlSettings_1 = require("../src/yamlSettings");
const requestTypes_1 = require("../src/requestTypes");
const testHelper_1 = require("./utils/testHelper");
const expect = chai.expect;
chai.use(sinonChai);
describe('Schema Selection Handlers', () => {
const sandbox = sinon.createSandbox();
const connection = {};
let service;
let requestServiceMock;
beforeEach(() => {
requestServiceMock = sandbox.fake.resolves(undefined);
service = new yamlSchemaService_1.YAMLSchemaService(requestServiceMock);
connection.client = {};
const onRequest = sandbox.fake();
connection.onRequest = onRequest;
});
afterEach(() => {
sandbox.restore();
});
it('add handler for "getSchema" and "getAllSchemas" requests', () => {
new schemaSelectionHandlers_1.JSONSchemaSelection(service, new yamlSettings_1.SettingsState(), connection);
expect(connection.onRequest).calledWith(requestTypes_1.SchemaSelectionRequests.getSchema);
expect(connection.onRequest).calledWith(requestTypes_1.SchemaSelectionRequests.getAllSchemas);
});
it('getAllSchemas should return all schemas', async () => {
service.registerExternalSchema('https://some.com/some.json', ['foo.yaml'], undefined, 'Schema name', 'Schema description');
const settings = new yamlSettings_1.SettingsState();
const testTextDocument = (0, testHelper_1.setupSchemaIDTextDocument)('');
settings.documents = new yamlSettings_1.TextDocumentTestManager();
settings.documents.set(testTextDocument);
const selection = new schemaSelectionHandlers_1.JSONSchemaSelection(service, settings, connection);
const result = await selection.getAllSchemas(testTextDocument.uri);
expect(result).length(1);
expect(result[0]).to.be.eqls({
uri: 'https://some.com/some.json',
fromStore: true,
usedForCurrentFile: false,
name: 'Schema name',
description: 'Schema description',
versions: undefined,
});
});
it('getAllSchemas should return all schemas and mark used for current file', async () => {
service.registerExternalSchema('https://some.com/some.json', [testHelper_1.SCHEMA_ID], undefined, 'Schema name', 'Schema description');
const settings = new yamlSettings_1.SettingsState();
const testTextDocument = (0, testHelper_1.setupSchemaIDTextDocument)('');
settings.documents = new yamlSettings_1.TextDocumentTestManager();
settings.documents.set(testTextDocument);
const selection = new schemaSelectionHandlers_1.JSONSchemaSelection(service, settings, connection);
const result = await selection.getAllSchemas(testTextDocument.uri);
expect(result).length(1);
expect(result[0]).to.be.eqls({
uri: 'https://some.com/some.json',
name: 'Schema name',
description: 'Schema description',
fromStore: false,
usedForCurrentFile: true,
versions: undefined,
});
});
it('getSchemas should return all schemas', async () => {
service.registerExternalSchema('https://some.com/some.json', [testHelper_1.SCHEMA_ID], undefined, 'Schema name', 'Schema description');
const settings = new yamlSettings_1.SettingsState();
const testTextDocument = (0, testHelper_1.setupSchemaIDTextDocument)('');
settings.documents = new yamlSettings_1.TextDocumentTestManager();
settings.documents.set(testTextDocument);
const selection = new schemaSelectionHandlers_1.JSONSchemaSelection(service, settings, connection);
const result = await selection.getSchemas(testTextDocument.uri);
expect(result).length(1);
expect(result[0]).to.be.eqls({
uri: 'https://some.com/some.json',
name: 'Schema name',
description: 'Schema description',
versions: undefined,
});
});
it('getSchemas should handle empty schemas', async () => {
const settings = new yamlSettings_1.SettingsState();
const testTextDocument = (0, testHelper_1.setupSchemaIDTextDocument)('');
settings.documents = new yamlSettings_1.TextDocumentTestManager();
settings.documents.set(testTextDocument);
const selection = new schemaSelectionHandlers_1.JSONSchemaSelection(service, settings, connection);
const result = await selection.getSchemas(testTextDocument.uri);
expect(result).length(0);
});
});
//# sourceMappingURL=schemaSelectionHandlers.test.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"schemaSelectionHandlers.test.js","sourceRoot":"","sources":["../../../test/schemaSelectionHandlers.test.ts"],"names":[],"mappings":";;AAAA;;;gGAGgG;AAChG,+BAA+B;AAC/B,6BAA6B;AAC7B,wCAAwC;AACxC,oGAA6F;AAC7F,yFAAsF;AAEtF,sDAA6E;AAC7E,sDAA8D;AAC9D,mDAA0E;AAE1E,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC;AAC3B,IAAI,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;AAEpB,QAAQ,CAAC,2BAA2B,EAAE,GAAG,EAAE;IACzC,MAAM,OAAO,GAAG,KAAK,CAAC,aAAa,EAAE,CAAC;IACtC,MAAM,UAAU,GAAe,EAAgB,CAAC;IAChD,IAAI,OAA0B,CAAC;IAC/B,IAAI,kBAAkC,CAAC;IAEvC,UAAU,CAAC,GAAG,EAAE;QACd,kBAAkB,GAAG,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC;QACtD,OAAO,GAAG,IAAI,qCAAiB,CAAC,kBAAkB,CAAC,CAAC;QACpD,UAAU,CAAC,MAAM,GAAG,EAAkB,CAAC;QACvC,MAAM,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AS,CAAC,UAAU,CAAC,gBAAgB,CAAC,GAAG,CAAC,CAAC;QAEhE,MAAM,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;IAC3B,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"}

View File

@@ -0,0 +1 @@
export {};

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
export {};

View File

@@ -0,0 +1,299 @@
"use strict";
/*---------------------------------------------------------------------------------------------
* Copyright (c) Red Hat, Inc. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
const chai = require("chai");
const request = require("request-light");
const sinon = require("sinon");
const sinonChai = require("sinon-chai");
const src_1 = require("../src");
const settingsHandlers_1 = require("../src/languageserver/handlers/settingsHandlers");
const validationHandlers_1 = require("../src/languageserver/handlers/validationHandlers");
const yamlSettings_1 = require("../src/yamlSettings");
const testHelper_1 = require("./utils/testHelper");
const testsTypes_1 = require("./utils/testsTypes");
const expect = chai.expect;
chai.use(sinonChai);
describe('Settings Handlers Tests', () => {
const sandbox = sinon.createSandbox();
const connection = {};
let workspaceStub;
let languageService;
let settingsState;
let validationHandler;
let xhrStub;
beforeEach(() => {
workspaceStub = sandbox.createStubInstance(testsTypes_1.TestWorkspace);
connection.workspace = workspaceStub;
connection.onDidChangeConfiguration = sandbox.mock();
connection.client = {};
connection.client.register = sandbox.mock();
const languageServerSetup = (0, testHelper_1.setupLanguageService)({});
languageService = languageServerSetup.languageService;
settingsState = new yamlSettings_1.SettingsState();
validationHandler = sandbox.mock(validationHandlers_1.ValidationHandler);
xhrStub = sandbox.stub(request, 'xhr');
const sendRequest = sandbox.fake();
connection.sendRequest = sendRequest;
});
afterEach(() => {
sandbox.restore();
});
it('should not register configuration notification handler if client not supports dynamic handlers', () => {
settingsState.clientDynamicRegisterSupport = false;
settingsState.hasConfigurationCapability = false;
const settingsHandler = new settingsHandlers_1.SettingsHandler(connection, languageService, settingsState, validationHandler, {});
settingsHandler.registerHandlers();
expect(connection.client.register).not.called;
});
it('should register configuration notification handler only if client supports dynamic handlers', () => {
settingsState.clientDynamicRegisterSupport = true;
settingsState.hasConfigurationCapability = true;
const settingsHandler = new settingsHandlers_1.SettingsHandler(connection, languageService, settingsState, validationHandler, {});
settingsHandler.registerHandlers();
expect(connection.client.register).calledOnce;
});
describe('Settings for YAML style should ', () => {
it(' reflect to the settings ', async () => {
const settingsHandler = new settingsHandlers_1.SettingsHandler(connection, languageService, settingsState, validationHandler, {});
workspaceStub.getConfiguration.resolves([{ style: { flowMapping: 'forbid', flowSequence: 'forbid' } }, {}, {}, {}, {}]);
await settingsHandler.pullConfiguration();
expect(settingsState.style).to.exist;
expect(settingsState.style.flowMapping).to.eqls('forbid');
expect(settingsState.style.flowSequence).to.eqls('forbid');
});
it(' reflect default values if no settings given', async () => {
const settingsHandler = new settingsHandlers_1.SettingsHandler(connection, languageService, settingsState, validationHandler, {});
workspaceStub.getConfiguration.resolves([{}, {}, {}, {}, {}]);
await settingsHandler.pullConfiguration();
expect(settingsState.style).to.exist;
expect(settingsState.style.flowMapping).to.eqls('allow');
expect(settingsState.style.flowSequence).to.eqls('allow');
});
});
describe('Settings for key ordering should ', () => {
it(' reflect to the settings ', async () => {
const settingsHandler = new settingsHandlers_1.SettingsHandler(connection, languageService, settingsState, validationHandler, {});
workspaceStub.getConfiguration.resolves([{ keyOrdering: true }, {}, {}, {}, {}]);
await settingsHandler.pullConfiguration();
expect(settingsState.keyOrdering).to.exist;
expect(settingsState.keyOrdering).to.be.true;
});
it(' reflect default values if no settings given', async () => {
const settingsHandler = new settingsHandlers_1.SettingsHandler(connection, languageService, settingsState, validationHandler, {});
workspaceStub.getConfiguration.resolves([{}, {}, {}, {}, {}]);
await settingsHandler.pullConfiguration();
expect(settingsState.style).to.exist;
expect(settingsState.keyOrdering).to.be.false;
});
});
describe('Settings for file associations should ', () => {
it('reflect to settings state', async () => {
const settingsHandler = new settingsHandlers_1.SettingsHandler(connection, languageService, settingsState, validationHandler, {});
workspaceStub.getConfiguration.resolves([{}, {}, {}, {}, { associations: { '*.bu': 'yaml' } }]);
await settingsHandler.pullConfiguration();
expect(settingsState.fileExtensions).to.include('*.bu');
expect(settingsState.fileExtensions).to.include('.yml');
expect(settingsState.fileExtensions).to.include('.yaml');
});
it('SettingsHandler should match patterns from file associations', async () => {
const languageServerSetup = (0, testHelper_1.setupLanguageService)({});
const languageService = languageServerSetup.languageService;
xhrStub.resolves({
responseText: `{"schemas": [
{
"name": "Butane config schema",
"description": "Schema to validate butane files for Fedora CoreOS",
"fileMatch": [
"*.bu"
],
"url": "https://raw.githubusercontent.com/Relativ-IT/Butane-Schemas/Release/Butane-Schema.json"
}]}`,
});
settingsState.fileExtensions.push('*.bu');
const settingsHandler = new settingsHandlers_1.SettingsHandler(connection, languageService, settingsState, validationHandler, {});
workspaceStub.getConfiguration.resolves([{}, {}, {}, {}]);
const configureSpy = sinon.stub(languageService, 'configure');
await settingsHandler.pullConfiguration();
configureSpy.restore();
expect(settingsState.schemaStoreSettings).deep.include({
uri: 'https://raw.githubusercontent.com/Relativ-IT/Butane-Schemas/Release/Butane-Schema.json',
fileMatch: ['*.bu'],
priority: src_1.SchemaPriority.SchemaStore,
name: 'Butane config schema',
description: 'Schema to validate butane files for Fedora CoreOS',
versions: undefined,
});
});
it('SettingsHandler should not match non-yaml files if there is no file assosication', async () => {
const languageServerSetup = (0, testHelper_1.setupLanguageService)({});
const languageService = languageServerSetup.languageService;
xhrStub.resolves({
responseText: `{"schemas": [
{
"name": "Butane config schema",
"description": "Schema to validate butane files for Fedora CoreOS",
"fileMatch": [
"*.bu"
],
"url": "https://raw.githubusercontent.com/Relativ-IT/Butane-Schemas/Release/Butane-Schema.json"
}]}`,
});
const settingsHandler = new settingsHandlers_1.SettingsHandler(connection, languageService, settingsState, validationHandler, {});
workspaceStub.getConfiguration.resolves([{}, {}, {}, {}]);
const configureSpy = sinon.stub(languageService, 'configure');
await settingsHandler.pullConfiguration();
configureSpy.restore();
expect(settingsState.schemaStoreSettings).not.deep.include({
uri: 'https://raw.githubusercontent.com/Relativ-IT/Butane-Schemas/Release/Butane-Schema.json',
fileMatch: ['*.bu'],
priority: src_1.SchemaPriority.SchemaStore,
name: 'Butane config schema',
description: 'Schema to validate butane files for Fedora CoreOS',
versions: undefined,
});
});
});
it('SettingsHandler should not modify file match patterns', async () => {
const languageServerSetup = (0, testHelper_1.setupLanguageService)({});
const languageService = languageServerSetup.languageService;
xhrStub.resolves({
responseText: `{"schemas": [
{
"name": ".adonisrc.json",
"description": "AdonisJS configuration file",
"fileMatch": [
".adonisrc.yaml"
],
"url": "https://raw.githubusercontent.com/adonisjs/application/master/adonisrc.schema.json"
}]}`,
});
const settingsHandler = new settingsHandlers_1.SettingsHandler(connection, languageService, settingsState, validationHandler, {});
workspaceStub.getConfiguration.resolves([{}, {}, {}, {}]);
const configureSpy = sinon.stub(languageService, 'configure');
await settingsHandler.pullConfiguration();
configureSpy.restore();
expect(settingsState.schemaStoreSettings).deep.include({
uri: 'https://raw.githubusercontent.com/adonisjs/application/master/adonisrc.schema.json',
fileMatch: ['.adonisrc.yaml'],
priority: src_1.SchemaPriority.SchemaStore,
name: '.adonisrc.json',
description: 'AdonisJS configuration file',
versions: undefined,
});
});
describe('Test that schema priorities are available', async () => {
const testSchemaFileMatch = ['foo/*.yml'];
const testSchemaURI = 'file://foo.json';
async function configureSchemaPriorityTest() {
const settingsHandler = new settingsHandlers_1.SettingsHandler(connection, languageService, settingsState, validationHandler, {});
const configureSpy = sinon.spy(languageService, 'configure');
await settingsHandler.pullConfiguration();
configureSpy.restore();
return configureSpy.args[0][0];
}
it('Schema Settings should have a priority', async () => {
xhrStub.resolves({
responseText: `{"schemas": [
{
"name": ".adonisrc.json",
"description": "AdonisJS configuration file",
"fileMatch": [
".adonisrc.yaml"
],
"url": "https://raw.githubusercontent.com/adonisjs/application/master/adonisrc.schema.json"
}]}`,
});
const schemas = {};
schemas[testSchemaURI] = testSchemaFileMatch;
workspaceStub.getConfiguration.resolves([{ schemas: schemas }, {}, {}, {}]);
const configureSpy = await configureSchemaPriorityTest();
expect(configureSpy.schemas).deep.include({
uri: testSchemaURI,
fileMatch: testSchemaFileMatch,
schema: undefined,
priority: src_1.SchemaPriority.Settings,
});
});
it('Schema Associations should have a priority when schema association is an array', async () => {
xhrStub.resolves({
responseText: `{"schemas": [
{
"name": ".adonisrc.json",
"description": "AdonisJS configuration file",
"fileMatch": [
".adonisrc.yaml"
],
"url": "https://raw.githubusercontent.com/adonisjs/application/master/adonisrc.schema.json"
}]}`,
});
settingsState.schemaAssociations = [
{
fileMatch: testSchemaFileMatch,
uri: testSchemaURI,
},
];
workspaceStub.getConfiguration.resolves([{}, {}, {}, {}]);
const configureSpy = await configureSchemaPriorityTest();
expect(configureSpy.schemas).deep.include({
uri: testSchemaURI,
fileMatch: testSchemaFileMatch,
schema: undefined,
priority: src_1.SchemaPriority.SchemaAssociation,
});
});
it('Schema Associations should have a priority when schema association is a record', async () => {
settingsState.schemaAssociations = {
[testSchemaURI]: testSchemaFileMatch,
};
workspaceStub.getConfiguration.resolves([{}, {}, {}, {}]);
const configureSpy = await configureSchemaPriorityTest();
expect(configureSpy.schemas).deep.include({
uri: testSchemaURI,
fileMatch: testSchemaFileMatch,
priority: src_1.SchemaPriority.SchemaAssociation,
});
});
});
describe('Settings fetch', () => {
it('should fetch preferences', async () => {
const settingsHandler = new settingsHandlers_1.SettingsHandler(connection, languageService, settingsState, validationHandler, {});
workspaceStub.getConfiguration.resolves([{}, {}, {}, {}, {}]);
await settingsHandler.pullConfiguration();
expect(workspaceStub.getConfiguration).calledOnceWith([
{ section: 'yaml' },
{ section: 'http' },
{ section: '[yaml]' },
{ section: 'editor' },
{ section: 'files' },
]);
});
it('should set schemaStoreSettings to empty when schemaStore is disabled', async () => {
const languageServerSetup = (0, testHelper_1.setupLanguageService)({});
const languageService = languageServerSetup.languageService;
settingsState.schemaStoreEnabled = true;
const settingsHandler = new settingsHandlers_1.SettingsHandler(connection, languageService, settingsState, validationHandler, {});
workspaceStub.getConfiguration.resolves([{ schemaStore: { enable: false, url: 'http://shouldnot.activate' } }, {}, {}, {}]);
// const configureSpy = sinon.spy(languageService, 'configure');
await settingsHandler.pullConfiguration();
// configureSpy.restore();
expect(settingsState.schemaStoreEnabled).to.be.false;
expect(settingsState.schemaStoreSettings).to.be.empty;
});
it('detect indentation settings change', async () => {
const settingsHandler = new settingsHandlers_1.SettingsHandler(connection, languageService, settingsState, validationHandler, {});
workspaceStub.getConfiguration.resolves([{}, {}, {}, { tabSize: 4, detectIndentation: false }]);
await settingsHandler.pullConfiguration();
expect(workspaceStub.getConfiguration).calledOnceWith([
{ section: 'yaml' },
{ section: 'http' },
{ section: '[yaml]' },
{ section: 'editor' },
{ section: 'files' },
]);
});
});
});
//# sourceMappingURL=settingsHandlers.test.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
export {};

View File

@@ -0,0 +1,92 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/*---------------------------------------------------------------------------------------------
* Copyright (c) Red Hat. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
const strings_1 = require("../src/languageservice/utils/strings");
const assert = require("assert");
const chai_1 = require("chai");
describe('String Tests', () => {
describe('startsWith', function () {
it('String with different lengths', () => {
const one = 'hello';
const other = 'goodbye';
const result = (0, strings_1.startsWith)(one, other);
assert.equal(result, false);
});
it('String with same length different first letter', () => {
const one = 'hello';
const other = 'jello';
const result = (0, strings_1.startsWith)(one, other);
assert.equal(result, false);
});
it('Same string', () => {
const one = 'hello';
const other = 'hello';
const result = (0, strings_1.startsWith)(one, other);
assert.equal(result, true);
});
});
describe('endsWith', function () {
it('String with different lengths', () => {
const one = 'hello';
const other = 'goodbye';
const result = (0, strings_1.endsWith)(one, other);
assert.equal(result, false);
});
it('Strings that are the same', () => {
const one = 'hello';
const other = 'hello';
const result = (0, strings_1.endsWith)(one, other);
assert.equal(result, true);
});
it('Other is smaller then one', () => {
const one = 'hello';
const other = 'hi';
const result = (0, strings_1.endsWith)(one, other);
assert.equal(result, false);
});
});
describe('convertSimple2RegExp', function () {
it('Test of convertRegexString2RegExp', () => {
const result = (0, strings_1.convertSimple2RegExp)('/toc\\.yml/i').test('TOC.yml');
assert.equal(result, true);
});
it('Test of convertGlobalPattern2RegExp', () => {
let result = (0, strings_1.convertSimple2RegExp)('toc.yml').test('toc.yml');
assert.equal(result, true);
result = (0, strings_1.convertSimple2RegExp)('toc.yml').test('TOC.yml');
assert.equal(result, false);
});
});
describe('safeCreateUnicodeRegExp', () => {
it('should create unicode RegExp for non unicode patterns', () => {
const result = (0, strings_1.safeCreateUnicodeRegExp)(
// eslint-disable-next-line prettier/prettier
'^([2-9])\\.([0-9]+)\\.([0-9]+)(\\-[0-9a-z-]+(\\.[0-9a-z-]+)*)?(\\+[0-9A-Za-z-]+(\\.[0-9A-Za-z-]+)*)?$');
(0, chai_1.expect)(result).is.not.undefined;
});
it('should create unicode RegExp for non unicode patterns2', () => {
// eslint-disable-next-line prettier/prettier
const result = (0, strings_1.safeCreateUnicodeRegExp)('^[^\\/~\\^\\: \\[\\]\\\\]+(\\/[^\\/~\\^\\: \\[\\]\\\\]+)*$');
(0, chai_1.expect)(result).is.not.undefined;
});
it('should create unicode RegExp for non unicode patterns3', () => {
// eslint-disable-next-line prettier/prettier
const result = (0, strings_1.safeCreateUnicodeRegExp)('^(\\s?)+=[^\\=](.+)');
(0, chai_1.expect)(result).is.not.undefined;
});
it('should create unicode RegExp for non unicode patterns4', () => {
// eslint-disable-next-line prettier/prettier
const result = (0, strings_1.safeCreateUnicodeRegExp)('^x-[\\w\\d\\.\\-\\_]+$');
(0, chai_1.expect)(result).is.not.undefined;
});
it('should create unicode RegExp for non unicode patterns5', () => {
// eslint-disable-next-line prettier/prettier
const result = (0, strings_1.safeCreateUnicodeRegExp)('^[\\w\\-_]+$');
(0, chai_1.expect)(result).is.not.undefined;
});
});
});
//# sourceMappingURL=strings.test.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"strings.test.js","sourceRoot":"","sources":["../../../test/strings.test.ts"],"names":[],"mappings":";;AAAA;;;gGAGgG;AAChG,kEAA2H;AAC3H,iCAAiC;AACjC,+BAA8B;AAE9B,QAAQ,CAAC,cAAc,EAAE,GAAG,EAAE;IAC5B,QAAQ,CAAC,YAAY,EAAE;QACrB,EAAE,CAAC,+BAA+B,EAAE,GAAG,EAAE;YACvC,MAAM,GAAG,GAAG,OAAO,CAAC;YACpB,MAAM,KAAK,GAAG,SAAS,CAAC;YAExB,MAAM,MAAM,GAAG,IAAA,oBAAU,EAAC,GAAG,EAAE,KAAK,CAAC,CAAC;YACtC,MAAM,CAAC,KAAK,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;QAC9B,CAAC,CAAC,CAAC;QAEH,EAAE,CAAC,gDAAgD,EAAE,GAAG,EAAE;YACxD,MAAM,GAAG,GAAG,OAAO,CAAC;YACpB,MAAM,KAAK,GAAG,OAAO,CAAC;YAEtB,MAAM,MAAM,GAAG,IAAA,oBAAU,EAAC,GAAG,EAAE,KAAK,CAAC,CAAC;YACtC,MAAM,CAAC,KAAK,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;QAC9B,CAAC,CAAC,CAAC;QAEH,EAAE,CAAC,aAAa,EAAE,GAAG,EAAE;YACrB,MAAM,GAAG,GAAG,OAAO,CAAC;YACpB,MAAM,KAAK,GAAG,OAAO,CAAC;YAEtB,MAAM,MAAM,GAAG,IAAA,oBAAU,EAAC,GAAG,EAAE,KAAK,CAAC,CAAC;YACtC,MAAM,CAAC,KAAK,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;QAC7B,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;IAEH,QAAQ,CAAC,UAAU,EAAE;QACnB,EAAE,CAAC,+BAA+B,EAAE,GAAG,EAAE;YACvC,MA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6CAA6C;YAC7C,MAAM,MAAM,GAAG,IAAA,iCAAuB,EAAC,cAAc,CAAC,CAAC;YACvD,IAAA,aAAM,EAAC,MAAM,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,SAAS,CAAC;QAClC,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"}

View File

@@ -0,0 +1 @@
export {};

View File

@@ -0,0 +1,36 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/*---------------------------------------------------------------------------------------------
* Copyright (c) Red Hat. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
const sinon = require("sinon");
const sinonChai = require("sinon-chai");
const chai = require("chai");
const schemaUrls_1 = require("../src/languageservice/utils/schemaUrls");
const telemetry_1 = require("../src/languageserver/telemetry");
const vscode_uri_1 = require("vscode-uri");
const expect = chai.expect;
chai.use(sinonChai);
describe('Telemetry Tests', () => {
const sandbox = sinon.createSandbox();
let telemetry;
beforeEach(() => {
const telemetryInstance = new telemetry_1.TelemetryImpl({});
telemetry = sandbox.stub(telemetryInstance);
});
afterEach(() => {
sandbox.restore();
});
describe('Kubernetos schema mapping', () => {
it('should not report if schema is not k8s', () => {
(0, schemaUrls_1.checkSchemaURI)([], vscode_uri_1.URI.parse('file:///some/path'), 'file:///some/path/to/schema.json', telemetry);
expect(telemetry.send).not.called;
});
it('should report if schema is k8s', () => {
(0, schemaUrls_1.checkSchemaURI)([], vscode_uri_1.URI.parse('file:///some/path'), 'kubernetes', telemetry);
expect(telemetry.send).calledOnceWith({ name: 'yaml.schema.configured', properties: { kubernetes: true } });
});
});
});
//# sourceMappingURL=telemetry.test.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"telemetry.test.js","sourceRoot":"","sources":["../../../test/telemetry.test.ts"],"names":[],"mappings":";;AAAA;;;gGAGgG;AAChG,+BAA+B;AAC/B,wCAAwC;AACxC,6BAA6B;AAC7B,wEAAyE;AACzE,+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

View File

@@ -0,0 +1,41 @@
"use strict";
/*---------------------------------------------------------------------------------------------
* Copyright (c) Red Hat. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
const textBuffer_1 = require("../src/languageservice/utils/textBuffer");
const vscode_languageserver_textdocument_1 = require("vscode-languageserver-textdocument");
const assert = require("assert");
describe('TextBuffer', () => {
it('getLineLength should return actual line length', () => {
const buffer = new textBuffer_1.TextBuffer(vscode_languageserver_textdocument_1.TextDocument.create('file://foo/bar', 'yaml', 1, 'Foo\nbar'));
const length = buffer.getLineLength(0);
assert.strictEqual(length, 4);
const length2 = buffer.getLineLength(1);
assert.strictEqual(length2, 3);
});
it('getLineLength should return actual line length, win style', () => {
const buffer = new textBuffer_1.TextBuffer(vscode_languageserver_textdocument_1.TextDocument.create('file://foo/bar', 'yaml', 1, 'Foo\r\nbar'));
const length = buffer.getLineLength(0);
assert.strictEqual(length, 5);
const length2 = buffer.getLineLength(1);
assert.strictEqual(length2, 3);
});
it('getLineContent should return actual line content', () => {
const buffer = new textBuffer_1.TextBuffer(vscode_languageserver_textdocument_1.TextDocument.create('file://foo/bar', 'yaml', 1, 'Foo\nbar\nfooBar\nsome'));
const line = buffer.getLineContent(1);
assert.strictEqual(line, 'bar\n');
});
it('getLineContent should return last line', () => {
const buffer = new textBuffer_1.TextBuffer(vscode_languageserver_textdocument_1.TextDocument.create('file://foo/bar', 'yaml', 1, 'Foo\nbar\nfooBar\nsome'));
const line = buffer.getLineContent(3);
assert.strictEqual(line, 'some');
});
it('getLineCharCode should return charCode', () => {
const buffer = new textBuffer_1.TextBuffer(vscode_languageserver_textdocument_1.TextDocument.create('file://foo/bar', 'yaml', 1, 'Foo\nbar\nfooBar\nsome'));
const charCode = buffer.getLineCharCode(3, 3);
assert.strictEqual(charCode, 'B'.charCodeAt(0));
});
});
//# sourceMappingURL=textBuffer.test.js.map

View File

@@ -0,0 +1 @@
{"version":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,EAAE,wBAAwB,CAAC,CAAC,CAAC;QAC1G,MAAM,IAAI,GAAG,MAAM,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC;QACtC,MAAM,CAAC,WAAW,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;IACpC,CAAC,CAAC,CAAC;IAEH,EAAE,CAAC,wCAAwC,EAAE,GAAG,EAAE;QAChD,MAAM,MAAM,GAAG,IAAI,uBAAU,CAAC,iDAAY,CAAC,MAAM,CAAC,gBAAgB,EAAE,MAAM,EAAE,CAAC,EAAE,wBAAwB,CAAC,CAAC,CAAC;QAC1G,MAAM,IAAI,GAAG,MAAM,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC;QACtC,MAAM,CAAC,WAAW,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;IACnC,CAAC,CAAC,CAAC;IAEH,EAAE,CAAC,wCAAwC,EAAE,GAAG,EAAE;QAChD,MAAM,MAAM,GAAG,IAAI,uBAAU,CAAC,iDAAY,CAAC,MAAM,CAAC,gBAAgB,EAAE,MAAM,EAAE,CAAC,EAAE,wBAAwB,CAAC,CAAC,CAAC;QAC1G,MAAM,QAAQ,GAAG,MAAM,CAAC,eAAe,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;QAC9C,MAAM,CAAC,WAAW,CAAC,QAAQ,EAAE,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC;IAClD,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"}

View File

@@ -0,0 +1,27 @@
/**
* List of error messages
*/
/**
* Type Errors
*/
export declare const StringTypeError = "Incorrect type. Expected \"string\".";
export declare const NumberTypeError = "Incorrect type. Expected \"number\".";
export declare const BooleanTypeError = "Incorrect type. Expected \"boolean\".";
export declare const ArrayTypeError = "Incorrect type. Expected \"array\".";
export declare const ObjectTypeError = "Incorrect type. Expected \"object\".";
export declare const TypeMismatchWarning = "Incorrect type. Expected \"{0}\".";
export declare const MissingRequiredPropWarning = "Missing property \"{0}\".";
export declare const ConstWarning = "Value must be {0}.";
export declare function propertyIsNotAllowed(name: string): string;
/**
* Parse errors
*/
export declare const BlockMappingEntryError = "Implicit map keys need to be followed by map values";
/**
* Value Errors
*/
export declare const IncludeWithoutValueError = "!include without value";
/**
* Duplicate Key error
*/
export declare const DuplicateKeyError = "Map keys must be unique";

View File

@@ -0,0 +1,38 @@
"use strict";
/*---------------------------------------------------------------------------------------------
* Copyright (c) Red Hat. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.DuplicateKeyError = exports.IncludeWithoutValueError = exports.BlockMappingEntryError = exports.propertyIsNotAllowed = exports.ConstWarning = exports.MissingRequiredPropWarning = exports.TypeMismatchWarning = exports.ObjectTypeError = exports.ArrayTypeError = exports.BooleanTypeError = exports.NumberTypeError = exports.StringTypeError = void 0;
/**
* List of error messages
*/
/**
* Type Errors
*/
exports.StringTypeError = 'Incorrect type. Expected "string".';
exports.NumberTypeError = 'Incorrect type. Expected "number".';
exports.BooleanTypeError = 'Incorrect type. Expected "boolean".';
exports.ArrayTypeError = 'Incorrect type. Expected "array".';
exports.ObjectTypeError = 'Incorrect type. Expected "object".';
exports.TypeMismatchWarning = 'Incorrect type. Expected "{0}".';
exports.MissingRequiredPropWarning = 'Missing property "{0}".';
exports.ConstWarning = 'Value must be {0}.';
function propertyIsNotAllowed(name) {
return `Property ${name} is not allowed.`;
}
exports.propertyIsNotAllowed = propertyIsNotAllowed;
/**
* Parse errors
*/
exports.BlockMappingEntryError = 'Implicit map keys need to be followed by map values';
/**
* Value Errors
*/
exports.IncludeWithoutValueError = '!include without value';
/**
* Duplicate Key error
*/
exports.DuplicateKeyError = 'Map keys must be unique';
//# sourceMappingURL=errorMessages.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"errorMessages.js","sourceRoot":"","sources":["../../../../test/utils/errorMessages.ts"],"names":[],"mappings":";AAAA;;;gGAGgG;;;AAEhG;;GAEG;AAEH;;GAEG;AACU,QAAA,eAAe,GAAG,oCAAoC,CAAC;AACvD,QAAA,eAAe,GAAG,oCAAoC,CAAC;AACvD,QAAA,gBAAgB,GAAG,qCAAqC,CAAC;AACzD,QAAA,cAAc,GAAG,mCAAmC,CAAC;AACrD,QAAA,eAAe,GAAG,oCAAoC,CAAC;AACvD,QAAA,mBAAmB,GAAG,iCAAiC,CAAC;AACxD,QAAA,0BAA0B,GAAG,yBAAyB,CAAC;AACvD,QAAA,YAAY,GAAG,oBAAoB,CAAC;AAEjD,SAAgB,oBAAoB,CAAC,IAAY;IAC/C,OAAO,YAAY,IAAI,kBAAkB,CAAC;AAC5C,CAAC;AAFD,oDAEC;AAED;;GAEG;AACU,QAAA,sBAAsB,GAAG,qDAAqD,CAAC;AAE5F;;GAEG;AACU,QAAA,wBAAwB,GAAG,wBAAwB,CAAC;AAEjE;;GAEG;AACU,QAAA,iBAAiB,GAAG,yBAAyB,CAAC"}

View File

@@ -0,0 +1,15 @@
import { LanguageSettings, SchemasSettings } from '../../src/languageservice/yamlLanguageService';
export declare class ServiceSetup {
languageSettings: LanguageSettings;
withValidate(): ServiceSetup;
withHover(): ServiceSetup;
withCompletion(): ServiceSetup;
withFormat(): ServiceSetup;
withKubernetes(allow?: boolean): ServiceSetup;
withSchemaFileMatch(schemaFileMatch: SchemasSettings): ServiceSetup;
withCustomTags(customTags: string[]): ServiceSetup;
withIndentation(indentation: string): ServiceSetup;
withFlowMapping(mapping: 'allow' | 'forbid'): ServiceSetup;
withFlowSequence(sequence: 'allow' | 'forbid'): ServiceSetup;
withKeyOrdering(order?: boolean): ServiceSetup;
}

View File

@@ -0,0 +1,70 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ServiceSetup = void 0;
class ServiceSetup {
constructor() {
/*
* By default the service setup is going to have everything disabled
* and each test is going to enable a feature with a with function call
*/
this.languageSettings = {
validate: false,
hover: false,
completion: false,
format: false,
isKubernetes: false,
schemas: [],
customTags: [],
indentation: undefined,
yamlVersion: '1.2',
flowMapping: 'allow',
flowSequence: 'allow',
};
}
withValidate() {
this.languageSettings.validate = true;
return this;
}
withHover() {
this.languageSettings.hover = true;
return this;
}
withCompletion() {
this.languageSettings.completion = true;
return this;
}
withFormat() {
this.languageSettings.format = true;
return this;
}
withKubernetes(allow = true) {
this.languageSettings.isKubernetes = allow;
return this;
}
withSchemaFileMatch(schemaFileMatch) {
this.languageSettings.schemas.push(schemaFileMatch);
return this;
}
withCustomTags(customTags) {
this.languageSettings.customTags = customTags;
return this;
}
withIndentation(indentation) {
this.languageSettings.indentation = indentation;
return this;
}
withFlowMapping(mapping) {
this.languageSettings.flowMapping = mapping;
return this;
}
withFlowSequence(sequence) {
this.languageSettings.flowSequence = sequence;
return this;
}
withKeyOrdering(order = true) {
this.languageSettings.keyOrdering = order;
return this;
}
}
exports.ServiceSetup = ServiceSetup;
//# sourceMappingURL=serviceSetup.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"serviceSetup.js","sourceRoot":"","sources":["../../../../test/utils/serviceSetup.ts"],"names":[],"mappings":";;;AAMA,MAAa,YAAY;IAAzB;QACE;;;WAGG;QACH,qBAAgB,GAAqB;YACnC,QAAQ,EAAE,KAAK;YACf,KAAK,EAAE,KAAK;YACZ,UAAU,EAAE,KAAK;YACjB,MAAM,EAAE,KAAK;YACb,YAAY,EAAE,KAAK;YACnB,OAAO,EAAE,EAAE;YACX,UAAU,EAAE,EAAE;YACd,WAAW,EAAE,SAAS;YACtB,WAAW,EAAE,KAAK;YAClB,WAAW,EAAE,OAAO;YACpB,YAAY,EAAE,OAAO;SACtB,CAAC;IAsDJ,CAAC;IApDC,YAAY;QACV,IAAI,CAAC,gBAAgB,CAAC,QAAQ,GAAG,IAAI,CAAC;QACtC,OAAO,IAAI,CAAC;IACd,CAAC;IAED,SAAS;QACP,IAAI,CAAC,gBAAgB,CAAC,KAAK,GAAG,IAAI,CAAC;QACnC,OAAO,IAAI,CAAC;IACd,CAAC;IAED,cAAc;QACZ,IAAI,CAAC,gBAAgB,CAAC,UAAU,GAAG,IAAI,CAAC;QACxC,OAAO,IAAI,CAAC;IACd,CAAC;IAED,UAAU;QACR,IAAI,CAAC,gBAAgB,CAAC,MAAM,GAAG,IAAI,CAAC;QACpC,OAAO,IAAI,CAAC;IACd,CAAC;IAED,cAAc,CAAC,KAAK,GAAG,IAAI;QACzB,IAAI,CAAC,gBAAgB,CAAC,YAAY,GAAG,KAAK,CAAC;QAC3C,OAAO,IAAI,CAAC;IACd,CAAC;IAED,mBAAmB,CAAC,eAAgC;QAClD,IAAI,CAAC,gBAAgB,CAAC,OAAO,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC;QACpD,OAAO,IAAI,CAAC;IACd,CAAC;IAED,cAAc,CAAC,UAAoB;QACjC,IAAI,CAAC,gBAAgB,CAAC,UAAU,GAAG,UAAU,CAAC;QAC9C,OAAO,IAAI,CAAC;IACd,CAAC;IAED,eAAe,CAAC,WAAmB;QACjC,IAAI,CAAC,gBAAgB,CAAC,WAAW,GAAG,WAAW,CAAC;QAChD,OAAO,IAAI,CAAC;IACd,CAAC;IACD,eAAe,CAAC,OAA2B;QACzC,IAAI,CAAC,gBAAgB,CAAC,WAAW,GAAG,OAAO,CAAC;QAC5C,OAAO,IAAI,CAAC;IACd,CAAC;IAED,gBAAgB,CAAC,QAA4B;QAC3C,IAAI,CAAC,gBAAgB,CAAC,YAAY,GAAG,QAAQ,CAAC;QAC9C,OAAO,IAAI,CAAC;IACd,CAAC;IACD,eAAe,CAAC,KAAK,GAAG,IAAI;QAC1B,IAAI,CAAC,gBAAgB,CAAC,WAAW,GAAG,KAAK,CAAC;QAC1C,OAAO,IAAI,CAAC;IACd,CAAC;CACF;AAvED,oCAuEC"}

View File

@@ -0,0 +1,78 @@
import { SettingsState } from '../../src/yamlSettings';
import { FileSystem } from '../../src/languageservice/services/schemaRequestHandler';
import { LanguageService, LanguageSettings } from '../../src';
import { ValidationHandler } from '../../src/languageserver/handlers/validationHandlers';
import { LanguageHandlers } from '../../src/languageserver/handlers/languageHandlers';
import { TextDocument } from 'vscode-languageserver-textdocument';
import { TestTelemetry } from './testsTypes';
import { JSONSchema } from '../../src/languageservice/jsonSchema';
export declare function toFsPath(str: unknown): string;
export declare const TEST_URI = "file://~/Desktop/vscode-k8s/test.yaml";
export declare const SCHEMA_ID = "default_schema_id.yaml";
export declare function setupTextDocument(content: string): TextDocument;
export declare function setupSchemaIDTextDocument(content: string, customSchemaID?: string): TextDocument;
export declare const testFileSystem: FileSystem;
export interface TestLanguageServerSetup {
languageService: LanguageService;
validationHandler: ValidationHandler;
languageHandler: LanguageHandlers;
yamlSettings: SettingsState;
telemetry: TestTelemetry;
schemaProvider: TestCustomSchemaProvider;
}
export declare function setupLanguageService(languageSettings: LanguageSettings): TestLanguageServerSetup;
/**
* Derives the absolute `position` of the caret given `content` containing a virtual caret.
* @param content The content of the document.
* The caret is located in the content using `|` bookends.
* For example, `content = 'ab|c|d'` places the caret over the `'c'`, at `position = 2`
* @returns The absolute position of the caret.
*/
export declare function caretPosition(content: string): {
position: number;
content: string;
};
export declare class TestCustomSchemaProvider {
private schemas;
private static self;
private constructor();
static instance(): TestCustomSchemaProvider;
/**
* Adds a schema to the list of custom schemas.
* @param doc The uri of the document
* @param schema The JSON schema object.
*/
addSchema(doc: string, schema: JSONSchema): void;
/**
* Adds a schema to the list of custom schemas.
* @param doc The uri of the document
* @param uri The uri of the schema
* @param schema The JSON schema object.
*/
addSchemaWithUri(doc: string, uri: string, schema: JSONSchema): void;
/**
* Deletes a schema from the list of custom schemas.
* @param doc The uri of the document
*/
deleteSchema(doc: string): void;
/**
* Checks if a schema exists for a given document.
* @param doc The uri of the document
* @returns True if a schema exists for the document, false otherwise.
*/
has(doc: string): boolean;
/**
* Returns the schemas for a given document
* @param doc The uri of the document.
* @returns The uris of the schemas
* @throws Error if no schema found
*/
getSchemas(doc: string): string | string[];
/**
* Returns the content of a schema for a given uri.
* @param uri The uri of the schema.
* @returns The content of the schema as a string, or null if the schema is not found.
*/
getContentForSchema(uri: string): string | null;
}
export declare function schemaItSelfCustomSchemaProvider(uri: string): Promise<string | string[]>;

View File

@@ -0,0 +1,197 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.schemaItSelfCustomSchemaProvider = exports.TestCustomSchemaProvider = exports.caretPosition = exports.setupLanguageService = exports.testFileSystem = exports.setupSchemaIDTextDocument = exports.setupTextDocument = exports.SCHEMA_ID = exports.TEST_URI = exports.toFsPath = void 0;
/*---------------------------------------------------------------------------------------------
* Copyright (c) Red Hat. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
const node_1 = require("vscode-languageserver/node");
const path = require("path");
const fs_1 = require("fs");
const yamlSettings_1 = require("../../src/yamlSettings");
const schemaRequestHandler_1 = require("../../src/languageservice/services/schemaRequestHandler");
const yamlServerInit_1 = require("../../src/yamlServerInit");
const vscode_languageserver_textdocument_1 = require("vscode-languageserver-textdocument");
const vscode_json_languageservice_1 = require("vscode-json-languageservice");
const yaml_documents_1 = require("../../src/languageservice/parser/yaml-documents");
const testsTypes_1 = require("./testsTypes");
function toFsPath(str) {
if (typeof str !== 'string') {
throw new TypeError(`Expected a string, got ${typeof str}`);
}
let pathName;
pathName = path.resolve(str);
pathName = pathName.replace(/\\/g, '/');
// Windows drive letter must be prefixed with a slash
if (pathName[0] !== '/') {
pathName = `/${pathName}`;
}
return encodeURI(`file://${pathName}`).replace(/[?#]/g, encodeURIComponent);
}
exports.toFsPath = toFsPath;
exports.TEST_URI = 'file://~/Desktop/vscode-k8s/test.yaml';
exports.SCHEMA_ID = 'default_schema_id.yaml';
function setupTextDocument(content) {
yaml_documents_1.yamlDocumentsCache.clear(); // clear cache
return vscode_languageserver_textdocument_1.TextDocument.create(exports.TEST_URI, 'yaml', 0, content);
}
exports.setupTextDocument = setupTextDocument;
function setupSchemaIDTextDocument(content, customSchemaID) {
yaml_documents_1.yamlDocumentsCache.clear(); // clear cache
if (customSchemaID) {
return vscode_languageserver_textdocument_1.TextDocument.create(customSchemaID, 'yaml', 0, content);
}
else {
return vscode_languageserver_textdocument_1.TextDocument.create(exports.SCHEMA_ID, 'yaml', 0, content);
}
}
exports.setupSchemaIDTextDocument = setupSchemaIDTextDocument;
exports.testFileSystem = { readFile: (fsPath) => fs_1.promises.readFile(fsPath).then((c) => c.toString()) };
function setupLanguageService(languageSettings) {
const yamlSettings = new yamlSettings_1.SettingsState();
process.argv.push('--node-ipc');
const connection = (0, node_1.createConnection)();
const schemaRequestHandlerWrapper = (connection, uri) => {
const testSchemaProvider = TestCustomSchemaProvider.instance();
const testSchema = testSchemaProvider.getContentForSchema(uri);
if (testSchema) {
return Promise.resolve(testSchema);
}
return (0, schemaRequestHandler_1.schemaRequestHandler)(connection, uri, yamlSettings.workspaceFolders, yamlSettings.workspaceRoot, yamlSettings.useVSCodeContentRequest, exports.testFileSystem);
};
const schemaRequestService = schemaRequestHandlerWrapper.bind(this, connection);
const telemetry = new testsTypes_1.TestTelemetry(connection);
const serverInit = new yamlServerInit_1.YAMLServerInit(connection, yamlSettings, schemaRequestHandler_1.workspaceContext, schemaRequestService, telemetry);
serverInit.connectionInitialized({
processId: null,
capabilities: vscode_json_languageservice_1.ClientCapabilities.LATEST,
rootUri: null,
workspaceFolders: null,
});
const languageService = serverInit.languageService;
const validationHandler = serverInit.validationHandler;
const languageHandler = serverInit.languageHandler;
languageService.configure(languageSettings);
const schemaProvider = TestCustomSchemaProvider.instance();
languageService.registerCustomSchemaProvider(schemaItSelfCustomSchemaProvider);
return {
languageService,
validationHandler,
languageHandler,
yamlSettings,
telemetry,
schemaProvider,
};
}
exports.setupLanguageService = setupLanguageService;
/**
* Derives the absolute `position` of the caret given `content` containing a virtual caret.
* @param content The content of the document.
* The caret is located in the content using `|` bookends.
* For example, `content = 'ab|c|d'` places the caret over the `'c'`, at `position = 2`
* @returns The absolute position of the caret.
*/
function caretPosition(content) {
// console.log(`was: len: ${content.length}, content: "${content}", str: "${content.substring(position)}"`);
// Find bookends `|.|` in content
const position = content.search(/\|[^]\|/); // | -> any char including newline -> |
if (position === -1)
throw new Error('Error in test case: no caret found in content');
// Elide bookends from content
content = content.substring(0, position) + content.substring(position + 1, position + 2) + content.substring(position + 3);
// console.log(`now: len: ${content.length}, content: "${content}", pos: ${position}, str: "${content.substring(position)}"`);
return { position, content };
}
exports.caretPosition = caretPosition;
/*
* A class that provides custom schemas for testing purposes.
*/
class TestCustomSchemaProvider {
constructor() {
this.schemas = new Array(0);
// use instance only
}
static instance() {
if (!TestCustomSchemaProvider.self) {
TestCustomSchemaProvider.self = new TestCustomSchemaProvider();
}
return TestCustomSchemaProvider.self;
}
/**
* Adds a schema to the list of custom schemas.
* @param doc The uri of the document
* @param schema The JSON schema object.
*/
addSchema(doc, schema) {
this.addSchemaWithUri(doc, `file:///${doc}`, schema);
}
/**
* Adds a schema to the list of custom schemas.
* @param doc The uri of the document
* @param uri The uri of the schema
* @param schema The JSON schema object.
*/
addSchemaWithUri(doc, uri, schema) {
const item = [doc, uri, schema];
this.schemas.push(item);
}
/**
* Deletes a schema from the list of custom schemas.
* @param doc The uri of the document
*/
deleteSchema(doc) {
const items = this.schemas.filter((item) => item[0] === doc);
if (items.length > 0) {
this.schemas = this.schemas.filter((item) => item[0] !== doc);
}
}
/**
* Checks if a schema exists for a given document.
* @param doc The uri of the document
* @returns True if a schema exists for the document, false otherwise.
*/
has(doc) {
const item = this.schemas.findIndex((item) => item[0] === doc);
return item > -1;
}
/**
* Returns the schemas for a given document
* @param doc The uri of the document.
* @returns The uris of the schemas
* @throws Error if no schema found
*/
getSchemas(doc) {
if (this.has(doc)) {
const items = this.schemas.filter((item) => item[0] === doc);
if (items.length === 1) {
return items[0][1];
}
return items.map((item) => {
return item[1];
});
}
throw new Error(`Test schema not found for ${doc}`);
}
/**
* Returns the content of a schema for a given uri.
* @param uri The uri of the schema.
* @returns The content of the schema as a string, or null if the schema is not found.
*/
getContentForSchema(uri) {
const item = this.schemas.findIndex((item) => item[1] === uri);
if (item < 0) {
return null;
}
return JSON.stringify(this.schemas[item][2]);
}
}
exports.TestCustomSchemaProvider = TestCustomSchemaProvider;
async function schemaItSelfCustomSchemaProvider(uri) {
const schemaProvider = TestCustomSchemaProvider.instance();
if (schemaProvider.has(uri)) {
return schemaProvider.getSchemas(uri);
}
return undefined;
}
exports.schemaItSelfCustomSchemaProvider = schemaItSelfCustomSchemaProvider;
//# sourceMappingURL=testHelper.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,27 @@
import { Event, NotificationHandler, RequestHandler } from 'vscode-jsonrpc';
import { ApplyWorkspaceEditParams, WorkspaceEdit, ApplyWorkspaceEditResponse, ConfigurationItem, WorkspaceFolder, WorkspaceFoldersChangeEvent, CreateFilesParams, RenameFilesParams, DeleteFilesParams } from 'vscode-languageserver-protocol';
import { Connection, RemoteWorkspace } from 'vscode-languageserver';
import { TelemetryImpl } from '../../src/languageserver/telemetry';
import { TelemetryEvent } from '../../src/languageservice/telemetry';
export declare class TestWorkspace implements RemoteWorkspace {
connection: Connection;
applyEdit(paramOrEdit: ApplyWorkspaceEditParams | WorkspaceEdit): Promise<ApplyWorkspaceEditResponse>;
getConfiguration(): Promise<any>;
getConfiguration(section: string): Promise<any>;
getConfiguration(item: ConfigurationItem): Promise<any>;
getConfiguration(items: ConfigurationItem[]): Promise<any[]>;
getWorkspaceFolders(): Promise<WorkspaceFolder[]>;
onDidChangeWorkspaceFolders: Event<WorkspaceFoldersChangeEvent>;
onDidCreateFiles(handler: NotificationHandler<CreateFilesParams>): void;
onDidRenameFiles(handler: NotificationHandler<RenameFilesParams>): void;
onDidDeleteFiles(handler: NotificationHandler<DeleteFilesParams>): void;
onWillCreateFiles(handler: RequestHandler<CreateFilesParams, WorkspaceEdit, never>): void;
onWillRenameFiles(handler: RequestHandler<RenameFilesParams, WorkspaceEdit, never>): void;
onWillDeleteFiles(handler: RequestHandler<DeleteFilesParams, WorkspaceEdit, never>): void;
}
export declare class TestTelemetry extends TelemetryImpl {
messages: TelemetryEvent[];
constructor(connection: Connection);
send(event: TelemetryEvent): void;
clearMessages(): void;
}

View File

@@ -0,0 +1,55 @@
"use strict";
/*---------------------------------------------------------------------------------------------
* Copyright (c) Red Hat. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.TestTelemetry = exports.TestWorkspace = void 0;
const telemetry_1 = require("../../src/languageserver/telemetry");
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
class TestWorkspace {
applyEdit(paramOrEdit) {
throw new Error('Method not implemented.');
}
getConfiguration(items) {
throw new Error('Method not implemented.');
}
getWorkspaceFolders() {
throw new Error('Method not implemented.');
}
onDidCreateFiles(handler) {
throw new Error('Method not implemented.');
}
onDidRenameFiles(handler) {
throw new Error('Method not implemented.');
}
onDidDeleteFiles(handler) {
throw new Error('Method not implemented.');
}
onWillCreateFiles(handler) {
throw new Error('Method not implemented.');
}
onWillRenameFiles(handler) {
throw new Error('Method not implemented.');
}
onWillDeleteFiles(handler) {
throw new Error('Method not implemented.');
}
}
exports.TestWorkspace = TestWorkspace;
class TestTelemetry extends telemetry_1.TelemetryImpl {
constructor(connection) {
super(connection);
this.messages = [];
}
send(event) {
this.messages.push(event);
}
clearMessages() {
this.messages = [];
}
}
exports.TestTelemetry = TestTelemetry;
//# sourceMappingURL=testsTypes.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"testsTypes.js","sourceRoot":"","sources":["../../../../test/utils/testsTypes.ts"],"names":[],"mappings":";AAAA;;;gGAGgG;;;AAehG,kEAAmE;AAGnE,uDAAuD;AACvD,sDAAsD;AACtD,sEAAsE;AACtE,MAAa,aAAa;IAExB,SAAS,CAAC,WAAqD;QAC7D,MAAM,IAAI,KAAK,CAAC,yBAAyB,CAAC,CAAC;IAC7C,CAAC;IAKD,gBAAgB,CAAC,KAAW;QAC1B,MAAM,IAAI,KAAK,CAAC,yBAAyB,CAAC,CAAC;IAC7C,CAAC;IACD,mBAAmB;QACjB,MAAM,IAAI,KAAK,CAAC,yBAAyB,CAAC,CAAC;IAC7C,CAAC;IAED,gBAAgB,CAAC,OAA+C;QAC9D,MAAM,IAAI,KAAK,CAAC,yBAAyB,CAAC,CAAC;IAC7C,CAAC;IACD,gBAAgB,CAAC,OAA+C;QAC9D,MAAM,IAAI,KAAK,CAAC,yBAAyB,CAAC,CAAC;IAC7C,CAAC;IACD,gBAAgB,CAAC,OAA+C;QAC9D,MAAM,IAAI,KAAK,CAAC,yBAAyB,CAAC,CAAC;IAC7C,CAAC;IACD,iBAAiB,CAAC,OAAgE;QAChF,MAAM,IAAI,KAAK,CAAC,yBAAyB,CAAC,CAAC;IAC7C,CAAC;IACD,iBAAiB,CAAC,OAAgE;QAChF,MAAM,IAAI,KAAK,CAAC,yBAAyB,CAAC,CAAC;IAC7C,CAAC;IACD,iBAAiB,CAAC,OAAgE;QAChF,MAAM,IAAI,KAAK,CAAC,yBAAyB,CAAC,CAAC;IAC7C,CAAC;CACF;AAlCD,sCAkCC;AAED,MAAa,aAAc,SAAQ,yBAAa;IAE9C,YAAY,UAAsB;QAChC,KAAK,CAAC,UAAU,CAAC,CAAC;QAFpB,aAAQ,GAAqB,EAAE,CAAC;IAGhC,CAAC;IACD,IAAI,CAAC,KAAqB;QACxB,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAC5B,CAAC;IAED,aAAa;QACX,IAAI,CAAC,QAAQ,GAAG,EAAE,CAAC;IACrB,CAAC;CACF;AAZD,sCAYC"}

View File

@@ -0,0 +1,8 @@
import { CompletionItem, CompletionItemKind, Diagnostic, DiagnosticSeverity, DocumentSymbol, InsertTextFormat, SymbolKind, SymbolInformation } from 'vscode-languageserver-types';
export declare function createExpectedError(message: string, startLine: number, startCharacter: number, endLine: number, endCharacter: number, severity?: DiagnosticSeverity, source?: string, code?: string | number): Diagnostic;
export declare function createDiagnosticWithData(message: string, startLine: number, startCharacter: number, endLine: number, endCharacter: number, severity: DiagnosticSeverity, source: string, schemaUri: string | string[], data?: Record<string, unknown>): Diagnostic;
export declare function createUnusedAnchorDiagnostic(message: string, startLine: number, startCharacter: number, endLine: number, endCharacter: number): Diagnostic;
export declare function createExpectedSymbolInformation(name: string, kind: SymbolKind, containerName: string | undefined, uri: string, startLine: number, startCharacter: number, endLine: number, endCharacter: number): SymbolInformation;
export declare function createExpectedDocumentSymbol(name: string, kind: SymbolKind, startLine: number, startCharacter: number, endLine: number, endCharacter: number, startLineSelection: number, startCharacterSelection: number, endLineSelection: number, endCharacterSelection: number, children?: DocumentSymbol[], detail?: string): DocumentSymbol;
export declare function createExpectedDocumentSymbolNoDetail(name: string, kind: SymbolKind, startLine: number, startCharacter: number, endLine: number, endCharacter: number, startLineSelection: number, startCharacterSelection: number, endLineSelection: number, endCharacterSelection: number, children?: DocumentSymbol[]): DocumentSymbol;
export declare function createExpectedCompletion(label: string, insertText: string, startLine: number, startCharacter: number, endLine: number, endCharacter: number, kind: CompletionItemKind, insertTextFormat?: InsertTextFormat, extra?: {}): CompletionItem;

View File

@@ -0,0 +1,82 @@
"use strict";
/*---------------------------------------------------------------------------------------------
* Copyright (c) Red Hat. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.createExpectedCompletion = exports.createExpectedDocumentSymbolNoDetail = exports.createExpectedDocumentSymbol = exports.createExpectedSymbolInformation = exports.createUnusedAnchorDiagnostic = exports.createDiagnosticWithData = exports.createExpectedError = void 0;
const vscode_languageserver_types_1 = require("vscode-languageserver-types");
const vscode_json_languageservice_1 = require("vscode-json-languageservice");
function createExpectedError(message, startLine, startCharacter, endLine, endCharacter, severity = 1, source = 'YAML', code = vscode_json_languageservice_1.ErrorCode.Undefined) {
return vscode_languageserver_types_1.Diagnostic.create(vscode_languageserver_types_1.Range.create(startLine, startCharacter, endLine, endCharacter), message, severity, code, source);
}
exports.createExpectedError = createExpectedError;
function createDiagnosticWithData(message, startLine, startCharacter, endLine, endCharacter, severity = 1, source = 'YAML', schemaUri, data = {}) {
const diagnostic = createExpectedError(message, startLine, startCharacter, endLine, endCharacter, severity, source);
diagnostic.data = { schemaUri: typeof schemaUri === 'string' ? [schemaUri] : schemaUri, ...data };
return diagnostic;
}
exports.createDiagnosticWithData = createDiagnosticWithData;
function createUnusedAnchorDiagnostic(message, startLine, startCharacter, endLine, endCharacter) {
const diagnostic = createExpectedError(message, startLine, startCharacter, endLine, endCharacter, vscode_languageserver_types_1.DiagnosticSeverity.Hint, 'YAML');
diagnostic.tags = [vscode_languageserver_types_1.DiagnosticTag.Unnecessary];
return diagnostic;
}
exports.createUnusedAnchorDiagnostic = createUnusedAnchorDiagnostic;
function createExpectedSymbolInformation(name, kind, containerName, uri, startLine, startCharacter, endLine, endCharacter) {
return {
name,
kind,
containerName,
location: {
uri,
range: {
start: {
line: startLine,
character: startCharacter,
},
end: {
line: endLine,
character: endCharacter,
},
},
},
};
}
exports.createExpectedSymbolInformation = createExpectedSymbolInformation;
function createExpectedDocumentSymbol(name, kind, startLine, startCharacter, endLine, endCharacter, startLineSelection, startCharacterSelection, endLineSelection, endCharacterSelection, children = [], detail) {
return vscode_languageserver_types_1.DocumentSymbol.create(name, detail, kind, vscode_languageserver_types_1.Range.create(startLine, startCharacter, endLine, endCharacter), vscode_languageserver_types_1.Range.create(startLineSelection, startCharacterSelection, endLineSelection, endCharacterSelection), children);
}
exports.createExpectedDocumentSymbol = createExpectedDocumentSymbol;
function createExpectedDocumentSymbolNoDetail(name, kind, startLine, startCharacter, endLine, endCharacter, startLineSelection, startCharacterSelection, endLineSelection, endCharacterSelection, children = []) {
const docSymbol = vscode_languageserver_types_1.DocumentSymbol.create(name, undefined, kind, vscode_languageserver_types_1.Range.create(startLine, startCharacter, endLine, endCharacter), vscode_languageserver_types_1.Range.create(startLineSelection, startCharacterSelection, endLineSelection, endCharacterSelection), children);
delete docSymbol.detail;
return docSymbol;
}
exports.createExpectedDocumentSymbolNoDetail = createExpectedDocumentSymbolNoDetail;
function createExpectedCompletion(label, insertText, startLine, startCharacter, endLine, endCharacter, kind, insertTextFormat = 2, extra = {}) {
return {
...{
insertText,
label,
insertTextFormat,
kind,
textEdit: {
newText: insertText,
range: {
start: {
line: startLine,
character: startCharacter,
},
end: {
line: endLine,
character: endCharacter,
},
},
},
},
...extra,
};
}
exports.createExpectedCompletion = createExpectedCompletion;
//# sourceMappingURL=verifyError.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"verifyError.js","sourceRoot":"","sources":["../../../../test/utils/verifyError.ts"],"names":[],"mappings":";AAAA;;;gGAGgG;;;AAEhG,6EAWqC;AACrC,6EAAwD;AAExD,SAAgB,mBAAmB,CACjC,OAAe,EACf,SAAiB,EACjB,cAAsB,EACtB,OAAe,EACf,YAAoB,EACpB,WAA+B,CAAC,EAChC,MAAM,GAAG,MAAM,EACf,OAAwB,uCAAS,CAAC,SAAS;IAE3C,OAAO,wCAAU,CAAC,MAAM,CAAC,mCAAK,CAAC,MAAM,CAAC,SAAS,EAAE,cAAc,EAAE,OAAO,EAAE,YAAY,CAAC,EAAE,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;AAC5H,CAAC;AAXD,kDAWC;AAED,SAAgB,wBAAwB,CACtC,OAAe,EACf,SAAiB,EACjB,cAAsB,EACtB,OAAe,EACf,YAAoB,EACpB,WAA+B,CAAC,EAChC,MAAM,GAAG,MAAM,EACf,SAA4B,EAC5B,OAAgC,EAAE;IAElC,MAAM,UAAU,GAAe,mBAAmB,CAAC,OAAO,EAAE,SAAS,EAAE,cAAc,EAAE,OAAO,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAC;IAChI,UAAU,CAAC,IAAI,GAAG,EAAE,SAAS,EAAE,OAAO,SA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 -0,0 +1,198 @@
"use strict";
/*---------------------------------------------------------------------------------------------
* Copyright (c) Red Hat. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
const sinon = require("sinon");
const sinonChai = require("sinon-chai");
const chai = require("chai");
const yaml_documents_1 = require("../src/languageservice/parser/yaml-documents");
const testHelper_1 = require("./utils/testHelper");
const yamlParser = require("../src/languageservice/parser/yamlParser07");
const vscode_languageserver_textdocument_1 = require("vscode-languageserver-textdocument");
const yaml_1 = require("yaml");
const textBuffer_1 = require("../src/languageservice/utils/textBuffer");
const expect = chai.expect;
chai.use(sinonChai);
describe('YAML Documents', () => {
const sandbox = sinon.createSandbox();
describe('YAML Documents Cache Tests', () => {
let parseStub;
beforeEach(() => {
parseStub = sandbox.stub(yamlParser, 'parse');
});
afterEach(() => {
sandbox.restore();
});
it('should cache parsed document', () => {
const cache = new yaml_documents_1.YamlDocuments();
const doc = (0, testHelper_1.setupTextDocument)('foo: bar');
parseStub.returns({});
const result1 = cache.getYamlDocument(doc);
const result2 = cache.getYamlDocument(doc);
expect(parseStub).calledOnce;
expect(result1).to.be.equal(result2);
});
it('should re parse document if document changed', () => {
const cache = new yaml_documents_1.YamlDocuments();
const doc = (0, testHelper_1.setupTextDocument)('foo: bar');
parseStub.onFirstCall().returns({});
parseStub.onSecondCall().returns({ foo: 'bar' });
const result1 = cache.getYamlDocument(doc);
vscode_languageserver_textdocument_1.TextDocument.update(doc, [], 2);
const result2 = cache.getYamlDocument(doc);
expect(parseStub).calledTwice;
expect(result1).to.be.not.equal(result2);
});
it('should invalidate cache if custom tags provided', () => {
const cache = new yaml_documents_1.YamlDocuments();
const doc = (0, testHelper_1.setupTextDocument)('foo: bar');
parseStub.onFirstCall().returns({});
parseStub.onSecondCall().returns({ foo: 'bar' });
const result1 = cache.getYamlDocument(doc);
const result2 = cache.getYamlDocument(doc, getParserOptions(['some']));
expect(parseStub).calledTwice;
expect(result1).to.not.equal(result2);
});
it('should use cache if custom tags are same', () => {
const cache = new yaml_documents_1.YamlDocuments();
const doc = (0, testHelper_1.setupTextDocument)('foo: bar');
parseStub.onFirstCall().returns({});
parseStub.onSecondCall().returns({ foo: 'bar' });
const result1 = cache.getYamlDocument(doc, getParserOptions(['some']));
const result2 = cache.getYamlDocument(doc, getParserOptions(['some']));
expect(parseStub).calledOnce;
expect(result1).to.be.equal(result2);
});
});
describe('Single YAML Document Tests', () => {
let documents;
beforeEach(() => {
documents = new yaml_documents_1.YamlDocuments();
});
afterEach(() => {
sandbox.restore();
});
it('Get node from position: key', () => {
const doc = (0, testHelper_1.setupTextDocument)('foo: bar');
const yamlDoc = documents.getYamlDocument(doc);
const [result] = yamlDoc.documents[0].getNodeFromPosition(2, new textBuffer_1.TextBuffer(doc));
expect(result).is.not.undefined;
expect((0, yaml_1.isScalar)(result)).is.true;
expect(result.value).eqls('foo');
});
it('Get node from position: value', () => {
const doc = (0, testHelper_1.setupTextDocument)('foo: bar');
const yamlDoc = documents.getYamlDocument(doc);
const [result] = yamlDoc.documents[0].getNodeFromPosition(6, new textBuffer_1.TextBuffer(doc));
expect(result).is.not.undefined;
expect((0, yaml_1.isScalar)(result)).is.true;
expect(result.value).eqls('bar');
});
it('Get node from position: map', () => {
const doc = (0, testHelper_1.setupTextDocument)('foo: bar');
const yamlDoc = documents.getYamlDocument(doc);
const [result] = yamlDoc.documents[0].getNodeFromPosition(4, new textBuffer_1.TextBuffer(doc));
expect(result).is.not.undefined;
expect((0, yaml_1.isMap)(result)).is.true;
expect(result.items).length(1);
});
it('Get node from position: scalar in array', () => {
const doc = (0, testHelper_1.setupTextDocument)('foo:\n - bar');
const yamlDoc = documents.getYamlDocument(doc);
const [result] = yamlDoc.documents[0].getNodeFromPosition(9, new textBuffer_1.TextBuffer(doc));
expect(result).is.not.undefined;
expect((0, yaml_1.isScalar)(result)).is.true;
expect(result.value).equal('bar');
});
it('Get node from position: array', () => {
const doc = (0, testHelper_1.setupTextDocument)('foo:\n - bar');
const yamlDoc = documents.getYamlDocument(doc);
const [result] = yamlDoc.documents[0].getNodeFromPosition(8, new textBuffer_1.TextBuffer(doc));
expect(result).is.not.undefined;
expect((0, yaml_1.isSeq)(result)).is.true;
expect(result.items).length(1);
});
it('Get node from position: map with array', () => {
const doc = (0, testHelper_1.setupTextDocument)('foo:\n - bar');
const yamlDoc = documents.getYamlDocument(doc);
const [result] = yamlDoc.documents[0].getNodeFromPosition(6, new textBuffer_1.TextBuffer(doc));
expect(result).is.not.undefined;
expect((0, yaml_1.isMap)(result)).is.true;
expect(result.items).length(1);
});
it('Get node from position: flow map key', () => {
const doc = (0, testHelper_1.setupTextDocument)('{foo: bar}');
const yamlDoc = documents.getYamlDocument(doc);
const [result] = yamlDoc.documents[0].getNodeFromPosition(3, new textBuffer_1.TextBuffer(doc));
expect(result).is.not.undefined;
expect((0, yaml_1.isScalar)(result)).is.true;
expect(result.value).eqls('foo');
});
it('Get node from position: flow map value', () => {
const doc = (0, testHelper_1.setupTextDocument)('{foo: bar}');
const yamlDoc = documents.getYamlDocument(doc);
const [result] = yamlDoc.documents[0].getNodeFromPosition(8, new textBuffer_1.TextBuffer(doc));
expect(result).is.not.undefined;
expect((0, yaml_1.isScalar)(result)).is.true;
expect(result.value).eqls('bar');
});
it('get pair parent in array', () => {
const doc = (0, testHelper_1.setupTextDocument)(`objA:
- name: nameA1
objB:
size: midle
name: nameB2
`);
const yamlDoc = documents.getYamlDocument(doc);
const result = yamlDoc.documents[0].findClosestNode(27, new textBuffer_1.TextBuffer(doc));
expect(result).is.not.undefined;
expect((0, yaml_1.isMap)(result)).is.true;
const resultItem = result.items[0];
expect(resultItem.key).property('value', 'name');
expect(resultItem.value).property('value', 'nameA1');
});
it('Find closes node: map', () => {
const doc = (0, testHelper_1.setupTextDocument)('foo:\n bar: aaa\n ');
const yamlDoc = documents.getYamlDocument(doc);
const textBuffer = new textBuffer_1.TextBuffer(doc);
const result = yamlDoc.documents[0].findClosestNode(18, textBuffer);
expect(result).is.not.undefined;
expect((0, yaml_1.isMap)(result)).is.true;
expect(result.items[0].key.value).eqls('bar');
});
it('Find closes node: array', () => {
const doc = (0, testHelper_1.setupTextDocument)('foo:\n - bar: aaa\n ');
const yamlDoc = documents.getYamlDocument(doc);
const textBuffer = new textBuffer_1.TextBuffer(doc);
const result = yamlDoc.documents[0].findClosestNode(20, textBuffer);
expect(result).is.not.undefined;
expect((0, yaml_1.isSeq)(result)).is.true;
expect(result.items[0].items[0].key.value).eqls('bar');
});
it('Find closes node: root map', () => {
const doc = (0, testHelper_1.setupTextDocument)('foo:\n bar: aaa\n ');
const yamlDoc = documents.getYamlDocument(doc);
const textBuffer = new textBuffer_1.TextBuffer(doc);
const result = yamlDoc.documents[0].findClosestNode(17, textBuffer);
expect(result).is.not.undefined;
expect((0, yaml_1.isMap)(result)).is.true;
expect(result.items[0].key.value).eqls('bar');
});
it('should parse document when no yamlVersion is provided', () => {
const doc = (0, testHelper_1.setupTextDocument)('foo: bar');
const opts = {
customTags: ['some'],
yamlVersion: undefined,
};
const yamlDoc = documents.getYamlDocument(doc, opts);
expect(yamlDoc).is.not.undefined;
});
});
});
function getParserOptions(customTags) {
return { customTags, yamlVersion: '1.2' };
}
//# sourceMappingURL=yaml-documents.test.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
export {};

View File

@@ -0,0 +1,280 @@
"use strict";
/*---------------------------------------------------------------------------------------------
* Copyright (c) Red Hat, Inc. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
const sinon = require("sinon");
const sinonChai = require("sinon-chai");
const chai = require("chai");
const yamlCodeActions_1 = require("../src/languageservice/services/yamlCodeActions");
const vscode_languageserver_types_1 = require("vscode-languageserver-types");
const testHelper_1 = require("./utils/testHelper");
const verifyError_1 = require("./utils/verifyError");
const commands_1 = require("../src/commands");
const expect = chai.expect;
chai.use(sinonChai);
const JSON_SCHEMA_LOCAL = 'file://some/path/schema.json';
const JSON_SCHEMA2_LOCAL = 'file://some/path/schema2.json';
describe('CodeActions Tests', () => {
const sandbox = sinon.createSandbox();
let clientCapabilities;
beforeEach(() => {
clientCapabilities = {};
});
afterEach(() => {
sandbox.restore();
});
describe('JumpToSchema tests', () => {
it('should not provide any actions if there are no diagnostics', () => {
const doc = (0, testHelper_1.setupTextDocument)('');
const params = {
context: vscode_languageserver_types_1.CodeActionContext.create(undefined),
range: undefined,
textDocument: vscode_languageserver_types_1.TextDocumentIdentifier.create(testHelper_1.TEST_URI),
};
const actions = new yamlCodeActions_1.YamlCodeActions(clientCapabilities);
const result = actions.getCodeAction(doc, params);
expect(result).to.be.undefined;
});
it('should provide action if diagnostic has uri for schema', () => {
const doc = (0, testHelper_1.setupTextDocument)('');
const diagnostics = [(0, verifyError_1.createDiagnosticWithData)('foo', 0, 0, 0, 0, 1, JSON_SCHEMA_LOCAL, JSON_SCHEMA_LOCAL)];
const params = {
context: vscode_languageserver_types_1.CodeActionContext.create(diagnostics),
range: undefined,
textDocument: vscode_languageserver_types_1.TextDocumentIdentifier.create(testHelper_1.TEST_URI),
};
clientCapabilities.window = { showDocument: { support: true } };
const actions = new yamlCodeActions_1.YamlCodeActions(clientCapabilities);
const result = actions.getCodeAction(doc, params);
const codeAction = vscode_languageserver_types_1.CodeAction.create('Jump to schema location (schema.json)', vscode_languageserver_types_1.Command.create('JumpToSchema', commands_1.YamlCommands.JUMP_TO_SCHEMA, JSON_SCHEMA_LOCAL));
codeAction.diagnostics = diagnostics;
expect(result[0]).to.deep.equal(codeAction);
});
it('should provide multiple action if diagnostic has uri for multiple schemas', () => {
const doc = (0, testHelper_1.setupTextDocument)('');
const diagnostics = [
(0, verifyError_1.createDiagnosticWithData)('foo', 0, 0, 0, 0, 1, JSON_SCHEMA_LOCAL, [JSON_SCHEMA_LOCAL, JSON_SCHEMA2_LOCAL]),
];
const params = {
context: vscode_languageserver_types_1.CodeActionContext.create(diagnostics),
range: undefined,
textDocument: vscode_languageserver_types_1.TextDocumentIdentifier.create(testHelper_1.TEST_URI),
};
clientCapabilities.window = { showDocument: { support: true } };
const actions = new yamlCodeActions_1.YamlCodeActions(clientCapabilities);
const result = actions.getCodeAction(doc, params);
const codeAction = vscode_languageserver_types_1.CodeAction.create('Jump to schema location (schema.json)', vscode_languageserver_types_1.Command.create('JumpToSchema', commands_1.YamlCommands.JUMP_TO_SCHEMA, JSON_SCHEMA_LOCAL));
const codeAction2 = vscode_languageserver_types_1.CodeAction.create('Jump to schema location (schema2.json)', vscode_languageserver_types_1.Command.create('JumpToSchema', commands_1.YamlCommands.JUMP_TO_SCHEMA, JSON_SCHEMA2_LOCAL));
codeAction.diagnostics = diagnostics;
codeAction2.diagnostics = diagnostics;
expect(result[0]).to.deep.equal(codeAction);
expect(result[1]).to.deep.equal(codeAction2);
});
});
describe('Convert TAB to Spaces', () => {
it('should add "Convert TAB to Spaces" CodeAction', () => {
const doc = (0, testHelper_1.setupTextDocument)('foo:\n\t- bar');
const diagnostics = [(0, verifyError_1.createExpectedError)('Using tabs can lead to unpredictable results', 1, 0, 1, 1, 1, JSON_SCHEMA_LOCAL)];
const params = {
context: vscode_languageserver_types_1.CodeActionContext.create(diagnostics),
range: undefined,
textDocument: vscode_languageserver_types_1.TextDocumentIdentifier.create(testHelper_1.TEST_URI),
};
const actions = new yamlCodeActions_1.YamlCodeActions(clientCapabilities);
const result = actions.getCodeAction(doc, params);
expect(result).to.has.length(2);
expect(result[0].title).to.be.equal('Convert Tab to Spaces');
expect(vscode_languageserver_types_1.WorkspaceEdit.is(result[0].edit)).to.be.true;
expect(result[0].edit.changes[testHelper_1.TEST_URI]).deep.equal([vscode_languageserver_types_1.TextEdit.replace(vscode_languageserver_types_1.Range.create(1, 0, 1, 1), ' ')]);
});
it('should support current indentation chars settings', () => {
const doc = (0, testHelper_1.setupTextDocument)('foo:\n\t- bar');
const diagnostics = [(0, verifyError_1.createExpectedError)('Using tabs can lead to unpredictable results', 1, 0, 1, 1, 1, JSON_SCHEMA_LOCAL)];
const params = {
context: vscode_languageserver_types_1.CodeActionContext.create(diagnostics),
range: undefined,
textDocument: vscode_languageserver_types_1.TextDocumentIdentifier.create(testHelper_1.TEST_URI),
};
const actions = new yamlCodeActions_1.YamlCodeActions(clientCapabilities);
actions.configure({ indentation: ' ' });
const result = actions.getCodeAction(doc, params);
expect(result[0].title).to.be.equal('Convert Tab to Spaces');
expect(result[0].edit.changes[testHelper_1.TEST_URI]).deep.equal([vscode_languageserver_types_1.TextEdit.replace(vscode_languageserver_types_1.Range.create(1, 0, 1, 1), ' ')]);
});
it('should provide "Convert all Tabs to Spaces"', () => {
const doc = (0, testHelper_1.setupTextDocument)('foo:\n\t\t\t- bar\n\t\t');
const diagnostics = [(0, verifyError_1.createExpectedError)('Using tabs can lead to unpredictable results', 1, 0, 1, 3, 1, JSON_SCHEMA_LOCAL)];
const params = {
context: vscode_languageserver_types_1.CodeActionContext.create(diagnostics),
range: undefined,
textDocument: vscode_languageserver_types_1.TextDocumentIdentifier.create(testHelper_1.TEST_URI),
};
const actions = new yamlCodeActions_1.YamlCodeActions(clientCapabilities);
const result = actions.getCodeAction(doc, params);
expect(result[1].title).to.be.equal('Convert all Tabs to Spaces');
expect(result[1].edit.changes[testHelper_1.TEST_URI]).deep.equal([
vscode_languageserver_types_1.TextEdit.replace(vscode_languageserver_types_1.Range.create(1, 0, 1, 3), ' '),
vscode_languageserver_types_1.TextEdit.replace(vscode_languageserver_types_1.Range.create(2, 0, 2, 2), ' '),
]);
});
});
describe('Remove Unused Anchor', () => {
it('should generate proper action', () => {
const doc = (0, testHelper_1.setupTextDocument)('foo: &bar bar\n');
const diagnostics = [(0, verifyError_1.createUnusedAnchorDiagnostic)('Unused anchor "&bar"', 0, 5, 0, 9)];
const params = {
context: vscode_languageserver_types_1.CodeActionContext.create(diagnostics),
range: undefined,
textDocument: vscode_languageserver_types_1.TextDocumentIdentifier.create(testHelper_1.TEST_URI),
};
const actions = new yamlCodeActions_1.YamlCodeActions(clientCapabilities);
const result = actions.getCodeAction(doc, params);
expect(result[0].title).to.be.equal('Delete unused anchor: &bar');
expect(result[0].edit.changes[testHelper_1.TEST_URI]).deep.equal([vscode_languageserver_types_1.TextEdit.del(vscode_languageserver_types_1.Range.create(0, 5, 0, 10))]);
});
it('should delete all whitespace after unused anchor', () => {
const doc = (0, testHelper_1.setupTextDocument)('foo: &bar \tbar\n');
const diagnostics = [(0, verifyError_1.createUnusedAnchorDiagnostic)('Unused anchor "&bar"', 0, 5, 0, 9)];
const params = {
context: vscode_languageserver_types_1.CodeActionContext.create(diagnostics),
range: undefined,
textDocument: vscode_languageserver_types_1.TextDocumentIdentifier.create(testHelper_1.TEST_URI),
};
const actions = new yamlCodeActions_1.YamlCodeActions(clientCapabilities);
const result = actions.getCodeAction(doc, params);
expect(result[0].title).to.be.equal('Delete unused anchor: &bar');
expect(result[0].edit.changes[testHelper_1.TEST_URI]).deep.equal([vscode_languageserver_types_1.TextEdit.del(vscode_languageserver_types_1.Range.create(0, 5, 0, 13))]);
});
});
describe('Convert to Block Style', () => {
it(' should generate action to convert flow map to block map ', () => {
const yaml = `host: phl-42
datacenter: {location: canada , cab: 15}
animals: [dog , cat , mouse] `;
const doc = (0, testHelper_1.setupTextDocument)(yaml);
const diagnostics = [
(0, verifyError_1.createExpectedError)('Flow style mapping is forbidden', 1, 12, 1, 39, vscode_languageserver_types_1.DiagnosticSeverity.Error, 'YAML', 'flowMap'),
(0, verifyError_1.createExpectedError)('Flow style sequence is forbidden', 2, 9, 2, 27, vscode_languageserver_types_1.DiagnosticSeverity.Error, 'YAML', 'flowSeq'),
];
const params = {
context: vscode_languageserver_types_1.CodeActionContext.create(diagnostics),
range: undefined,
textDocument: vscode_languageserver_types_1.TextDocumentIdentifier.create(testHelper_1.TEST_URI),
};
const actions = new yamlCodeActions_1.YamlCodeActions(clientCapabilities);
const result = actions.getCodeAction(doc, params);
expect(result).to.be.not.empty;
expect(result).to.have.lengthOf(2);
expect(result[0].edit.changes[testHelper_1.TEST_URI]).deep.equal([
vscode_languageserver_types_1.TextEdit.replace(vscode_languageserver_types_1.Range.create(1, 12, 1, 39), `\n location: canada \n cab: 15`),
]);
expect(result[1].edit.changes[testHelper_1.TEST_URI]).deep.equal([
vscode_languageserver_types_1.TextEdit.replace(vscode_languageserver_types_1.Range.create(2, 9, 2, 27), `\n - dog \n - cat \n - mouse`),
]);
});
});
describe('Map Key Order', () => {
it(' should generate action to order a map with incorrect key order', () => {
const yaml = '- key 2: v\n key 1: val\n key 5: valu\n key 3: ff';
const doc = (0, testHelper_1.setupTextDocument)(yaml);
const diagnostics = [
(0, verifyError_1.createExpectedError)('Wrong ordering of key "key 2" in mapping', 0, 2, 0, 9, vscode_languageserver_types_1.DiagnosticSeverity.Error, 'YAML', 'mapKeyOrder'),
(0, verifyError_1.createExpectedError)('Wrong ordering of key "key 5" in mapping', 2, 0, 2, 9, vscode_languageserver_types_1.DiagnosticSeverity.Error, 'YAML', 'mapKeyOrder'),
];
const params = {
context: vscode_languageserver_types_1.CodeActionContext.create(diagnostics),
range: undefined,
textDocument: vscode_languageserver_types_1.TextDocumentIdentifier.create(testHelper_1.TEST_URI),
};
const actions = new yamlCodeActions_1.YamlCodeActions(clientCapabilities);
const result = actions.getCodeAction(doc, params);
expect(result).to.be.not.empty;
expect(result).to.have.lengthOf(2);
expect(result[0].edit.changes[testHelper_1.TEST_URI]).deep.equal([
vscode_languageserver_types_1.TextEdit.replace(vscode_languageserver_types_1.Range.create(0, 2, 3, 11), `key 1: val\n key 2: v\n key 3: ff\n key 5: valu`),
]);
expect(result[1].edit.changes[testHelper_1.TEST_URI]).deep.equal([
vscode_languageserver_types_1.TextEdit.replace(vscode_languageserver_types_1.Range.create(0, 2, 3, 11), `key 1: val\n key 2: v\n key 3: ff\n key 5: valu`),
]);
});
it(' should generate action to order nested and block maps', () => {
const yaml = '- key 2: v\n key 1: val\n key 5: {b: 1, a: 2}\n ';
const doc = (0, testHelper_1.setupTextDocument)(yaml);
const diagnostics = [
(0, verifyError_1.createExpectedError)('Wrong ordering of key "key 2" in mapping', 0, 2, 0, 9, vscode_languageserver_types_1.DiagnosticSeverity.Error, 'YAML', 'mapKeyOrder'),
(0, verifyError_1.createExpectedError)('Wrong ordering of key "key b" in mapping', 2, 9, 3, 0, vscode_languageserver_types_1.DiagnosticSeverity.Error, 'YAML', 'mapKeyOrder'),
];
const params = {
context: vscode_languageserver_types_1.CodeActionContext.create(diagnostics),
range: undefined,
textDocument: vscode_languageserver_types_1.TextDocumentIdentifier.create(testHelper_1.TEST_URI),
};
const actions = new yamlCodeActions_1.YamlCodeActions(clientCapabilities);
const result = actions.getCodeAction(doc, params);
expect(result).to.be.not.empty;
expect(result).to.have.lengthOf(2);
expect(result[0].edit.changes[testHelper_1.TEST_URI]).deep.equal([
vscode_languageserver_types_1.TextEdit.replace(vscode_languageserver_types_1.Range.create(0, 2, 3, 0), `key 1: val\n key 2: v\n key 5: {b: 1, a: 2}\n`),
]);
expect(result[1].edit.changes[testHelper_1.TEST_URI]).deep.equal([vscode_languageserver_types_1.TextEdit.replace(vscode_languageserver_types_1.Range.create(2, 9, 2, 21), `{a: 2, b: 1}\n`)]);
});
it(' should generate action to order maps with multi-line strings', () => {
const yaml = '- cc: 1\n gg: 2\n aa: >\n some\n text\n vv: 4';
const doc = (0, testHelper_1.setupTextDocument)(yaml);
const diagnostics = [
(0, verifyError_1.createExpectedError)('Wrong ordering of key "key gg" in mapping', 1, 0, 1, 8, vscode_languageserver_types_1.DiagnosticSeverity.Error, 'YAML', 'mapKeyOrder'),
];
const params = {
context: vscode_languageserver_types_1.CodeActionContext.create(diagnostics),
range: undefined,
textDocument: vscode_languageserver_types_1.TextDocumentIdentifier.create(testHelper_1.TEST_URI),
};
const actions = new yamlCodeActions_1.YamlCodeActions(clientCapabilities);
const result = actions.getCodeAction(doc, params);
expect(result).to.be.not.empty;
expect(result).to.have.lengthOf(1);
expect(result[0].edit.changes[testHelper_1.TEST_URI]).deep.equal([
vscode_languageserver_types_1.TextEdit.replace(vscode_languageserver_types_1.Range.create(0, 2, 5, 7), `aa: >\n some\n text\n cc: 1\n gg: 2\n vv: 4`),
]);
});
it(' should generate actions when values are missing', () => {
const yaml = '- cc: 1\n gg: 2\n aa:';
const doc = (0, testHelper_1.setupTextDocument)(yaml);
const diagnostics = [
(0, verifyError_1.createExpectedError)('Wrong ordering of key "key gg" in mapping', 1, 0, 1, 8, vscode_languageserver_types_1.DiagnosticSeverity.Error, 'YAML', 'mapKeyOrder'),
];
const params = {
context: vscode_languageserver_types_1.CodeActionContext.create(diagnostics),
range: undefined,
textDocument: vscode_languageserver_types_1.TextDocumentIdentifier.create(testHelper_1.TEST_URI),
};
const actions = new yamlCodeActions_1.YamlCodeActions(clientCapabilities);
const result = actions.getCodeAction(doc, params);
expect(result).to.be.not.empty;
expect(result).to.have.lengthOf(1);
expect(result[0].edit.changes[testHelper_1.TEST_URI]).deep.equal([vscode_languageserver_types_1.TextEdit.replace(vscode_languageserver_types_1.Range.create(0, 2, 2, 5), `aa: cc: 1\n gg: 2`)]);
});
it(' should preserve comments', () => {
const yaml = '- cc: 1\n gg: 2 #a comment\n aa: 1';
const doc = (0, testHelper_1.setupTextDocument)(yaml);
const diagnostics = [
(0, verifyError_1.createExpectedError)('Wrong ordering of key "key gg" in mapping', 1, 0, 1, 8, vscode_languageserver_types_1.DiagnosticSeverity.Error, 'YAML', 'mapKeyOrder'),
];
const params = {
context: vscode_languageserver_types_1.CodeActionContext.create(diagnostics),
range: undefined,
textDocument: vscode_languageserver_types_1.TextDocumentIdentifier.create(testHelper_1.TEST_URI),
};
const actions = new yamlCodeActions_1.YamlCodeActions(clientCapabilities);
const result = actions.getCodeAction(doc, params);
expect(result).to.be.not.empty;
expect(result).to.have.lengthOf(1);
expect(result[0].edit.changes[testHelper_1.TEST_URI]).deep.equal([
vscode_languageserver_types_1.TextEdit.replace(vscode_languageserver_types_1.Range.create(0, 2, 2, 7), `aa: 1\n cc: 1\n gg: 2 #a comment`),
]);
});
});
});
//# sourceMappingURL=yamlCodeActions.test.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
export {};

Some files were not shown because too many files have changed in this diff Show More