Feature/jest2 (#322)

* Adding more tests
* adding jest
* fixing tests
* fixing linting
* removing 1 slash less
* fixing more tests
* fixing last test
* more last fixes
This commit is contained in:
Daan Verstraten
2024-11-09 10:08:30 +01:00
committed by GitHub
parent b788f118ff
commit 8e59f63167
39 changed files with 8224 additions and 1158 deletions

View File

@@ -1,50 +0,0 @@
# This is a basic workflow to help you get started with Actions
name: Format json files
# Controls when the action will run.
on:
# Triggers the workflow on push or pull request events but only for the main branch
pull_request:
branches: [main]
# Allows you to run this workflow manually from the Actions tab
workflow_dispatch:
# A workflow run is made up of one or more jobs that can run sequentially or in parallel
jobs:
# This workflow contains a single job called "build"
build:
# The type of runner that the job will run on
runs-on: ubuntu-latest
# Steps represent a sequence of tasks that will be executed as part of the job
steps:
# Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
- name: Checkout
uses: actions/checkout@v4
with:
ref: ${{github.ref}}
# Runs a single command using the runners shell
- name: 🏗️ Setup Node.js Environment
uses: actions/setup-node@v4
with:
cache: npm
cache-dependency-path: package-lock.json
node-version-file: .nvmrc
# Runs a set of commands using the runners shell
- name: Formatting
run: |
cd ${{github.workspace}}
npx prettier --write "source/**/*.json" --config ${{github.workspace}}/scripts/json.prettierrc.json
- name: Commiting
continue-on-error: true
run: |
git add .
git config --global user.email "orbi@blockception.com"
git config --global user.name "Orbi-bot"
git commit -m "auto: Formatted json files"
git push

1
.gitignore vendored
View File

@@ -10,3 +10,4 @@ client/server
lib lib
lib/ lib/
reports reports
coverage

View File

@@ -1 +0,0 @@
test

View File

@@ -1,7 +0,0 @@
{
"color": true,
"extension": ["ts"],
"ui": "bdd",
"recursive": true,
"require": "ts-node/register"
}

28
eslint.config.mjs Normal file
View File

@@ -0,0 +1,28 @@
import eslint from "@eslint/js";
import tseslint from "typescript-eslint";
export default tseslint.config(
{
ignores: [
'**/coverage/*',
'**/lib/*',
'**/node_modules/*',
'lib/*'
],
},
{
files: ["**/*.ts"],
extends: [eslint.configs.recommended, ...tseslint.configs.recommended],
plugins: {
jest: {},
},
},
{
rules: {
"@typescript-eslint/no-namespace": "off",
"@typescript-eslint/no-explicit-any": "off",
"no-case-declarations": "off",
},
}
);

190
jest.config.ts Normal file
View File

@@ -0,0 +1,190 @@
/**
* For a detailed explanation regarding each configuration property, visit:
* https://jestjs.io/docs/configuration
*/
import type { Config } from "jest";
const config: Config = {
// All imported modules in your tests should be mocked automatically
// automock: false,
// Stop running tests after `n` failures
// bail: 0,
// The directory where Jest should store its cached dependency information
// cacheDirectory: "C:\\Users\\daanv\\AppData\\Local\\Temp\\jest",
// Automatically clear mock calls, instances, contexts and results before every test
clearMocks: true,
// Indicates whether the coverage information should be collected while executing the test
collectCoverage: true,
// An array of glob patterns indicating a set of files for which coverage information should be collected
collectCoverageFrom: ["./src", "./test"],
// The directory where Jest should output its coverage files
coverageDirectory: "coverage",
// An array of regexp pattern strings used to skip coverage collection
coveragePathIgnorePatterns: ["node_modules", "coverage"],
// Indicates which provider should be used to instrument code for coverage
coverageProvider: "v8",
// A list of reporter names that Jest uses when writing coverage reports
// coverageReporters: [
// "json",
// "text",
// "lcov",
// "clover"
// ],
// An object that configures minimum threshold enforcement for coverage results
// coverageThreshold: undefined,
// A path to a custom dependency extractor
// dependencyExtractor: undefined,
// Make calling deprecated APIs throw helpful error messages
// errorOnDeprecated: false,
// The default configuration for fake timers
// fakeTimers: {
// "enableGlobally": false
// },
// Force coverage collection from ignored files using an array of glob patterns
// forceCoverageMatch: [],
// A path to a module which exports an async function that is triggered once before all test suites
// globalSetup: undefined,
// A path to a module which exports an async function that is triggered once after all test suites
// globalTeardown: undefined,
// A set of global variables that need to be available in all test environments
// globals: {},
// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
// maxWorkers: "50%",
// An array of directory names to be searched recursively up from the requiring module's location
moduleDirectories: ["node_modules"],
// An array of file extensions your modules use
// moduleFileExtensions: [
// "js",
// "mjs",
// "cjs",
// "jsx",
// "ts",
// "tsx",
// "json",
// "node"
// ],
// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
// moduleNameMapper: {},
// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
// modulePathIgnorePatterns: [],
// Activates notifications for test results
// notify: false,
// An enum that specifies notification mode. Requires { notify: true }
// notifyMode: "failure-change",
// A preset that is used as a base for Jest's configuration
preset: "ts-jest",
// Run tests from one or more projects
// projects: undefined,
// Use this configuration option to add custom reporters to Jest
// reporters: undefined,
// Automatically reset mock state before every test
// resetMocks: false,
// Reset the module registry before running each individual test
// resetModules: false,
// A path to a custom resolver
// resolver: undefined,
// Automatically restore mock state and implementation before every test
// restoreMocks: false,
// The root directory that Jest should scan for tests and modules within
// rootDir: undefined,
// A list of paths to directories that Jest should use to search for files in
roots: ["./src", "./test"],
// Allows you to use a custom runner instead of Jest's default test runner
// runner: "jest-runner",
// The paths to modules that run some code to configure or set up the testing environment before each test
// setupFiles: [],
// A list of paths to modules that run some code to configure or set up the testing framework before each test
// setupFilesAfterEnv: [],
// The number of seconds after which a test is considered as slow and reported as such in the results.
// slowTestThreshold: 5,
// A list of paths to snapshot serializer modules Jest should use for snapshot testing
// snapshotSerializers: [],
// The test environment that will be used for testing
// testEnvironment: "jest-environment-node",
// Options that will be passed to the testEnvironment
// testEnvironmentOptions: {},
// Adds a location field to test results
// testLocationInResults: false,
// The glob patterns Jest uses to detect test files
testMatch: ["**/__tests__/**/*.[jt]s?(x)", "**/?(*.)+(spec|test).[tj]s?(x)"],
// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
// testPathIgnorePatterns: [
// "\\\\node_modules\\\\"
// ],
// The regexp pattern or array of patterns that Jest uses to detect test files
// testRegex: [],
// This option allows the use of a custom results processor
// testResultsProcessor: undefined,
// This option allows use of a custom test runner
// testRunner: "jest-circus/runner",
// A map from regular expressions to paths to transformers
// transform: undefined,
// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
// transformIgnorePatterns: [
// "\\\\node_modules\\\\",
// "\\.pnp\\.[^\\\\]+$"
// ],
// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
// unmockedModulePathPatterns: undefined,
// Indicates whether each individual test should be reported during the run
// verbose: undefined,
// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
// watchPathIgnorePatterns: [],
// Whether to use watchman for file crawling
// watchman: true,
};
export default config;

8697
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -12,12 +12,12 @@
"clean": "rimraf lib", "clean": "rimraf lib",
"compile": "tsc -b", "compile": "tsc -b",
"format": "prettier --write \"src/**/*.ts\" \"src/**/*.js\"", "format": "prettier --write \"src/**/*.ts\" \"src/**/*.js\"",
"lint": "exit 0", "lint": "eslint",
"postversion": "git push && git push --tags", "postversion": "git push && git push --tags",
"prepublishOnly": "npm test", "prepublishOnly": "npm test",
"pretest": "npm run compile", "pretest": "npm run compile",
"preversion": "", "preversion": "",
"test": "mocha --debug-brk", "test": "jest",
"version": "git add -A src", "version": "git add -A src",
"watch": "tsc -w -p ./src" "watch": "tsc -w -p ./src"
}, },
@@ -36,17 +36,19 @@
}, },
"homepage": "https://github.com/Blockception/Minecraft-bedrock-json-schemas#readme", "homepage": "https://github.com/Blockception/Minecraft-bedrock-json-schemas#readme",
"devDependencies": { "devDependencies": {
"@types/chai": "^4.3.11", "@eslint/js": "^9.14.0",
"@types/mocha": "^10.0.6", "@types/eslint__js": "^8.42.3",
"@types/jest": "^29.5.14",
"@types/node": "^20.10.1", "@types/node": "^20.10.1",
"chai": "^4.3.10",
"comment-json": "^4.2.3", "comment-json": "^4.2.3",
"json-loader": "^0.5.7", "eslint": "^9.14.0",
"mocha": "^10.2.0", "eslint-plugin-jest": "^28.9.0",
"ts-jest": "^29.2.5",
"ts-loader": "^9.5.1", "ts-loader": "^9.5.1",
"ts-mocha": "^10.0.0",
"ts-node": "^10.9.1", "ts-node": "^10.9.1",
"typescript": "^5.3.2" "typescript": "^5.3.2",
"typescript-eslint": "^8.13.0",
"vscode": "^1.1.37"
}, },
"dependencies": { "dependencies": {
"fast-glob": "^3.3.2", "fast-glob": "^3.3.2",

View File

@@ -10,6 +10,7 @@
}, },
"oneOf": [ "oneOf": [
{ {
"type": "string",
"$ref": "#/definitions/color" "$ref": "#/definitions/color"
}, },
{ {

View File

@@ -49,7 +49,6 @@
} }
}, },
"components": { "components": {
"additionalProperties": { "type": "object" },
"type": "object", "type": "object",
"description": "The components of this item.", "description": "The components of this item.",
"properties": { "properties": {

View File

@@ -1,4 +1,4 @@
import path = require("path"); import * as path from "path";
export namespace DummyFiles { export namespace DummyFiles {
export function TestFolder(): string { export function TestFolder(): string {

View File

@@ -1,16 +0,0 @@
{
"format_version": "1.16.200",
"minecraft:block": {
"description": {
"identifier": "namespace:block",
"properties": {}
},
"components": {},
"events": {
"minecraft:on_fall_on": {
"add_mob_effect": {},
"sequence": [{ "die": {} }]
}
}
}
}

View File

@@ -1,10 +1,8 @@
{ {
"format_version": "1.20.41", "format_version": "1.19.50",
"minecraft:npc_dialogue": { "minecraft:camera_preset": {
"identifier": "example:custom", "identifier": "example:custom",
"inherit_from": "minecraft:free", "inherit_from": "minecraft:free",
"player_effects": true,
"listener": "player",
"pos_x": 30, "pos_x": 30,
"pos_y": 90, "pos_y": 90,
"pos_z": -20, "pos_z": -20,

View File

@@ -11,11 +11,7 @@
"minecraft:equippable": { "minecraft:equippable": {
"slots": [ "slots": [
{ {
"accepted_items": [ "accepted_items": ["minecraft:tool"],
{
"tags": "query.any_tag('minecraft:is_tool')"
}
],
"item": { "item": {
"tags": "query.any_tag('minecraft:is_tool')" "tags": "query.any_tag('minecraft:is_tool')"
}, },

View File

@@ -1,9 +0,0 @@
{
"format_version": "1.13.0",
"minecraft:scatter_feature": {
"description": {
"identifier": "namespace:entity_name"
}
}
}

View File

@@ -1,19 +0,0 @@
{
"format_version": "1.13.0",
"minecraft:beards_and_shavers": {
"description": {
"identifier": "beards_and_shavers_features:beards_and_shavers_feature"
},
"places_feature": "beards_and_shavers_features:beards_and_shavers_feature_obsidian",
"y_delta": 0,
"bounding_box_min": [-4, 0, -4],
"bounding_box_max": [5, 12, 5],
"beard_raggedness_min": 0.25,
"beard_raggedness_max": 0.5,
"surface_block_type": "minecraft:grass",
"subsurface_block_type": "minecraft:dirt"
}
}

View File

@@ -1,17 +0,0 @@
{
"format_version": "1.13.0",
"minecraft:conditional_list": {
"description": {
"identifier": "conditional_list_features:conditional_list_feature"
},
"conditional_features": [
{
"places_feature": "conditional_list_features:conditional_list_feature_obsidian",
"condition": "query.noise(v.originx, v.originz) < 0"
}
],
"early_out_scheme": "placement_success"
}
}

View File

@@ -1,11 +0,0 @@
{
"format_version": "1.13.0",
"minecraft:hell_cave_carver_feature": {
"description": {
"identifier": "hell_cave_carver_features:hell_cave_carver_feature"
},
"fill_with": "minecraft:planks",
"width_modifier": 1
}
}

View File

@@ -1,21 +0,0 @@
{
"format_version": "1.13.0",
"minecraft:rect_layout": {
"description": {
"identifier": "rect_layout_features:rect_layout_feature"
},
"ratio_of_empty_space": 0.5,
"feature_areas":[
{
"feature": "rect_layout_features:rect_layout_feature_obsidian",
"area_dimensions": [1, 1]
},
{
"feature": "rect_layout_features:rect_layout_feature_planks",
"area_dimensions": [1, 1]
}
]
}
}

View File

@@ -1,11 +0,0 @@
{
"format_version": "1.13.0",
"minecraft:scan_surface": {
"description": {
"identifier": "scan_surface_features:scan_surface_feature"
},
"scan_surface_feature": "scan_surface_features:scan_surface_feature_obsidian"
}
}

View File

@@ -1,14 +1,14 @@
{ {
"format_version": "1.13.0", "format_version": "1.13.0",
"minecraft:single_block_feature": { "minecraft:single_block_feature": {
"description": { "description": {
"identifier": "scan_surface_features:scan_surface_feature_obsidian" "identifier": "scan_surface_features:scan_surface_feature_obsidian"
}, },
"places_block": "minecraft:obsidian", "places_block": "minecraft:obsidian",
"enforce_placement_rules": false, "enforce_placement_rules": false,
"enforce_survivability_rules": false "enforce_survivability_rules": false
} }
} }

View File

@@ -1,31 +0,0 @@
{
"format_version": "1.13.0",
"minecraft:scatter_feature": {
"description": {
"identifier": "scatter_and_singleblock_features:scatter_feature"
},
"places_feature": "scatter_and_singleblock_features:scatter_feature_obsidian",
"scatter_chance": {
"numerator": 2,
"denominator": 3
},
"iterations": "math.pow(2, 4)",
"coordinate_eval_order": "zxy",
"project_input_to_floor": true,
"z": {
"distribution": "fixed_grid",
"extent": [10, 15],
"step_size": 2,
"grid_offset": 3
},
"x": {
"distribution": "gaussian",
"extent": ["(v.worldx < 12) * 2", 16]
},
"y": 0
}
}

View File

@@ -15,7 +15,9 @@
"minecraft:damage": 2, "minecraft:damage": 2,
"minecraft:stacked_by_data": true, "minecraft:stacked_by_data": true,
"minecraft:should_despawn": true, "minecraft:should_despawn": true,
"minecraft:hover_text_color": "aqua", "minecraft:hover_text_color": {
},
"minecraft:use_animation": "brush", "minecraft:use_animation": "brush",
"minecraft:use_modifiers": { "minecraft:use_modifiers": {
"use_duration": 2 "use_duration": 2

View File

@@ -7,7 +7,7 @@
"type": "item", "type": "item",
"name": "minecraft:diamond_sword", "name": "minecraft:diamond_sword",
"weight": 1, "weight": 1,
"functions": [{ "function": "specific_enchants", "enchants": [{ "id": "power", "level": 3 }, "power"] }] "functions": [{ "function": "specific_enchants", "enchants": [{ "id": "power", "level": 3 }] }]
} }
] ]
} }

View File

@@ -1,18 +1,24 @@
{ {
"tiers": [ "tiers": [
{ {
"trades": [ "total_exp_required": 5,
"groups": [
{ {
"wants": [ "num_to_select": 2,
"trades": [
{ {
"item": "minecraft:wheat", "wants": [
"quantity": { {
"min": 18, "item": "minecraft:wheat",
"max": 22 "quantity": {
} "min": 18,
"max": 22
}
}
],
"gives": [{ "item": "minecraft:emerald" }]
} }
], ]
"gives": [{ "item": "minecraft:emerald" }]
} }
] ]
} }

View File

@@ -1,6 +1,6 @@
{ {
"Example": { "Example": {
"textures": "example", "textures": "test",
"sound": "obsidian" "sound": "amethyst_block"
} }
} }

View File

@@ -6,7 +6,7 @@
"header": { "header": {
"name": "Hell Cave Carver Features", "name": "Hell Cave Carver Features",
"uuid": "459909b9-fdb8-4eb3-9b8d-55d09545b89d", "uuid": "459909b9-fdb8-4eb3-9b8d-55d09545b89h",
"description": "Tests hell cave carver features", "description": "Tests hell cave carver features",
"version": [0, 0, 1], "version": [0, 0, 1],
"min_engine_version": [1, 17, 0] "min_engine_version": [1, 17, 0]

View File

@@ -6,7 +6,7 @@
"header": { "header": {
"name": "Hell Cave Carver Features", "name": "Hell Cave Carver Features",
"uuid": "459909b9-fdb8-4eb3-9b8d-55d09545b89d", "uuid": "459909b9-fdb8-4eb3-9b8d-55d09545b89h",
"description": "Tests hell cave carver features", "description": "Tests hell cave carver features",
"version": [1, 0, 0], "version": [1, 0, 0],
"min_engine_version": [1, 17, 0] "min_engine_version": [1, 17, 0]

View File

@@ -1,45 +1,23 @@
import { expect } from "chai";
import { Github } from "../github";
import { Schema } from "../schema-tester"; import { Schema } from "../schema-tester";
import { Files } from "../utillity"; import { Files } from "../utillity";
describe("test correct files", function () { describe("test correct files", function () {
const folder = Files.CorrectFilesFolder().replace(/\\/gi, "/"); const folder = Files.CorrectFilesFolder().replace(/\\/gi, "/");
const files = Files.GetFiles(folder); const files = Files.GetFiles(folder).filter((f) => f.endsWith(".json"));
const validator = Schema.GetValidator(); const validator = Schema.GetValidator();
expect(files.length, "No files were returned").to.greaterThan(0); expect(files.length).toBeGreaterThan(0);
files test.each(files)("File should have a schema & validate correctly: %s", async (file) => {
.filter((f) => f.endsWith(".json")) const result = validator.ValidateFile(file);
.forEach((file) => { const schemas = validator.ls.getMatchingSchemas(result.doc, result.jdoc);
const testfolder = file.replace(folder + "/", "");
it(`File should have a schema & validate correctly: ${testfolder}`, async function () { const succes = await result.promise;
const result = validator.ValidateFile(file);
const schemas = validator.ls.getMatchingSchemas(result.doc, result.jdoc);
result.promise.then( expect(succes).toHaveLength(0);
(succes) => { succes.forEach((item) => console.log(item.message));
expect(succes.length, "Expected no errors got: " + succes.length).to.equal(0);
succes.forEach((item) => console.log(item.message));
},
(fail) => {
Github.createError("Failed on validating", { file: file });
expect.fail("Failed to validate");
}
);
schemas.then(
(success) => {
expect(success.length, "Expected schemas to be returned").to.greaterThan(0);
},
(fail) => {
Github.createError("Failed on retrieving schemas", { file: file });
expect.fail("failed on retrieving schemas");
}
);
return Promise.all([result.promise, schemas]); const s = await schemas;
}); expect(s.length).toBeGreaterThan(0);
}); });
}); });

View File

@@ -1,44 +1,20 @@
import { expect } from "chai";
import { Github } from "../github";
import { Schema } from "../schema-tester"; import { Schema } from "../schema-tester";
import { Files } from "../utillity"; import { Files } from "../utillity";
describe("test incorrect files", function () { describe("test incorrect files", function () {
const folder = Files.InCorrectFilesFolder().replace(/\\/gi, "/"); const folder = Files.InCorrectFilesFolder().replace(/\\/gi, "/");
const files = Files.GetFiles(folder); const files = Files.GetFiles(folder).filter((f) => f.endsWith(".json"));
const validator = Schema.GetValidator(); const validator = Schema.GetValidator();
expect(files.length, "No files were returned").to.greaterThan(0); expect(files.length).toBeGreaterThan(0);
files test.each(files)("File should invalidate & have a schema: %s", async (file) => {
.filter((f) => f.endsWith(".json")) const result = validator.ValidateFile(file);
.forEach((file) => { const schemas = validator.ls.getMatchingSchemas(result.doc, result.jdoc);
const testfolder = file.replace(folder + "/", "");
it(`File should invalidate & have a schema: ${testfolder}`, async function () { const success = await result.promise;
const result = validator.ValidateFile(file); expect(success.length).toBeGreaterThan(0);
const schemas = validator.ls.getMatchingSchemas(result.doc, result.jdoc); const s = await schemas;
expect(s.length).toBeGreaterThan(0);
result.promise.then( });
(succes) => {
expect(succes.length, "Expected errors! but had none").to.greaterThan(0);
},
() => {
Github.createError("No errors where found", { file: file });
expect.fail("Failed to validate");
}
);
schemas.then(
(success) => {
expect(success.length, "Expected schemas to be returned").to.greaterThan(0);
},
() => {
Github.createError("Found no schema", { file: file });
expect.fail("failed on retrieving schemas");
}
);
return Promise.all([schemas, result]);
});
});
}); });

View File

@@ -9,7 +9,7 @@ export interface ErrorAnnotation {
export namespace Github { export namespace Github {
export function createError(message: string, error: ErrorAnnotation = {}): void { export function createError(message: string, error: ErrorAnnotation = {}): void {
const data = Object.entries(error) const data = Object.entries(error)
.filter(([key, value]) => value !== undefined) .filter(([, value]) => value !== undefined)
.map(([key, value]) => `${key}=${value}`) .map(([key, value]) => `${key}=${value}`)
.join(","); .join(",");

View File

@@ -1,7 +1,8 @@
import { getLanguageService, LanguageService, LanguageSettings, SchemaConfiguration, TextDocument, JSONDocument, Diagnostic, Thenable } from "vscode-json-languageservice"; import { existsSync, readFileSync } from "fs";
import * as path from "path";
import * as url from "url"; import * as url from "url";
import { Diagnostic, getLanguageService, JSONDocument, LanguageService, LanguageSettings, SchemaConfiguration, TextDocument, Thenable } from "vscode-json-languageservice";
import * as data from "../../vscode-settings.json"; import * as data from "../../vscode-settings.json";
import { readFileSync } from "fs";
import { Files } from "./utillity"; import { Files } from "./utillity";
export namespace Schema { export namespace Schema {
@@ -21,26 +22,41 @@ export namespace Schema {
} }
export function GetLanguageService(): LanguageService { export function GetLanguageService(): LanguageService {
return getLanguageService({ workspaceContext }); return getLanguageService({
workspaceContext,
schemaRequestService: getSchema,
});
}
export async function getSchema(uri: string): Promise<string> {
const rootfolder = Files.RootFolder();
const filepath = uri.replace("https://raw.githubusercontent.com/Blockception/Minecraft-bedrock-json-schemas/main", rootfolder);
if (!existsSync(filepath)) {
throw new Error("file doesn't exist: " + filepath);
}
return readFileSync(filepath).toString();
} }
export function GetLanguageSettings(): LanguageSettings { export function GetLanguageSettings(): LanguageSettings {
const schemas: SchemaConfiguration[] = []; const schemas: SchemaConfiguration[] = [];
const settings: LanguageSettings = { schemas: schemas }; const settings: LanguageSettings = {
schemas: schemas,
};
let rootfolder = Files.RootFolder(); let rootfolder = Files.RootFolder();
if (!rootfolder.endsWith("/")) rootfolder += "/"; if (!rootfolder.endsWith("/")) rootfolder += "/";
rootfolder = path.normalize(rootfolder);
data["json.schemas"].forEach((m) => { data["json.schemas"].forEach((m) => {
if (m) { if (m) {
const schema = m.url.replace("https://raw.githubusercontent.com/Blockception/Minecraft-bedrock-json-schemas/main/", rootfolder);
let matches = m.fileMatch; let matches = m.fileMatch;
if (typeof matches === "string") { if (typeof matches === "string") {
matches = [matches]; matches = [matches];
} }
schemas.push({ uri: schema, fileMatch: matches }); schemas.push({ uri: m.url, fileMatch: matches });
} }
}); });

View File

@@ -1,19 +1,17 @@
import { expect } from "chai";
import { DummyFiles } from "../../src/main";
import { Files } from "./utillity"; import { Files } from "./utillity";
describe("Files", function () { describe("Files", function () {
it("Root", function () { it("Root", function () {
const temp = Files.RootFolder(); const temp = Files.RootFolder();
expect(temp.endsWith("lib"), "ended with lib").to.be.false; expect(temp.endsWith("lib")).toBeFalsy();
expect(temp.endsWith("lib\\test"), "ended with lib\\test").to.be.false; expect(temp.endsWith("lib\\test")).toBeFalsy();
expect(temp.endsWith("lib/test"), "ended with lib/test").to.be.false; expect(temp.endsWith("lib/test")).toBeFalsy();
}); });
it("Test", function () { it("Test", function () {
const temp = Files.TestFolder(); const temp = Files.TestFolder();
expect(temp.endsWith("lib"), "ended with lib").to.be.false; expect(temp.endsWith("lib")).toBeFalsy();
}); });
}); });

View File

@@ -1,5 +1,5 @@
import FastGlob = require("fast-glob"); import * as FastGlob from "fast-glob";
import path = require("path"); import * as path from "path";
export namespace Files { export namespace Files {
export function TestFolder(): string { export function TestFolder(): string {

View File

@@ -1,35 +1,24 @@
import path = require("path");
import { Files } from "./utillity";
import * as fs from "fs";
import * as JSONC from "comment-json"; import * as JSONC from "comment-json";
import { expect } from "chai"; import * as fs from "fs";
import * as path from "path";
import { ErrorAnnotation, Github } from "./github"; import { ErrorAnnotation, Github } from "./github";
import { Files } from "./utillity";
describe("Validate", function () { describe("Validate", function () {
const folder = path.join(Files.TestFolder(), "..", "source"); const folder = path.join(Files.TestFolder(), "..", "source");
console.log(folder);
const files = Files.GetFiles(folder); const files = Files.GetFiles(folder);
expect(files.length).toBeGreaterThan(0);
files.forEach((filepath) => { test.each(files)("Validating schema parts: %s", (filepath) => {
const filename = filepath.slice(folder.length); const data = fs.readFileSync(filepath, "utf8");
const object = JSONC.parse(data) as JsonSchema;
expect(object).toBeDefined();
if (!object) {
return;
}
it(`Validating schema parts: ${filename}`, function () { const explorer = new Explorer(data, filepath);
let object: JsonSchema | undefined = undefined; explorer.explore_refs(object, path.dirname(filepath));
let data: string;
data = fs.readFileSync(filepath, "utf8");
object = <JsonSchema>JSONC.parse(data);
expect(object).to.not.be.undefined;
expect(object).to.not.be.null;
if (!object) {
this.skip();
return;
}
const explorer = new Explorer(data, filepath);
explorer.explore_refs(object, path.dirname(filepath));
});
}); });
}); });
@@ -60,7 +49,7 @@ class Explorer {
anno.file = this.filepath; anno.file = this.filepath;
Github.createError(`Ref not found: ${ref}`, anno); Github.createError(`Ref not found: ${ref}`, anno);
expect.fail(`ref ${ref} does not exists`); throw new Error(`ref ${ref} does not exists`);
} }
} }
} }

View File

@@ -248,7 +248,7 @@
}, },
{ {
"fileMatch": ["cameras/presets/*.{json,jsonc,json5}"], "fileMatch": ["cameras/presets/*.{json,jsonc,json5}"],
"url": "https://raw.githubusercontent.com/Blockception/Minecraft-bedrock-json-schemas/main/behavior/cameras/presets/camera.json" "url": "https://raw.githubusercontent.com/Blockception/Minecraft-bedrock-json-schemas/main/behavior/cameras/presets/cameras.json"
}, },
{ {
"fileMatch": [ "fileMatch": [