import {expect, test} from "@jest/globals"; import {Graph} from "./Graph-demo.js"; test("Graph: constructor:", ()=>{ const g = new Graph(); g.addEdge(1, 2); g.addEdge(1, 3); g.addEdge(2, 3); g.addEdge(2, 4); const txt = g.toString(); const expected = `1 → [2, 3] 2 → [1, 3, 4] 3 → [1, 2] 4 → [2]`; expect(txt).toBe(expected); const vertices = [1, 2, 3, 4]; const action = (v) => expect(vertices).toContain(v); g.forEachVertices(action); }); test("Graph: iterate all edges:", ()=>{ const g = new Graph(); g.addEdge(1, 2); g.addEdge(3, 1); g.addEdge(2, 3); g.addEdge(2, 4); const edges = [ "1-2", "1-3", "2-3", "2-4" ]; const action = (a, b) => { const [s,e] = a < b ? [a,b] : [b,a]; const edge = `${s}-${e}`; expect(edges).toContain(edge) }; g.forEachEdges(action); }); test("Graph: Don't add floating point number to vertex set:", ()=>{ const g = new Graph(); try { g.addVertex(1.2); }catch (e) { expect(e.message).toBe('Argument 1.2 is not a valid vertex'); expect(e.constructor).toBe(TypeError); } }); test("Graph: Don't add string to vertex set:", ()=>{ const g = new Graph(); try { g.addVertex("add"); }catch (e) { expect(e.message).toBe('Argument add is not a valid vertex'); expect(e.constructor).toBe(TypeError); } }); test("Graph: iterates over vertices:", ()=>{ const g = new Graph(); g.addEdge(1, 2); g.addEdge(1, 3); g.addEdge(2, 3); g.addEdge(2, 4); const vertices = []; for(const v of g.vertices()) { vertices.push(v); } vertices.sort(); const expected = [1, 2, 3, 4]; expect(vertices).toEqual(expected); }); test("Graph: iterates over neighbor of a vertex:", ()=>{ const g = new Graph(); g.addEdge(1, 2); g.addEdge(1, 3); g.addEdge(2, 3); g.addEdge(2, 4); g.addEdge(4, 1); const vertices = []; for(const v of g.adjacentOf(1)) { vertices.push(v); } vertices.sort(); const expected = [2, 3, 4]; expect(vertices).toEqual(expected); }); test("Graph: merge existing attributes:", ()=>{ const g = new Graph(); g.addVertex(1); const undef = g.getAttribute(1); expect(undef).toBe(undefined); const firstA = {'a':1, 'b':2}; g.mergeAttribute(1, firstA); const getFirstA = g.getAttribute(1); expect(getFirstA.get('a')).toBe( firstA['a'] ); expect(getFirstA.get('b')).toBe( firstA['b'] ); const secondA = {'b': 3, 'c': 5}; g.mergeAttribute(1,secondA); const getSecondA = g.getAttribute(1); expect(getSecondA.get('a')).toBe(firstA['a']); // same thing expect(getSecondA.get('b')).toBe(secondA['b']); expect(getSecondA.get('c')).toBe(secondA['c']); }); test("Graph: don't merge attributes if given vertex not in graph:", ()=>{ const g = new Graph(); g.addVertex(1); try { g.mergeAttribute(2, {'a':1, 'b':2}); }catch (e) { expect(e.message).toBe('Graph does not include vertex 2'); expect(e.constructor).toBe(Error); } }); test("Graph: don't merge bad attribute:", ()=>{ const g = new Graph(); g.addVertex(1); try { g.mergeAttribute(1, null); }catch (e) { expect(e.message).toBe('Bad attribute'); expect(e.constructor).toBe(Error); } });