From 4b91478dd762881f81300bbcbb2edc6fcabc536b Mon Sep 17 00:00:00 2001
From: jsteuer <jan.steuer.htw@gmail.com>
Date: Tue, 17 Dec 2019 09:05:14 +0100
Subject: [PATCH] add unit tests

---
 src/Helpers.ts |  125 ++++++++++++++++++++++++++++-------------
 1 files changed, 86 insertions(+), 39 deletions(-)

diff --git a/src/Helpers.ts b/src/Helpers.ts
index 3ec398c..c1b69ec 100644
--- a/src/Helpers.ts
+++ b/src/Helpers.ts
@@ -1,18 +1,17 @@
 /// <reference path="../mathcoach-api.d.ts"/>
 
+
 /**
  * Hilfsfunktionen für Werkzeug-Entwickler. Diese werden nicht durch die `ide-lib.js` 
  * ausgeliefert!
  */
 export namespace Helpers {
+
     /**
      * Bildet die MathCoach API nach, sodass diese auch Offline (ohne IDE) 
-     * verfügbar ist.
-     * 
-     * Das Dateisystem wird durch den LocalStorage des Browsers implementiert.
-     * Einige Features der IDE (beispielsweise der Navigator) sind nicht verfügbar 
-     * und führen keine Aktionen durch. Alle Aktionen werden in der Browser-Console
-     * geloggt.
+     * verfügbar ist. Aktuell wird eine Implementierung auf Basis des LocalStorage
+     * verwendet. Funktionen wie der Navigator sind nicht verfügbar. Alle API Aufrufe
+     * werden in der Browser-Console geloggt.
      * 
      * **Hinweis**: Wenn die echte MathCoach-API der IDE verfügbar ist, hat der Aufruf 
      * dieser Funktion keinen Seiteneffekt.
@@ -21,7 +20,7 @@
      * 
      *      import { Helpers } from "@mathcoach/ide-api";
      *      Helpers.enableOfflineUsageIfNecessary();
-     * 
+     *      MC.isReady() // use the api
      * 
      * @param contextFileExtension Datei-Erweiterung der Kontext-Datei (Das Werkzeug soll 
      * jedoch unabhängig von der Endung arbeiten können)
@@ -29,11 +28,34 @@
      * wurde, andernfalls `false`
      */
     export function enableOfflineUsageIfNecessary(contextFileExtension: string = "dummy.json"): boolean {
+        if (typeof MC === "undefined") {
+            console.warn("you are offline - offline api is used");
+            const WINDOW = (typeof window === "undefined") ? {} as any : window;
+            WINDOW.MC = createStorageBasedApi(contextFileExtension);
+            return true;
+        } else {
+            return false;
+        }
+    }
 
+    /**
+     * Implementierung der MathCoach IDE API zu Testzwecken.
+     * 
+     * Das Dateisystem wird durch den LocalStorage des Browsers (oder InMemory) implementiert.
+     * Einige Features der IDE (beispielsweise der Navigator) sind nicht verfügbar 
+     * und führen keine Aktionen durch. Alle Aktionen werden in der Browser-Console
+     * geloggt.
+     * 
+     * Anwendungsbeispiel
+     * 
+     *      const MC = new LocalStorageBasedApi();
+     *      const contextFile = await MC.ide.getContextFile() // use the api
+     */
+    export function createStorageBasedApi(contextFileExtension: string = "dummy.json"): MathCoach.Api {
         const fileIdentifier = (file: MathCoach.File) => `mock-file://${file.owner}@${file.part}/${file.path}`;
         const traceMethod = (method: string, args?: any[]) => console.log(["[MC MOCK API]", " ", method, "(", (args ? args : [""]).join(","), ")"].join(""));
-
-        class MockAPI implements MathCoach.Api {
+        let storage: Storage = (typeof localStorage === "undefined") ? new InMemoryStorage() : localStorage;
+        class LocalStorageBasedApi implements MathCoach.Api {
 
             public ide: MathCoach.IdeApi = {
                 async getContextFile(): Promise<MathCoach.File> {
@@ -51,11 +73,11 @@
                 fs: {
                     async readFile(file: MathCoach.File) {
                         traceMethod("MC.ide.fs.readFile", [JSON.stringify(file)]);
-                        return localStorage.getItem(fileIdentifier(file)) || "";
+                        return storage.getItem(fileIdentifier(file)) || "";
                     },
                     async writeFile(file: MathCoach.File, text: string) {
                         traceMethod("MC.ide.fs.writeFile", [JSON.stringify(file), JSON.stringify(`...${text.length} chars...`)]);
-                        return localStorage.setItem(fileIdentifier(file), text);
+                        return storage.setItem(fileIdentifier(file), text);
                     }
                 },
                 navigator: {
@@ -68,20 +90,27 @@
                 }
             };
             public async isReady(): Promise<boolean> {
-                traceMethod("MC.isReady()");
+                traceMethod("MC.isReady");
                 return true;
             }
         }
-        if (typeof MC === "undefined") {
-            console.warn("you are offline - offline api is used");
-            (window as any).MC = new MockAPI(); // fake the MathCoach-API
-            return true;
-        } else {
-            return false;
-        }
+        return new LocalStorageBasedApi();
     }
 
 
+    /**
+     * Type Guard, der prüft, ob es sich um eine gültige `MathCoach.File`-Referenz handelt.
+     * 
+     * @param maybeFile Ein beliebiges Objekt, das geprüft werden soll
+     */
+    export function isFile(maybeFile: any): maybeFile is MathCoach.File {
+        return (maybeFile ? true : false)
+            && (maybeFile.owner ? true : false) && (typeof maybeFile.owner === "string")
+            && (maybeFile.part ? true : false) && (typeof maybeFile.part === "string")
+            && (maybeFile.part === "vfs" || maybeFile.part === "www")
+            && (maybeFile.path ? true : false) && (typeof maybeFile.path === "string")
+            && (maybeFile.path.indexOf("/") === 0)
+    }
 
 
     /**
@@ -101,29 +130,47 @@
      *      const exerciseFile: MathCoach.File = Helpers.contextFileToExerciseFile(contextFile);
      */
     export function contextFileToExerciseFile(contextFile: MathCoach.File): MathCoach.File {
-        if (contextFile) {
-            if (!contextFile.owner || !(typeof contextFile.owner === "string") || !(contextFile.owner.trim() === "")) {
-                throw new Error("Context file has no valid 'owner' property.");
-            }
-            if (!contextFile.part || !(typeof contextFile.part === "string")) {
-                if (contextFile.part !== "vfs" && contextFile.part !== "www") {
-                    throw new Error("Context file has no valid 'part' property. Allowed values are 'vfs' and 'www'.");
-                }
-            }
-            if (!contextFile.path || !(typeof contextFile.path === "string") || !(contextFile.owner.trim().startsWith("/"))) {
-                throw new Error("Context file has no valid 'path' property.");
-            }
+        if (isFile(contextFile)) {
+            let exerciseFile: MathCoach.File = {
+                part: contextFile.part,
+                owner: contextFile.owner,
+                path: contextFile.path.split(".")[0] + ".groovy"
+            };
+            return exerciseFile;
         } else {
-            throw new Error("No context file object given.")
+            throw new Error("no valid file reference given, expected object like {owner:'demo', part:'vfs'|'www', path: '/...'}")
         }
-        let file: MathCoach.File = {
-            part: contextFile.part,
-            owner: contextFile.owner,
-            path: contextFile.path.split(".")[0] + ".groovy"
-        };
-        return file;
     }
 
+    /**
+     * Storage auf Basis einer Map. Kann z.B. bei Unit-Tests verwendet
+     * werden, beid denen der LocalStorage nicht verfügbar ist.
+     */
+    class InMemoryStorage implements Storage {
 
+        private readonly items: Map<string, string> = new Map();
 
-}
\ No newline at end of file
+        get length(): number {
+            return this.items.size;
+        }
+        clear(): void {
+            this.items.clear();
+        }
+        getItem(key: string): string | null {
+            const value = this.items.get(key);
+            return value ? value : null;
+        }
+        key(index: number): string | null {
+            throw new Error("FakeStorage: key function is not implemented now");
+        }
+        removeItem(key: string): void {
+            this.items.delete(key);
+        }
+        setItem(key: string, value: string): void {
+            this.items.set(key, value);
+        }
+
+    }
+
+}
+

--
Gitblit v1.10.0-SNAPSHOT