repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
foxhatleo/dragonglass-level-editor
redux/action/ActionType.ts
enum ActionType { UPDATE_SIGN_IN_STATUS, SET_FILE_ID, CTRL_CLICK, SHIFT_CLICK, SINGLE_CLICK, PARSE_DATA, SET_NAME, CLEAR_SELECTION, PAINT, ERASE, ADD_QUEUE, REMOVE_QUEUE, MARK_READY, MARK_SAVED, SET_COLORS, FAIL, SET_LEVEL_TIME, SET_CANVAS_BASE_TIME, SET_CANVAS_PER_COLOR_TIME, } export default ActionType;
foxhatleo/dragonglass-level-editor
components/ColorStrip.tsx
import React from "react"; const ColorStrip: React.FunctionComponent<{ colors: [number, number, number][]; }> = (p) => ( <ul> {p.colors.map((c, i) => ( <li key={i}> <span style={{background: `rgb(${c[0]},${c[1]},${c[2]})`}}/> </li> ))} <style jsx>{` ul, li, span { margin: 0; padding: 0; display: inline-block; } span { width: 18px; height: 18px; border: 1px solid white; } li:not(:first-child) { margin-left: .2rem; } `}</style> </ul> ); export default ColorStrip;
foxhatleo/dragonglass-level-editor
config/GlobalTimer.ts
<filename>config/GlobalTimer.ts import {TimerData} from "../redux/store/State"; export const GLOBAL_TIMER: Required<TimerData> = { levelTime: 120, canvasBaseTime: 5, canvasPerColorTime: 2 };
foxhatleo/dragonglass-level-editor
redux/reducer/RootReducer.ts
import {Reducer} from "redux"; import State, {defaultState} from "../store/State"; import ActionType from "../action/ActionType"; import Action from "../action/Action"; import * as V1Representation from "../util/V1Representation"; import * as Config from "../../config/Google"; function lastClicked(s: number[][]): [[number, number], number] { let biggest = 0, qI = 0, cI = 0; for (let i = 0; i < s.length; i++) { const q = s[i]; for (let j = 0; j < q.length; j++) { if (q[j] > biggest) { biggest = q[j]; qI = i; cI = j; } } } return [[qI, cI], biggest]; } const RootReducer: Reducer<State, Action> = (s = defaultState, a) => { switch (a.type) { case ActionType.UPDATE_SIGN_IN_STATUS: { if (!a.value) return {...s, loggedIn: false}; const grantedScopes = gapi.auth2.getAuthInstance().currentUser.get().getGrantedScopes().split(" "); let missingScope = false; for (let s of Config.SCOPES) { if (grantedScopes.indexOf(s) < 0) { missingScope = true; break; } } return {...s, loggedIn: !missingScope}; } case ActionType.SET_FILE_ID: { return {...s, fileId: a.value}; } case ActionType.SINGLE_CLICK: { const newSelected = s.selected.map(i => (i.map(_ => 0))); newSelected[a.value[0]][a.value[1]] = 1; return {...s, selected: newSelected}; } case ActionType.CTRL_CLICK: { const newSelected = s.selected.map(i => (i.map(o => o))); if (newSelected[a.value[0]][a.value[1]] > 0) newSelected[a.value[0]][a.value[1]] = 0; else newSelected[a.value[0]][a.value[1]] = lastClicked(newSelected)[1] + 1; return {...s, selected: newSelected}; } case ActionType.SHIFT_CLICK: { const newSelected = s.selected.map(i => (i.map(o => o))); const lc = lastClicked(newSelected); if (lc[1] == 0) { newSelected[a.value[0]][a.value[1]] = 1; } else { const qIdLow = Math.min(a.value[0], lc[0][0]); const qIdHigh = Math.max(a.value[0], lc[0][0]); const cIdLow = Math.min(a.value[1], lc[0][1]); const cIdHigh = Math.max(a.value[1], lc[0][1]); for (let i = qIdLow; i <= qIdHigh; i++) { const q = newSelected[i]; for (let j = cIdLow; j <= cIdHigh; j++) { if (i == a.value[0] && j == a.value[1]) { q[j] = lc[1] + 2; } if (j >= q.length || q[j] > 0) { continue; } q[j] = lc[1] + 1; } } } return {...s, selected: newSelected}; } case ActionType.SET_NAME: { return {...s, name: a.value}; } case ActionType.PARSE_DATA: { if (s.lastStored != V1Representation.stringify(s.level)) { console.warn("Refused to parse data. Last stored does not match level."); return s; } let l; if (a.value.trim() == "") { l = JSON.parse(JSON.stringify(defaultState.level)); } else { l = V1Representation.parse(a.value); } const sel = []; for (let q = 0; q < l.queues.length; q++) { const qsel = []; const qc = l.queues[q].length; for (let c = 0; c < qc + 1; c++) { qsel.push(q < s.level.queues.length ? (c < s.level.queues[q].length + 1 ? s.selected[q][c] : 0) : 0); } sel.push(qsel); } let e = {selected: sel, ready: true, lastStored: V1Representation.stringify(l)}; return {...s, level: l, ...e}; } case ActionType.CLEAR_SELECTION: { const newSelected = s.selected.map(i => (i.map(_ => 0))); return {...s, selected: newSelected}; } case ActionType.PAINT: { const queues = s.level.queues.map(a => a.map(b => b.map(c => c))); const selected = s.selected.map(a => a.map(b => b)); for (let qi = 0; qi < s.selected.length; qi++) { const q = s.selected[qi]; for (let ci = 0; ci < q.length; ci++) { if (q[ci] < 1) continue; if (ci == s.level.queues[qi].length) { queues[qi].push([a.value]); selected[qi].push(0); } else if (!queues[qi][ci].includes(a.value)) { queues[qi][ci].push(a.value); queues[qi][ci].sort(); } } } return {...s, level: {...s.level, queues}, selected}; } case ActionType.ERASE: { const queues = s.level.queues.map(a => a.map(b => b.map(c => c))); const selected = s.selected.map(a => a.map(b => b)); for (let qi = 0; qi < selected.length; qi++) { const q = selected[qi]; for (let ci = 0; ci < q.length - 1; ci++) { if (q[ci] < 1) continue; const ind = queues[qi][ci].indexOf(a.value); if (ind < 0) continue; queues[qi][ci].splice(ind, 1); if (queues[qi][ci].length == 0) { queues[qi].splice(ci, 1); q.splice(ci, 1); ci--; } } } return {...s, level: {...s.level, queues}, selected}; } case ActionType.ADD_QUEUE: { return { ...s, level: {...s.level, queues: [...s.level.queues, []]}, selected: [...s.selected, [0]] }; } case ActionType.REMOVE_QUEUE: { const queues = s.level.queues; queues.splice(queues.length - 1, 1); const selected = s.selected; selected.splice(selected.length - 1, 1); return {...s, level: {...s.level, queues}, selected}; } case ActionType.MARK_READY: { return {...s, ready: true}; } case ActionType.MARK_SAVED: { return {...s, lastStored: a.value} } case ActionType.SET_COLORS: { const st = {...s, level: {...s.level, colors: a.value}}; if (st.level.colors.length >= s.level.colors.length) return st; const newSelected = st.selected.map(i => (i.map(_ => 1))); let temp_st = {...st, selected: newSelected}; for (let i = s.level.colors.length - 1; i > st.level.colors.length - 1; i--) { temp_st = RootReducer(temp_st, {type: ActionType.ERASE, value: i}); } return RootReducer(temp_st, {type: ActionType.CLEAR_SELECTION}); } case ActionType.FAIL: { let body = null; let stack = null; let details = null; if (typeof a.value[1] !== "undefined") { if (a.value[1].body) { body = a.value[1].body.toString(); try { body = JSON.parse(body); } catch (e) { } } if (a.value[1].stack) { stack = a.value[1].stack.toString(); } if (a.value[1].details) { stack = a.value[1].details.toString(); } } return { ...s, globalError: JSON.stringify({ reporter: a.value[0], state: s, error: { toString: typeof a.value[1] !== "undefined" ? a.value[1].toString() : null, stack, body, details } }) }; } case ActionType.SET_LEVEL_TIME: { const tObj = s.level["timer"] || {}; if (a.value >= 0) { tObj.levelTime = a.value; } else { delete tObj["levelTime"]; } return {...s, level: {...s.level, timer: tObj}}; } case ActionType.SET_CANVAS_BASE_TIME: { const tObj = s.level["timer"] || {}; if (a.value >= 0) { tObj.canvasBaseTime = a.value; } else { delete tObj["canvasBaseTime"]; } return {...s, level: {...s.level, timer: tObj}}; } case ActionType.SET_CANVAS_PER_COLOR_TIME: { const tObj = s.level["timer"] || {}; if (a.value >= 0) { tObj.canvasPerColorTime = a.value; } else { delete tObj["canvasPerColorTime"]; } return {...s, level: {...s.level, timer: tObj}}; } } return s; }; export default RootReducer;
foxhatleo/dragonglass-level-editor
pages/[rid]/edit.tsx
<filename>pages/[rid]/edit.tsx<gh_stars>0 import {useRouter} from "next/router"; import App from "../../components/App"; import {Provider} from "react-redux"; import store from "../../redux/store/Store"; import React from "react"; const Edit = () => { const router = useRouter(); const {rid} = router.query; return ( <Provider store={store}> <App createMode={false} id={rid as string}/> </Provider> ); } export default Edit;
foxhatleo/dragonglass-level-editor
redux/util/V1Representation.ts
import {LevelData} from "../store/State"; import prettyStringify from "json-stringify-pretty-compact"; export function hexToRgb(hex: string): [number, number, number] { let result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); return result ? [ parseInt(result[1], 16), parseInt(result[2], 16), parseInt(result[3], 16), ] : [255, 255, 255]; } export function parse(a: string): LevelData | null { const o = JSON.parse(a.replaceAll(/;.*\n/g, "").trim()); if (o.version != 1) return null; const cl = o["colors"]; if (cl.length > 0 && typeof cl[0] === "string") { for (let i = 0, j = cl.length; i < j; i++) { cl[i] = hexToRgb(cl[i]); } } return {colors: cl, queues: o["queues"], timer: o["timer"]}; } const pretext = "; ==============================================================================\n" + "; This file is to be opened by Panic Painter Level Editor.\n" + ";\n" + "; To install, go to:\n" + "; https://workspace.google.com/marketplace/app/appname/656662885342\n" + "; Access limited to individuals affiliated with Cornell University.\n" + "; ==============================================================================\n" + "\n\n\n"; export function stringify(o: LevelData, forExport: boolean = false): string { if (!forExport) { return pretext + JSON.stringify({...o, version: 1}); } else { return prettyStringify({...o, version: 1}); } }
foxhatleo/dragonglass-level-editor
redux/action/Dispatcher.ts
import ActionType from "./ActionType"; import Action, {CellInd} from "./Action"; const marker = <T>(type: ActionType): (() => Action) => (() => ({type} as unknown as Action)); const updater = <T>(type: ActionType): ((value: T) => Action) => ((value: T) => ({type, value} as unknown as Action)); export const clearSelection = marker(ActionType.CLEAR_SELECTION); export const addQueue = marker(ActionType.ADD_QUEUE); export const removeQueue = marker(ActionType.REMOVE_QUEUE); export const markReady = marker(ActionType.MARK_READY); export const markSaved = updater<string>(ActionType.MARK_SAVED); export const setColors = updater<[number, number, number][]>(ActionType.SET_COLORS); export const updateSignInStatus = updater<boolean>(ActionType.UPDATE_SIGN_IN_STATUS); export const paint = updater<number>(ActionType.PAINT); export const erase = updater<number>(ActionType.ERASE); export const setLevelTime = updater<number>(ActionType.SET_LEVEL_TIME); export const setCanvasPerColorTime = updater<number>(ActionType.SET_CANVAS_PER_COLOR_TIME); export const setCanvasBaseTime = updater<number>(ActionType.SET_CANVAS_BASE_TIME); export const setFileId = updater<string>(ActionType.SET_FILE_ID); export const setName = updater<string>(ActionType.SET_NAME); export const ctrlClick = updater<CellInd>(ActionType.CTRL_CLICK); export const shiftClick = updater<CellInd>(ActionType.SHIFT_CLICK); export const singleClick = updater<CellInd>(ActionType.SINGLE_CLICK); export const parseData = updater<string>(ActionType.PARSE_DATA); export const fail = updater<[string, any]>(ActionType.FAIL);
foxhatleo/dragonglass-level-editor
pages/index.tsx
<reponame>foxhatleo/dragonglass-level-editor<gh_stars>0 import React from "react"; import {NextPage} from "next"; import {Modal} from "react-bootstrap"; import {isDebug} from "../config/Debug"; const Home: NextPage = () => { if (isDebug()) { location.href = "/123/edit"; return <>Transferring...</>; } return <> <Modal backdrop="static" show={true} onHide={() => { }}> <Modal.Header><Modal.Title>Invalid request</Modal.Title></Modal.Header> <Modal.Body> Please open a level file or create a new one from Google Drive. </Modal.Body> </Modal> </>; }; Home.getInitialProps = async (appContext) => { const fail = () => { appContext.res?.writeHead(400); appContext.res?.write("This is not a valid state object."); appContext.res?.end(); } if (typeof window === "undefined" && appContext.res && appContext.res.writeHead && appContext.query.state) { try { const googleState = JSON.parse(appContext.query.state as string); if (googleState["action"] == "create" && typeof googleState["folderId"] === "string") { appContext.res.writeHead(302, {Location: `/${googleState["folderId"]}/create`}); appContext.res.end(); } else if (googleState["action"] == "open" && typeof googleState["ids"][0] === "string") { appContext.res.writeHead(302, {Location: `/${googleState["ids"][0]}/edit`}); appContext.res.end(); } } catch (e) { fail(); } } return {}; } export default Home;
foxhatleo/dragonglass-level-editor
pages/_app.tsx
<reponame>foxhatleo/dragonglass-level-editor import React, {FunctionComponent} from "react"; import {AppProps} from "next/app"; import "../styles/bootstrap.min.css"; const MyApp: FunctionComponent<AppProps> = ({Component, pageProps}) => ( <> <script type="text/javascript" src="https://apis.google.com/js/platform.js"/> <style jsx global>{` html, body { padding: 0; margin: 0; font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen, Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif; } a { color: inherit; text-decoration: none; } * { box-sizing: border-box; } a, button, div, form, span { cursor: default !important; user-select: none; } a:not(.btn) { cursor: pointer !important; } a:not(.btn):hover, a:not(.btn):active { color: var(--primary); } p { margin-top: 1rem; } .navbar { padding-top: 0; padding-bottom: 0; } .dropdown-menu { padding: 0; border-radius: 0; } .dropdown-divider { margin: 0; } .dropdown-item { padding: .25rem 1.25em; } .modal-content { border-radius: 0; } .modal-header { padding: .25rem .5rem; background-color: var(--primary); border-radius: 0; } .modal-body { padding: .5rem; } .modal-footer { padding: .25rem; } .btn { padding: .1rem 1.25rem; border-radius: 0; } .form-control { padding: .125rem .25rem; border-radius: 0; background: black; color: white; } .form-control:focus { background: #191919; color: white; } .modal-title { font-size: 1rem; font-weight: 400; } `}</style> <Component {...pageProps} /> </> ); export default MyApp;
foxhatleo/dragonglass-level-editor
redux/action/Action.ts
<gh_stars>0 import ActionType from "./ActionType"; import {Action as ReduxAction} from "redux"; interface PureAction<T extends ActionType> extends ReduxAction<T> { } interface SetterAction<T extends ActionType, S> extends PureAction<T> { value: S; } export type CellInd = [number, number]; declare type Action = PureAction<ActionType.CLEAR_SELECTION> | PureAction<ActionType.MARK_READY> | PureAction<ActionType.ADD_QUEUE> | PureAction<ActionType.REMOVE_QUEUE> | SetterAction<ActionType.MARK_SAVED, string> | SetterAction<ActionType.SET_COLORS, [number, number, number][]> | SetterAction<ActionType.FAIL, [string, any]> | SetterAction<ActionType.PAINT, number> | SetterAction<ActionType.ERASE, number> | SetterAction<ActionType.UPDATE_SIGN_IN_STATUS, boolean> | SetterAction<ActionType.SET_NAME, string> | SetterAction<ActionType.PARSE_DATA, string> | SetterAction<ActionType.CTRL_CLICK, CellInd> | SetterAction<ActionType.SHIFT_CLICK, CellInd> | SetterAction<ActionType.SINGLE_CLICK, CellInd> | SetterAction<ActionType.SET_FILE_ID, string> | SetterAction<ActionType.SET_LEVEL_TIME, number> | SetterAction<ActionType.SET_CANVAS_BASE_TIME, number> | SetterAction<ActionType.SET_CANVAS_PER_COLOR_TIME, number>; export default Action;
foxhatleo/dragonglass-level-editor
components/Navbar.tsx
import React from "react"; import {Button, Navbar as RBNavbar, NavbarBrand} from "react-bootstrap"; import {connect, ConnectedProps} from "react-redux"; import State from "../redux/store/State"; import {bindActionCreators} from "redux"; import * as Dispatcher from "../redux/action/Dispatcher"; import ColorStrip from "./ColorStrip"; import * as V1Representation from "../redux/util/V1Representation"; const connector = connect( (s: State) => ({ name: s.name, colorLength: s.level.colors.length, colors: s.level.colors, selected: s.selected, queues: s.level.queues, level: s.level, saved: s.lastStored, anySelected: s.selected.reduce((p, q) => (p || q.reduce((p, c) => p || (c > 0), false)), false) }), (d) => bindActionCreators(Dispatcher, d), ); export type NavbarProps = { onColor: () => void; onSimulate: () => void; onTimer: () => void; }; const Navbar: React.FunctionComponent<ConnectedProps<typeof connector> & NavbarProps> = (p) => { const anySelected = p.anySelected; const exportJSON = () => { const blob = new Blob([V1Representation.stringify(p.level, true)], {type: "application/json"}); const a = p.name.split(".").concat(); if (a.length >= 2) a.splice(a.length - 1, 1); const filename = a.join(".") + ".json"; if (typeof window.navigator.msSaveOrOpenBlob != "undefined") { window.navigator.msSaveBlob(blob, filename); } else { const elem = window.document.createElement('a'); elem.href = window.URL.createObjectURL(blob); elem.download = filename; document.body.appendChild(elem); elem.click(); document.body.removeChild(elem); } }; return ( <RBNavbar variant={"dark"} bg={"dark"} fixed={"top"} className={"justify-content-between"}> <div> <NavbarBrand>{p.name}</NavbarBrand> {!anySelected ? <> <Button onClick={p.onColor}>Edit colors ({p.colorLength})</Button> <Button onClick={p.onSimulate}>Simulate</Button> <Button onClick={p.onTimer}>Timer</Button> <Button onClick={exportJSON}>Export</Button> </> : <> {p.colors.map((c, i) => { const allSelected = p.selected.reduce((pr, q, qi) => (pr && q.reduce((pr, c, ci) => { return pr && (c ? (ci == p.queues[qi].length ? false : p.queues[qi][ci].includes(i)) : true); }, true)), true); const handler = () => { if (allSelected) p.erase(i); else p.paint(i); }; return <Button key={i} onClick={handler} variant={allSelected ? "primary" : "secondary"}> <ColorStrip colors={[c]}/> </Button>; })} </>} </div> <div> {p.saved != V1Representation.stringify(p.level) ? "Saving..." : "Saved."} </div> <style jsx>{` div :global(.btn) { padding: .1rem .3rem; margin-left: .5rem; } `}</style> </RBNavbar> ); }; export default connector(Navbar);
foxhatleo/dragonglass-level-editor
redux/store/State.ts
<filename>redux/store/State.ts import * as V1Representation from "../util/V1Representation"; import {hexToRgb} from "../util/V1Representation"; export type TimerData = { levelTime?: number; canvasBaseTime?: number; canvasPerColorTime?: number; }; export type LevelData = { colors: [number, number, number][]; queues: number[][][]; timer?: TimerData; }; declare type RootState = { loggedIn: boolean; fileId: string; level: LevelData; name: string; globalError: string; selected: number[][]; lastStored: string; ready: boolean; }; export default RootState; const defaultLevel: LevelData = { colors: [ hexToRgb("#F44E3B"), hexToRgb("#FB9E00"), hexToRgb("#68BC00"), hexToRgb("#73D8FF"), ], queues: [[], [], [], [], []], }; const defaultState: RootState = { loggedIn: false, fileId: "", name: "", globalError: "", lastStored: V1Representation.stringify(defaultLevel), ready: false, selected: [[0], [0], [0], [0], [0]], level: defaultLevel, }; export {defaultState};
foxhatleo/dragonglass-level-editor
components/TimerWindow.tsx
<gh_stars>0 import React, {ChangeEvent, useEffect, useState} from "react"; import {Button, FormControl, Modal} from "react-bootstrap"; import {connect, ConnectedProps} from "react-redux"; import State, {TimerData} from "../redux/store/State"; import {bindActionCreators} from "redux"; import * as Dispatcher from "../redux/action/Dispatcher"; import {GLOBAL_TIMER} from "../config/GlobalTimer"; const connector = connect( (s: State) => ({timer: s.level.timer || {}}), (d) => bindActionCreators(Dispatcher, d), ); type EditTimerData = { levelTime?: string; canvasBaseTime?: string; canvasPerColorTime?: string; }; export const NO_TIMER_DATA: Required<EditTimerData> = { levelTime: "-1", canvasBaseTime: "-1", canvasPerColorTime: "-1" }; function toEdit(t: TimerData): EditTimerData { if (!t) return {}; const a: EditTimerData = {}; if (typeof t.levelTime === "number") a.levelTime = t.levelTime.toString(); if (typeof t.canvasBaseTime === "number") a.canvasBaseTime = t.canvasBaseTime.toString(); if (typeof t.canvasPerColorTime === "number") a.canvasPerColorTime = t.canvasPerColorTime.toString(); return a; } const pi = (n: string) => { const z = parseInt(n); if (isNaN(z)) return -1; return z; } const TimerWindow: React.FunctionComponent<ConnectedProps<typeof connector> & { onClose: () => void; show: boolean; }> = (p) => { const [timer, setTimer] = useState<Required<EditTimerData>>(NO_TIMER_DATA); useEffect(() => { setTimer({...NO_TIMER_DATA, ...toEdit(p.timer)}); }, [p.show]); const ok = () => { p.setLevelTime(pi(timer.levelTime)); p.setCanvasBaseTime(pi(timer.canvasBaseTime)); p.setCanvasPerColorTime(pi(timer.canvasPerColorTime)); p.onClose(); }; const setAttr = (attrName: keyof TimerData, e: ChangeEvent<HTMLInputElement>) => { const v = e.currentTarget.value as string; setTimer({...timer, [attrName]: v}); } const cancel = p.onClose; return ( <> <Modal backdrop="static" show={p.show} onHide={() => { }}> <Modal.Header><Modal.Title>Change timer</Modal.Title></Modal.Header> <Modal.Body> <div className={"setting"}> <strong>Level time</strong> <FormControl onChange={(e: ChangeEvent<HTMLInputElement>) => setAttr("levelTime", e)} value={timer.levelTime} type={"number"} min={-1} max={600} step={1} /> This is the time allowed for the entire level.<br/> -1 means using global default, which is set at {GLOBAL_TIMER.levelTime}. </div> <div className={"setting pt-2"}> <strong>Canvas Base Time</strong> <FormControl onChange={(e: ChangeEvent<HTMLInputElement>) => setAttr("canvasBaseTime", e)} value={timer.canvasBaseTime} type={"number"} min={-1} max={60} step={1} /> This is the base time for each canvas.<br/> -1 means using global default, which is set at {GLOBAL_TIMER.canvasBaseTime}. </div> <div className={"setting pt-2"}> <strong>Canvas Per Color Time</strong> <FormControl onChange={(e: ChangeEvent<HTMLInputElement>) => setAttr("canvasPerColorTime", e)} value={timer.canvasPerColorTime} type={"number"} min={-1} max={60} step={1} /> This is the time for each color on a canvas, added to the base time.<br/> -1 means using global default, which is set at {GLOBAL_TIMER.canvasPerColorTime}. </div> <style jsx>{` .setting:not(:first-child) { margin-top: 1rem; } `}</style> </Modal.Body> <Modal.Footer> <Button onClick={cancel} variant="secondary">Cancel</Button> <Button onClick={ok} variant="primary">OK</Button> </Modal.Footer> </Modal> </> ) }; export default connector(TimerWindow);
foxhatleo/dragonglass-level-editor
components/Simulate.tsx
import React, {useEffect, useState} from "react"; import {Button, Modal} from "react-bootstrap"; import {connect, ConnectedProps} from "react-redux"; import State, {TimerData} from "../redux/store/State"; import {bindActionCreators} from "redux"; import * as Dispatcher from "../redux/action/Dispatcher"; import ColorStrip from "./ColorStrip"; import {GLOBAL_TIMER} from "../config/GlobalTimer"; const connector = connect( (s: State) => ({timer: s.level.timer || {}, queues: s.level.queues, colors: s.level.colors}), (d) => bindActionCreators(Dispatcher, d), ); const Simulate: React.FunctionComponent<ConnectedProps<typeof connector> & { show: boolean; onClose: () => void; }> = (p) => { const [queues, setQueues] = useState<number[][][]>([[]]); const [startTimes, setStartTimes] = useState<number[][]>([]); const [colors, setColors] = useState<[number, number, number][]>([[0, 0, 0]]); const [currentColor, setCurrentColor] = useState<number>(0); const [actionCount, setActionCount] = useState<number>(0); const [lostClients, setLostClients] = useState<number>(0); const [satisfiedClients, setSatisfiedClients] = useState<number>(0); const [lostClientsP, setLostClientsP] = useState<number>(0); const [mode, _setMode] = useState<number>(0); const [selected, setSelected] = useState<boolean[]>([]); const [startDrag, setStartDrag] = useState<number>(-1); const [stage, setStage] = useState<number>(0); const clearSelected = () => setSelected([...Array(p.queues.length)].map(_ => false)); const [secondsSoFar, setSecondsSoFar] = useState<number>(-3); const [interval, setInt] = useState<any | null>(null); const [timerData, setTimerData] = useState<Required<TimerData>>(GLOBAL_TIMER); const [leftTime, setLeftTime] = useState<number>(-1); const unfinished = queues.reduce((p, c) => p + ((c.length > 0) ? 1 : 0), 0); const done = unfinished == 0 || secondsSoFar >= timerData.levelTime; if (done && leftTime < 0) { setLeftTime(timerData.levelTime - secondsSoFar); } const setMode = (i: number) => { _setMode(i); clearSelected(); setStartDrag(-1); } useEffect(() => { if (stage > 0 && !interval) { setInt(setInterval(() => updateCountdown(), 1000)); } else if (interval) { clearInterval(interval); setInt(null); setSecondsSoFar(-3); } return () => { if (interval) clearInterval(interval); setInt(null); }; }, [stage]); const updateCountdown = () => { setSecondsSoFar(i => i + 1); }; const calcAllowedTime = (i: number, q = queues, td = timerData) => { return q[i].length == 0 || q[i][0].length == 0 ? 0 : (td.canvasBaseTime + td.canvasPerColorTime * q[i][0].length); }; if (stage > 0 && !done) { let cq: number[][][] = queues; for (let i = 0; i < queues.length; i++) { if (queues[i].length <= 0) break; const elapsedTime = secondsSoFar - startTimes[i][1]; if (elapsedTime >= startTimes[i][0]) { setLostClientsP(i => i + 1); setQueues(q => { const t = q.map(a => a.map(b => b.map(c => c))); cq = t; t[i].splice(0, 1); return t; }) setStartTimes(st => { const nst = st.map(a => a.map(b => b)); nst[i][0] = calcAllowedTime(i, cq); nst[i][1] = secondsSoFar; return nst; }); } } } const reset = () => { const td = {...GLOBAL_TIMER, ...p.timer}; setQueues(p.queues.map(a => a.map(b => b.map(c => c)))); setCurrentColor(Math.floor(p.colors.length * Math.random())); setStartTimes([...Array(p.queues.length)].map((_, i) => [calcAllowedTime(i, p.queues, td), 0])); setActionCount(0); setLostClients(0); setLostClientsP(0); setSatisfiedClients(0); setColors(p.colors); _setMode(0); clearSelected(); setStartDrag(-1); setStage(0); setSecondsSoFar(-3); setTimerData(td); setLeftTime(-1); }; useEffect(() => { reset(); }, [p.show]); const hover = (i: number) => { if (mode == 2) { setSelected((selected) => { const s = selected.concat(); s[i] = true; if (i == s.length - 1 && i - 1 >= 0) s[i - 1] = true; else if (i + 1 < s.length) s[i + 1] = true; return s; }); } else if (mode == 3 && startDrag >= 0) { const a = Math.min(i, startDrag); const b = Math.max(i, startDrag); const s = [...Array(p.queues.length)].map(_ => false); for (let i = a; i <= b; i++) { s[i] = true; } setSelected(s); } }; const out = (_: number) => { if (mode == 2) clearSelected(); }; const baseClick = (i: number) => { let removingFromQueue = false; let q: number[][][]; setQueues((queues) => { const t = queues.map(a => a.map(b => b.map(c => c))); if (i < 0 || i >= queues.length || t[i].length == 0) return t; const ind = t[i][0].indexOf(currentColor); if (ind < 0) { if (t[i][0].length == 0) return t; setLostClients((p) => p + 1); t[i].splice(0, 1); removingFromQueue = true; q = t; return t; } t[i][0].splice(ind, 1); if (t[i][0].length < 1) { removingFromQueue = true; t[i].splice(0, 1); setSatisfiedClients(i => i + 1) } q = t; return t; }); if (removingFromQueue) setStartTimes((s) => { const ns = [...s]; if (queues[i].length <= 0) return ns; ns[i][0] = calcAllowedTime(i, q); ns[i][1] = secondsSoFar; return ns; }); }; const clickTile = (i: number) => { switch (mode) { case 1: { setActionCount(a => a + 1); baseClick(i); break; } case 2: { setActionCount(a => a + 1); baseClick(i); baseClick(i >= queues.length - 1 ? i - 1 : i + 1); break; } case 3: { if (startDrag < 0) { setStartDrag(i); setSelected((selected) => { const s = selected.concat(); s[i] = true; return s; }); } else if (startDrag == i) { setStartDrag(-1); clearSelected(); } else { setActionCount(a => a + 1); const a = Math.min(i, startDrag); const b = Math.max(i, startDrag); for (let i = a; i <= b; i++) { baseClick(i); } setStartDrag(-1); clearSelected(); } break; } } }; let helpText = ""; switch (mode) { case 0: { helpText = "Choose an action to begin."; break; } case 1: { helpText = "To scribble, click on any single item."; break; } case 2: { helpText = "To flick, click on an item. The one next to it will also be painted." break; } case 3: { if (startDrag < 0) { helpText = "To drag, start by clicking an beginning item."; } else { helpText = "Now, click on the ending item. The area to be painted will be highlighted automatically."; } break; } } return ( <Modal show={p.show} onHide={p.onClose} backdrop="static" dialogClassName="modal-bw"> <Modal.Header closeButton><Modal.Title>Simulate playtesting</Modal.Title></Modal.Header> <Modal.Body> {stage == 0 ? <div className={"starting"}> <Button variant={mode == 1 ? "primary" : "secondary"} onClick={() => setStage(1)}>Start</Button> <style jsx>{` .starting { text-align: center; } `}</style> </div> : secondsSoFar < 0 ? <div className={"sec"}> {-secondsSoFar} <style jsx>{` .sec { text-align: center; font-size: 3em; } `}</style> </div> : ((!done ? <> <div>Level Time left: {timerData.levelTime - secondsSoFar}</div> <div className={"container-row"}> {[...Array(queues.length)].map((_, i) => ( <div key={i}> <div> {queues[i].length <= 1 ? "<empty>" : <ColorStrip colors={queues[i][1].map(id => colors[id])}/>} </div> </div> ))} </div> <div className={"container-row front pt-2"}> {[...Array(queues.length)].map((_, i) => ( <div key={i} className={(selected[i] ? "selected" : "") + (queues[i].length == 0 ? " empty" : "")}> <div onClick={() => clickTile(i)} onMouseEnter={() => hover(i)} onMouseLeave={() => out(i)}> {queues[i].length == 0 ? <>&lt;empty&gt;<br/>0</> : <><ColorStrip colors={queues[i][0].map(id => colors[id])}/> <br/>{startTimes[i][0] - (secondsSoFar - startTimes[i][1])}</>} </div> </div> ))} </div> <div className={"pt-2"}> Current paintbrush: <span className={"pl-1"}><ColorStrip colors={[colors.length > currentColor ? colors[currentColor] : colors[0]]}/></span> <br/>Actions taken: {actionCount} <br/>Clients satisfied: {satisfiedClients} <br/>Clients lost due to incorrect actions: {lostClients} <br/>Clients lost due to impatience: {lostClientsP} <p>{helpText}</p> <p> <Button variant={mode == 1 ? "primary" : "secondary"} onClick={() => setMode(1)}>Scribble</Button> <Button variant={mode == 2 ? "primary" : "secondary"} onClick={() => setMode(2)}>Flick</Button> <Button variant={mode == 3 ? "primary" : "secondary"} onClick={() => setMode(3)}>Drag</Button> {p.colors.map((c, i) => <Button variant="secondary" key={i} onClick={() => { setActionCount(a => a + 1); setCurrentColor(i) }}><ColorStrip colors={[c]}/></Button>)} </p> </div> <style jsx>{` :global(.modal-bw) { width: 90%; max-width: 800px !important; } .container-row { width: 100%; display: flex; } .container-row > div { flex-grow: 1; flex-shrink: 1; flex-basis: 0; padding: .1rem; } .container-row > div > div { padding: 1rem; } .front > div > div { background: rgba(255, 255, 255, .1); } .front > div.empty { pointer-events: none; } .front > div:not(.empty) > div:hover, .front > div.selected:not(.empty) > div { background: var(--primary); } div { text-align: center; } `}</style> </> : <> <strong>Finished.</strong> <br/>Level time remaining when finishing: {leftTime} <br/>Actions taken: {actionCount} <br/>Clients satisfied: {satisfiedClients} <br/>Clients lost due to incorrect actions: {lostClients} <br/>Clients lost due to impatience: {lostClientsP} <br/>Clients unfinished because level time ran out: {unfinished} <div className={"mt-2"}><Button onClick={() => reset()}>Restart</Button></div> </>))} </Modal.Body> </Modal> ) }; export default connector(Simulate);
foxhatleo/dragonglass-level-editor
components/UnexpectedError.tsx
<reponame>foxhatleo/dragonglass-level-editor import React, {SyntheticEvent} from "react"; import {Alert, Button, FormControl, Modal} from "react-bootstrap"; import {connect, ConnectedProps} from "react-redux"; import RootState from "../redux/store/State"; const connector = connect((s: RootState) => ({ fileId: s.fileId, ge: s.globalError })); const UnexpectedError: React.FunctionComponent<ConnectedProps<typeof connector>> = (p) => { const e404 = !!p.ge && JSON.parse(p.ge).error.body?.error?.code == 404 && p.fileId != ""; const redirect404 = () => window.location.replace(`https://drive.google.com/file/d/${p.fileId}/view`); if (e404) { setTimeout(redirect404, 5000); } return ( <> <Modal backdrop="static" show={!!p.ge && !e404} onHide={() => {}}> <Modal.Header><Modal.Title>Unexpected Error</Modal.Title></Modal.Header> <Modal.Body> Try refreshing. If problem persists, please copy and paste the following information and send it to Leo for debugging. <FormControl rows={5} as={"textarea"} className={"mt-2"} value={p.ge} onChange={() => { }} onSelect={(e: SyntheticEvent<HTMLTextAreaElement>) => { e.currentTarget.selectionStart = 0; e.currentTarget.selectionEnd = p.ge.length; }}/> </Modal.Body> </Modal> <Modal backdrop="static" show={e404} onHide={() => {}}> <Modal.Header><Modal.Title>404 Error</Modal.Title></Modal.Header> <Modal.Body> The level editor cannot find the resource requested. This issue may be resolved by reopening it from Google Drive. <p>Redirecting you momentarily...</p> </Modal.Body> <Modal.Footer> <Button variant={"primary"} onClick={redirect404}>Redirect now</Button> </Modal.Footer> </Modal> </> ); } export default connector(UnexpectedError);
foxhatleo/dragonglass-level-editor
components/TableArea.tsx
import React from "react"; import {connect, ConnectedProps} from "react-redux"; import State from "../redux/store/State"; import {bindActionCreators} from "redux"; import * as Dispatcher from "../redux/action/Dispatcher"; import {Alert, Button} from "react-bootstrap"; import ColorStrip from "./ColorStrip"; const connector = connect( (s: State) => ({ colors: s.level.colors, queues: s.level.queues, editorSelected: s.selected, }), (d) => bindActionCreators(Dispatcher, d), ); const _Cell: React.FunctionComponent<ConnectedProps<typeof connector> & { queueInd: number; customerInd: number; }> = (p) => { const queue = p.queues[p.queueInd]; if (p.customerInd > queue.length) return null; let inner; if (p.customerInd < queue.length) { const colorInds = queue[p.customerInd]; const colors = colorInds.map((c) => p.colors[c]); inner = <ColorStrip colors={colors}/>; } else if (p.customerInd == queue.length) { inner = <>&lt;add&gt;</> } const handleClick = (e: React.MouseEvent<HTMLDivElement>) => { e.stopPropagation(); if (e.shiftKey) { p.shiftClick([p.queueInd, p.customerInd]); } else if (e.ctrlKey) { p.ctrlClick([p.queueInd, p.customerInd]); } else { p.singleClick([p.queueInd, p.customerInd]); } }; return ( <> <div className={"area"} onClick={handleClick}> {inner} <style jsx>{` .area { user-select: none; -moz-user-select: none; -ms-user-select: none; -webkit-user-select: none; padding: 1rem .2rem; color: white; background: ${p.editorSelected[p.queueInd][p.customerInd] ? "var(--primary)" : "rgba(255, 255, 255, .1)"}; } .area:hover, .area:active { background: ${p.editorSelected[p.queueInd][p.customerInd] ? "var(--primary)" : "rgba(255, 255, 255, .3)"}; } `}</style> </div> </> ) } const Cell = connector(_Cell); const TableArea: React.FunctionComponent<ConnectedProps<typeof connector>> = (p) => { const clear = (e: React.MouseEvent<HTMLDivElement>) => { p.clearSelection(); } return ( <> <div className={"table-area"} onClick={clear}> <div> {[...Array(p.queues.length)].map((_, i) => <div className={"cell"} key={i}>Q{i + 1}</div>)} <div className={"cell pm"}> {p.queues.length < 6 ? <Button onClick={p.addQueue}>+</Button> : ""} {p.queues.length > 1 ? <Button onClick={p.removeQueue}>-</Button> : ""} </div> </div> {[...Array(p.queues.reduce((u, c) => Math.max(u, c.length), 0) + 1)].map( (_, i) => ( <div className={"content-row"} key={i}> {[...Array(p.queues.length)].map((_, i2) => ( <div className={"cell"} key={i2}> <Cell queueInd={i2} customerInd={i}/> </div> ))} </div> ) )} </div> <Alert variant={"dark"} className={"mt-3"}> <strong>How to use:</strong> <ul> <li>Hold Ctrl to select individual cells at the same time.</li> <li>Hold Shift to select an area of cells.</li> <li>Click anywhere else in the table area to clear selections.</li> </ul> </Alert> <style jsx>{` .table-area :global(.btn) { padding: .1rem .5rem; } .table-area { padding: 1rem; border-radius: 10px; background: black; border: 1px solid #666; } .cell { width: 120px; display: inline-block; padding: .1rem .2rem; text-align: center; } .cell.pm { width: auto; } .content-row .cell { padding: .3rem .1rem; } `}</style> </> ); }; export default connector(TableArea);
foxhatleo/dragonglass-level-editor
components/App.tsx
<filename>components/App.tsx<gh_stars>0 import React, {useEffect, useState} from "react"; import AuthManager from "./AuthManager"; import FileManager from "./FileManager"; import SaveManager from "./SaveManager"; import TableArea from "./TableArea"; import {Container} from "react-bootstrap"; import Navbar from "./Navbar"; import TimerWindow from "./TimerWindow"; import ColorWindow from "./ColorWindow"; import Simulate from "./Simulate"; import UnexpectedError from "./UnexpectedError"; import Head from "next/head"; import {connect, ConnectedProps} from "react-redux"; import RootState from "../redux/store/State"; import {bindActionCreators} from "redux"; import * as Dispatcher from "../redux/action/Dispatcher"; const connector = connect( (s: RootState) => ({ready: s.ready, name: s.name, fileId: s.fileId}), (d) => bindActionCreators(Dispatcher, d), ); export type AppProps = { createMode: boolean; id: string; }; const App: React.FunctionComponent<ConnectedProps<typeof connector> & AppProps> = (p) => { const [showColor, setShowColor] = useState<boolean>(false); const [simulate, setSimulate] = useState<boolean>(false); const [timer, setTimer] = useState<boolean>(false); useEffect(() => { p.setFileId(p.id); }, [p.id]); return ( <React.Fragment> <Head> <title>{!p.name ? "" : `${p.name} - `}Panic Painter Level Editor</title> </Head> <AuthManager/> <FileManager createMode={p.createMode}/> <SaveManager/> {p.ready ? <> <ColorWindow show={showColor} onClose={() => setShowColor(false)}/> <TimerWindow show={timer} onClose={() => setTimer(false)}/> <Simulate show={simulate} onClose={() => setSimulate(false)}/> <Navbar onColor={() => setShowColor(true)} onSimulate={() => setSimulate(true)} onTimer={() => setTimer(true)}/> <Container className={"mt-5 mb-3"} fluid="lg"> <TableArea/> <div className={"text-center text-muted"}> Made with ♥ by Wenhao "Leo" Liang<br/> Source available at <a href={"https://github.com/foxhatleo/panic-painter-level-editor/"} target="_blank" rel="noreferrer noopener">GitHub</a> <span className={"pl-3"}> <a href={"https://github.com/foxhatleo/panic-painter-level-editor/blob/master/PRIVACY.md"} target="_blank" rel="noreferrer noopener"> Privacy Policy </a> </span> </div> </Container> </> : ""} <UnexpectedError/> </React.Fragment> ); }; export default connector(App);
foxhatleo/dragonglass-level-editor
components/ColorWindow.tsx
import React, {useEffect, useState} from "react"; import {Button, Modal} from "react-bootstrap"; import {connect, ConnectedProps} from "react-redux"; import State from "../redux/store/State"; import {bindActionCreators} from "redux"; import * as Dispatcher from "../redux/action/Dispatcher"; import {CompactPicker} from "react-color"; const connector = connect( (s: State) => ({colors: s.level.colors}), (d) => bindActionCreators(Dispatcher, d), ); const ColorWindow: React.FunctionComponent<ConnectedProps<typeof connector> & { onClose: () => void; show: boolean; }> = (p) => { const [colors, setColors] = useState<[number, number, number][]>([]); useEffect(() => { setColors(p.colors.map(i => i.map(c => c) as [number, number, number])); }, [p.show]); const ok = () => { p.setColors(colors); p.onClose(); }; const addNewColor = () => { setColors([...colors, [255, 255, 255]]) }; const removeColor = () => { const c = colors.concat(); c.splice(c.length - 1, 1); setColors(c); }; const cancel = p.onClose; return ( <> <Modal backdrop="static" show={p.show} onHide={() => { }}> <Modal.Header><Modal.Title>Change colors</Modal.Title></Modal.Header> <Modal.Body> { colors.map((c, i) => ( <div key={i} className={"color"}> <strong>Color {i}</strong> <div className={"mt-2"}><CompactPicker color={{r: c[0], g: c[1], b: c[2]}} onChange={(c) => { const cs = colors.concat(); cs[i] = [c.rgb.r, c.rgb.g, c.rgb.b]; setColors(cs); }}/></div> </div> )) } <div className={"color"}> <Button disabled={colors.length >= 6} onClick={addNewColor}>Add a new color</Button> <Button disabled={colors.length <= 1} onClick={removeColor}>Remove last color</Button> </div> <style jsx>{` .color:not(:first-child) { margin-top: 1rem; } `}</style> </Modal.Body> <Modal.Footer> <Button onClick={cancel} variant="secondary">Cancel</Button> <Button onClick={ok} variant="primary">OK</Button> </Modal.Footer> </Modal> </> ) }; export default connector(ColorWindow);
foxhatleo/dragonglass-level-editor
pages/[rid]/create.tsx
<filename>pages/[rid]/create.tsx import {useRouter} from "next/router"; import App from "../../components/App"; import store from "../../redux/store/Store"; import {Provider} from "react-redux"; import React from "react"; const Create = () => { const router = useRouter(); const {rid} = router.query; return ( <Provider store={store}> <App createMode={true} id={rid as string}/> </Provider> ); } export default Create;
foxhatleo/dragonglass-level-editor
components/SaveManager.ts
<gh_stars>0 import React from "react"; import {connect, ConnectedProps} from "react-redux"; import State from "../redux/store/State"; import {bindActionCreators} from "redux"; import * as Dispatcher from "../redux/action/Dispatcher"; import {setTimeout} from "timers"; import * as V1Representation from "../redux/util/V1Representation"; import {reload} from "./FileManager"; import {isDebug} from "../config/Debug"; const connector = connect( (s: State) => ({ level: s.level, saved: s.lastStored, fileId: s.fileId, ready: s.ready, }), (d) => bindActionCreators(Dispatcher, d), ); const MAX_ERROR_ALLOWED = 5; class SaveManager extends React.Component<ConnectedProps<typeof connector>, { saving: boolean; savingError: number; refreshing: boolean; refreshingError: number; }> { private interval: ReturnType<typeof setTimeout> | undefined; private interval2: ReturnType<typeof setTimeout> | undefined; constructor(p: ConnectedProps<typeof connector>) { super(p); this.state = {saving: false, refreshing: false, savingError: 0, refreshingError: 0}; } update(): void { const l = this.props.level; const j = V1Representation.stringify(l); if (isDebug()) { this.props.markSaved(j); return; } if (this.state.saving || !this.props.ready || j == this.props.saved || this.state.savingError > MAX_ERROR_ALLOWED) return; this.setState({saving: true}); gapi.client.request({ path: "/upload/drive/v3/files/" + this.props.fileId, method: "PATCH", params: { uploadType: "media" }, body: j }).then(() => { this.props.markSaved(j); this.setState((p) => ({...p, saving: false, savingError: 0})); }, (e) => { if (this.state.savingError > MAX_ERROR_ALLOWED) { this.props.fail(["save:save", e]); return; } this.setState((p) => ({...p, saving: false, savingError: p.savingError + 1})); }); } refresh(): void { if (isDebug() || this.state.saving || this.state.refreshing || this.state.refreshingError > MAX_ERROR_ALLOWED) return; const l = this.props.level; const j = V1Representation.stringify(l); if (j != this.props.saved) return; this.setState({refreshing: true}); reload("save:refresh", this.props, () => { this.setState((p) => ({...p, refreshing: false, refreshingError: 0})); }, (e) => { if (this.state.refreshingError > MAX_ERROR_ALLOWED) { this.props.fail(["save:save", e]); return; } this.setState((p) => ({...p, refreshing: false, refreshingError: p.refreshingError + 1})); }); } componentDidMount() { this.interval = setInterval(() => this.update(), 200); this.interval2 = setInterval(() => this.refresh(), 1000); } componentWillUnmount() { if (typeof this.interval !== undefined) clearInterval(this.interval as any); if (typeof this.interval2 !== undefined) clearInterval(this.interval2 as any); } render() { if (this.props.ready && typeof window !== "undefined") { window.onbeforeunload = this.state.saving ? function () { return "It seems that your level has not been saved yet. Are you sure you want to exit?"; } : null; } return null; } } export default connector(SaveManager);
foxhatleo/dragonglass-level-editor
redux/store/Store.ts
import {createStore, Store as ReduxStore} from "redux"; import State from "./State"; import RootReducer from "../reducer/RootReducer"; import Action from "../action/Action"; const store: ReduxStore<State, Action> = createStore(RootReducer); export default store;
foxhatleo/dragonglass-level-editor
config/Google.ts
export const CLIENT_ID = "656662885342-aku8gdtahr0g4a9lu6rieetf8k9kegfp.apps.googleusercontent.com"; export const API_KEY = "<KEY>"; export const DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/drive/v3/rest"]; export const SCOPES = [ "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile", // "https://www.googleapis.com/auth/drive", // "https://www.googleapis.com/auth/drive.install", "https://www.googleapis.com/auth/drive.appdata", // "https://www.googleapis.com/auth/drive.metadata", "https://www.googleapis.com/auth/drive.file", ];
tukusejssirs/nest-orm-test
src/status/status.module.ts
import {Module} from '@nestjs/common' import {StatusService} from './status.service' import {StatusController} from './status.controller' import {MikroOrmModule} from '@mikro-orm/nestjs' import {Status} from './status.entity' import {ConfigModule} from '@nestjs/config' @Module({ imports: [MikroOrmModule.forFeature([Status]), ConfigModule], providers: [StatusService], controllers: [StatusController] }) export class StatusModule {}
tukusejssirs/nest-orm-test
src/status/status.entity.ts
import {Entity, PrimaryKey, Property} from '@mikro-orm/core' @Entity({schema: 'm1', tableName: 'status'}) export class Status { @PrimaryKey() id!: number @Property({columnType: 'TIMESTAMP WITH TIME ZONE', fieldName: 'datumcas'}) createdAt = new Date() @Property({columnType: 'VARCHAR(32)', default: '', length: 32}) program: string @Property({columnType: 'SMALLINT', fieldName: 'zelena'}) green: number @Property({columnType: 'SMALLINT', fieldName: 'oranzova'}) yellow: number @Property({columnType: 'SMALLINT', fieldName: 'cervena'}) red: number @Property({columnType: 'SMALLINT', fieldName: 'vypnuty'}) isTurnedOff: number @Property({columnType: 'SMALLINT', fieldName: 'chyba'}) error: number constructor(createdAt: Date, program: string, green: number, yellow: number, red: number, isTurnedOff: number, error: number) { this.createdAt = createdAt this.program = program this.green = green this.yellow = yellow this.red = red this.isTurnedOff = isTurnedOff this.error = error } }
tukusejssirs/nest-orm-test
src/status/status.repository.ts
import {EntityRepository} from '@mikro-orm/postgresql' import {Status} from './status.entity' export class StatusRepository extends EntityRepository<Status> {}
tukusejssirs/nest-orm-test
src/status/status.service.ts
import {Injectable} from '@nestjs/common' import {InjectRepository} from '@mikro-orm/nestjs' import {Status} from './status.entity' import {EntityRepository} from '@mikro-orm/postgresql' import {ConfigService} from '@nestjs/config' import {CreateStatusDto} from './create-status.dto' @Injectable() export class StatusService { constructor( @InjectRepository(Status) private readonly statusRepository: EntityRepository<Status>, private readonly configService: ConfigService ) {} async createStatus(createStatusDto: CreateStatusDto): Promise<Status> { const status = new Status(createStatusDto.createdAt, createStatusDto.program, createStatusDto.green, createStatusDto.yellow, createStatusDto.red, createStatusDto.isTurnedOff, createStatusDto.error) await this.statusRepository.persistAndFlush(status) return status } }
tukusejssirs/nest-orm-test
src/status/create-status.dto.ts
<reponame>tukusejssirs/nest-orm-test import {IsDate, IsInt, IsNotEmpty, Max, Min} from 'class-validator' export class CreateStatusDto { @IsDate() createdAt: Date @IsNotEmpty() program: string @IsInt() @Min(0) @Max(1) green: number @IsInt() @Min(0) @Max(1) yellow: number @IsInt() @Min(0) @Max(1) red: number @IsInt() @Min(0) @Max(1) isTurnedOff: number @IsInt() @Min(0) @Max(1) error: number }
tukusejssirs/nest-orm-test
src/mikro-orm.config.ts
<filename>src/mikro-orm.config.ts import {Logger} from '@nestjs/common' import {Options} from '@mikro-orm/core' import {SqlHighlighter} from '@mikro-orm/sql-highlighter' import {TsMorphMetadataProvider} from '@mikro-orm/reflection' import {ConfigService} from '@nestjs/config' import cfg from '../config/getEnvConfig' const logger = new Logger('MikroORM') const configService = new ConfigService() const config = { entities: ['dist/**/*.entity.js'], entitiesTs: ['src/**/*.entity.ts'], dbName: configService.get<string>('PSQL_DB_NAME_CS') || cfg()['PSQL_DB_NAME_CS'], type: 'postgresql', host: configService.get<string>('PSQL_HOST', 'localhost') || cfg()['PSQL_HOST'], port: configService.get<number>('PSQL_PORT', 5432) || cfg()['PSQL_PORT'], // FIXME: Consider disabling highlighting, for potential performance issues. highlighter: new SqlHighlighter(), debug: false, logger: logger.log.bind(logger), username: configService.get<string>('PSQL_USER') || cfg()['PSQL_USER'], password: configService.get<string>('P<PASSWORD>') || cfg()['PSQL_PASS'], synchronize: true, metadataProvider: TsMorphMetadataProvider, // TODO: Use migrations; more info: https://en.wikipedia.org/wiki/Schema_migration migrations: { tableName: 'mikro_orm_migrations', // name of database table with log of executed transactions path: './migrations', // path to the folder with migrations pattern: /^[\w-]+\d+\.ts$/, // regex pattern for the migration files transactional: true, // wrap each migration in a transaction disableForeignKeys: true, // wrap statements with `set foreign_key_checks = 0` or equivalent allOrNothing: true, // wrap all migrations in master transaction dropTables: true, // allow to disable table dropping safe: true, // allow to disable table and column dropping; TODO: Do we need this to set to `true`? emit: 'ts' // migration generation mode } } as Options if (configService.get<string>('LOG_LEVEL', 'warn') === 'debug' || configService.get<string>('LOG_LEVEL', 'warn') === 'trace' || cfg()['LOG_LEVEL'] === 'debug' || cfg()['LOG_LEVEL'] === 'trace') { config.debug = true } export default config
tukusejssirs/nest-orm-test
src/app.module.ts
import config from '../config/getEnvConfig' import {ConfigModule} from '@nestjs/config' import {StatusModule} from './status/status.module' import {MiddlewareConsumer, Module, NestModule} from '@nestjs/common' import {MikroOrmMiddleware, MikroOrmModule} from '@mikro-orm/nestjs' @Module({ imports: [MikroOrmModule.forRoot(), StatusModule, ConfigModule.forRoot({load: [config]})], providers: [], controllers: [] }) export class AppModule implements NestModule { // Note: For some reason the auth middlewares in profile and article modules are fired before the request context one, so they would fail to access contextual EM. by registering the middleware directly in AppModule, we can get around this issue. configure(consumer: MiddlewareConsumer) { consumer.apply(MikroOrmMiddleware).forRoutes('*') } }
tukusejssirs/nest-orm-test
src/status/status.controller.ts
import {Body, Controller, Get, Post} from '@nestjs/common' import {CreateStatusDto} from './create-status.dto' import {Status} from './status.entity' import {StatusService} from './status.service' @Controller('status') export class StatusController { constructor(private readonly StatusService: StatusService) {} @Post() async createStatus(@Body() createStatusDto: CreateStatusDto): Promise<Status> { return await this.StatusService.createStatus(createStatusDto) } }
tukusejssirs/nest-orm-test
config/getEnvConfig.ts
<filename>config/getEnvConfig.ts // Change the config as required. const config = { LOG_LEVEL: 'debug', NEST_PORT: 3000, PSQL_DB_NAME_CS: 'test_db', PSQL_HOST: 'localhost', PSQL_PASS: 'password', PSQL_PORT: 5432, PSQL_USER: 'postgres' } export default () => config
tukusejssirs/nest-orm-test
src/main.ts
import {AppModule} from './app.module' import {FastifyAdapter, NestFastifyApplication} from '@nestjs/platform-fastify' import {NestFactory} from '@nestjs/core' import {ConfigService} from '@nestjs/config' import {RequestContext} from '@mikro-orm/core' import {MikroORM} from '@mikro-orm/core' async function bootstrap() { const configService = new ConfigService() const logLevel = configService.get<string>('LOG_LEVEL', 'warn') const app = await NestFactory.create<NestFastifyApplication>(AppModule, new FastifyAdapter({logger: {level: logLevel, prettyPrint: true}})) const orm = await MikroORM.init() app.setGlobalPrefix('api') // Note: This is added as for @B4nan's recommendation. app.use((req, res, next) => RequestContext.create(orm.em, next)) await app.listen(configService.get<number>('NEST_PORT', 3000)) } bootstrap()
DannyMyles/Dhub_Search
src/services/profile.service.ts
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { map } from 'rxjs/operators' import { Repository } from 'src/app/repository'; import { User } from 'src/app/user'; import { environment } from 'src/environments/environment'; @Injectable({ providedIn: 'root' }) export class ProfileService { private username!: string; private clientid = environment.clientid private clientsecret = environment.clientsecret constructor(private http:HttpClient) { console.log("service is now ready"); this.username ='DannyaMyles' } getProfileInfo(username:string):Promise<User>{ return this.http.get<User>("https://api.github.com/users/" + username +"?client_id"+ this.clientid + "&client_secret" + this.clientsecret) .toPromise(); } getRepositories(url:string):Promise<Repository[]>{ return this.http.get<Repository[]>( url +"?client_id"+ this.clientid + "&client_secret" + this.clientsecret) .toPromise(); } }
DannyMyles/Dhub_Search
src/app/components/profile/profile.component.ts
<reponame>DannyMyles/Dhub_Search<filename>src/app/components/profile/profile.component.ts import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { Repository } from 'src/app/repository'; import { User } from 'src/app/user'; import { ProfileService } from 'src/services/profile.service'; @Component({ selector: 'app-profile', templateUrl: './profile.component.html', styleUrls: ['./profile.component.css'] }) export class ProfileComponent implements OnInit { user!:User; repositories!:Repository[]; active = 1; constructor(private route:ActivatedRoute, private profileservice:ProfileService) { } ngOnInit(): void { this.route.params.subscribe(param=>{ console.log(param); this.profileservice.getProfileInfo(param.username).then((response:User)=>{ console.log(response); this.user = response; this.profileservice.getRepositories(response.repos_url).then((repositoryResponse:Repository[])=>{ console.log(repositoryResponse); this.repositories = repositoryResponse; }) }) }) } }
DannyMyles/Dhub_Search
src/app/repository.ts
// import { profile } from "console"; export class Repository { name:String; description:String Private:Boolean constructor(name:String, description:String, Private:Boolean){ this.name=name; this.description=description; this.Private=Private; } }
DannyMyles/Dhub_Search
src/environments/environment.ts
export const environment = { production: false, clientid:'1279d7ec943e647e717e', clientsecret:'1271fce86f453086ae073f7a83f4f5af7f95dca5' };
DannyMyles/Dhub_Search
src/environments/environment.prod.ts
<reponame>DannyMyles/Dhub_Search export const environment = { production: true, clientid:'1279d7ec943e647e717e', clientsecret:'1271fce86f453086ae073f7a83f4f5af7f95dca5' };
DannyMyles/Dhub_Search
src/app/user.ts
export class User { login:String; bio:String; avatar_url:string name:String; company:String; followers:number; following:number; repos_url:string; constructor(login:String, bio:String, avata:string, name:String, company:String, followers:number, following:number, repos_url:string,){ this.bio = bio; this.login = login; this.avatar_url = avata; this.name= name; this.company=company; this.followers=followers; this.following=following; this.repos_url=repos_url; } }
yegobox/kraken
frontend/projects/components/src/lib/full-page/full-page.component.spec.ts
<reponame>yegobox/kraken import {async, ComponentFixture, fakeAsync, TestBed, tick} from '@angular/core/testing'; import {FullPageComponent} from './full-page.component'; import {Component, ViewChild} from '@angular/core'; import {By} from '@angular/platform-browser'; import {EventModule} from 'projects/event/src/lib/event.module'; import {EventBusService} from 'projects/event/src/lib/event-bus.service'; import {TabsAddedEvent} from 'projects/tabs/src/lib/tabs-added-event'; import {TabsSide} from 'projects/tabs/src/lib/tabs-side'; import {TabsPosition} from 'projects/tabs/src/lib/tabs-position'; @Component({ selector: 'lib-test', template: ` <lib-full-page> <div class="menu" full-page-menu>Menu</div> <div class="content" full-page-content>Content</div> </lib-full-page> ` }) class TestComponent { @ViewChild(FullPageComponent, {static: true}) fullPage: FullPageComponent; } describe('FullPageComponent', () => { let component: TestComponent; let fixture: ComponentFixture<TestComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ imports: [EventModule], declarations: [TestComponent, FullPageComponent] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(TestComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should display menu and content', () => { expect(fixture.debugElement.query(By.css('[full-page-menu]')).nativeElement.innerHTML).toBe('Menu'); expect(fixture.debugElement.query(By.css('[full-page-content]')).nativeElement.innerHTML).toBe('Content'); }); it('should leave place for tabs', fakeAsync(() => { const eventBus = TestBed.get(EventBusService); eventBus.publish(new TabsAddedEvent(TabsSide.BOTTOM, TabsPosition.START)); eventBus.publish(new TabsAddedEvent(TabsSide.LEFT, TabsPosition.START)); eventBus.publish(new TabsAddedEvent(TabsSide.TOP, TabsPosition.START)); eventBus.publish(new TabsAddedEvent(TabsSide.RIGHT, TabsPosition.START)); tick(100); fixture.detectChanges(); expect(component.fullPage.tabsRight).toBe(true); expect(component.fullPage.tabsLeft).toBe(true); expect(component.fullPage.tabsBottom).toBe(true); expect(component.fullPage.tabsTop).toBe(true); })); });
yegobox/kraken
frontend/projects/runtime/src/lib/runtime-log/runtime-logs-panel/runtime-logs-panel.component.ts
<reponame>yegobox/kraken import {Component, Injector, OnDestroy} from '@angular/core'; import {ReplaySubject, Subscription} from 'rxjs'; import {WindowService} from 'projects/tools/src/lib/window.service'; import {EventBusService} from 'projects/event/src/lib/event-bus.service'; import {map} from 'rxjs/operators'; import * as _ from 'lodash'; import {ComponentPortal, PortalInjector} from '@angular/cdk/portal'; import {LogEvent} from 'projects/runtime/src/lib/events/log-event'; import {Log} from 'projects/runtime/src/lib/entities/log'; import { RUNTIME_LOGS, RuntimeLogsComponent } from 'projects/runtime/src/lib/runtime-log/runtime-logs/runtime-logs.component'; import {RuntimeLogService} from 'projects/runtime/src/lib/runtime-log/runtime-log.service'; import {OpenLogsEvent} from 'projects/runtime/src/lib/events/open-logs-event'; import {OpenTasksEvent} from 'projects/runtime/src/lib/events/open-tasks-event'; export interface LogTab { content: ComponentPortal<RuntimeLogsComponent>; lastLog: Log; logsSubject: ReplaySubject<Log>; } @Component({ selector: 'lib-runtime-logs-panel', templateUrl: './runtime-logs-panel.component.html', styleUrls: ['./runtime-logs-panel.component.scss'] }) export class RuntimeLogsPanelComponent implements OnDestroy { tabs: LogTab[] = []; selectedIndex = 0; private subscription: Subscription; constructor(public windowService: WindowService, private eventBus: EventBusService, private service: RuntimeLogService, private injector: Injector) { this.subscription = this.eventBus.of<LogEvent>(LogEvent.CHANNEL) .pipe(map(event => event.log)) .subscribe(this._onLog.bind(this)); } ngOnDestroy() { this.subscription.unsubscribe(); } close(index: number) { this.tabs.splice(index, 1); if (this.selectedIndex === index) { this._updateSelectedIndex(index); } } stop(log: Log) { this.service.cancel(log); } closeTerminatedLogs() { _.remove(this.tabs, (tab: LogTab) => { return tab.lastLog.status === 'CLOSED'; }); this._updateSelectedIndex(this.selectedIndex); } _updateSelectedIndex(index: number) { this.selectedIndex = Math.min(Math.max(index, 0), this.tabs.length - 1); if (!this.tabs.length) { this.eventBus.publish(new OpenTasksEvent()); } } _onLog(log: Log) { const index: number = _.findIndex(this.tabs, commandTab => commandTab.lastLog.id === log.id); if (index === -1) { this._addLogsTab(log); return; } this.tabs[index].logsSubject.next(log); this.tabs[index].lastLog = log; } _addLogsTab(log: Log) { const injectorTokens = new WeakMap(); const logsSubject = new ReplaySubject<Log>(10); injectorTokens.set(RUNTIME_LOGS, logsSubject); const content = new ComponentPortal(RuntimeLogsComponent, null, new PortalInjector(this.injector, injectorTokens)); const command: LogTab = { content, logsSubject, lastLog: log, }; logsSubject.next(log); this.tabs.push(command); this.selectedIndex = this.tabs.length - 1; this.eventBus.publish(new OpenLogsEvent()); } }
yegobox/kraken
frontend/projects/gatling/src/app/simulations/simulation.service.spec.ts
<gh_stars>0 import {TestBed} from '@angular/core/testing'; import {SimulationService} from './simulation.service'; import {StorageNodeToExtPipe} from 'projects/storage/src/lib/storage-pipes/storage-node-to-ext.pipe'; import {testStorageDirectoryNode, testStorageFileNode} from 'projects/storage/src/lib/entities/storage-node.spec'; import {StorageService} from 'projects/storage/src/lib/storage.service'; import {DialogService} from 'projects/dialog/src/lib/dialog.service'; import {storageServiceSpy} from 'projects/storage/src/lib/storage.service.spec'; import {dialogsServiceSpy} from 'projects/dialog/src/lib/dialog.service.spec'; import {of} from 'rxjs'; import {ExecuteSimulationDialogComponent} from 'projects/gatling/src/app/simulations/simulation-dialogs/execute-simulation-dialog/execute-simulation-dialog.component'; import {DateTimeToStringPipe} from 'projects/date/src/lib/date-time-to-string.pipe'; import {EventBusService} from 'projects/event/src/lib/event-bus.service'; import {eventBusSpy} from 'projects/event/src/lib/event-bus.service.spec'; import {CoreTestModule} from 'projects/commons/src/lib/core/core.module.spec'; import {GatlingConfigurationService} from 'projects/gatling/src/app/gatling-configuration.service'; import {gatlingConfigurationServiceSpy} from 'projects/gatling/src/app/gatling-configuration.service.spec'; import {FileUploadDialogComponent} from 'projects/storage/src/lib/storage-dialogs/file-upload-dialog/file-upload-dialog.component'; import {ImportHarDialogComponent} from 'projects/gatling/src/app/simulations/simulation-dialogs/import-har-dialog/import-har-dialog.component'; import {OpenResultsEvent} from 'projects/analysis/src/lib/events/open-results-event'; import {DialogSize} from 'projects/dialog/src/lib/dialog-size'; import {StorageConfigurationService} from 'projects/storage/src/lib/storage-configuration.service'; import {storageConfigurationServiceSpy} from 'projects/storage/src/lib/storage-configuration.service.spec'; import {RuntimeTaskService} from 'projects/runtime/src/lib/runtime-task/runtime-task.service'; import {runtimeTaskServiceSpy} from 'projects/runtime/src/lib/runtime-task/runtime-task.service.spec'; import {testExecutionContext} from 'projects/runtime/src/lib/entities/execution-context.spec'; import {OpenTasksEvent} from 'projects/runtime/src/lib/events/open-tasks-event'; import SpyObj = jasmine.SpyObj; export const simulationServiceSpy = () => { const spy = jasmine.createSpyObj('SimulationService', [ 'run', 'debug', 'isSimulationNode', 'isHarNode', ]); return spy; }; describe('SimulationService', () => { let service: SimulationService; let storage: SpyObj<StorageService>; let dialogs: SpyObj<DialogService>; let eventBus: SpyObj<EventBusService>; let tasks: SpyObj<RuntimeTaskService>; beforeEach(() => { TestBed.configureTestingModule({ imports: [CoreTestModule], providers: [ {provide: StorageService, useValue: storageServiceSpy()}, {provide: DialogService, useValue: dialogsServiceSpy()}, {provide: RuntimeTaskService, useValue: runtimeTaskServiceSpy()}, {provide: EventBusService, useValue: eventBusSpy()}, {provide: StorageConfigurationService, useValue: storageConfigurationServiceSpy()}, {provide: GatlingConfigurationService, useValue: gatlingConfigurationServiceSpy()}, StorageNodeToExtPipe, DateTimeToStringPipe, SimulationService, ] }); service = TestBed.get(SimulationService); tasks = TestBed.get(RuntimeTaskService); storage = TestBed.get(StorageService); dialogs = TestBed.get(DialogService); eventBus = TestBed.get(EventBusService); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should run', () => { storage.getContent.and.returnValue(of(` package computerdatabase.advanced import io.gatling.core.Predef._ import io.gatling.http.Predef._ import scala.concurrent.duration._ import java.util.concurrent.ThreadLocalRandom class AdvancedSimulationStep05 extends Simulation { object Search { `)); const context = testExecutionContext(); dialogs.open.and.returnValue(of(context)); tasks.execute.and.returnValue(of('taskId')); service.run(testStorageFileNode()); expect(dialogs.open).toHaveBeenCalledWith(ExecuteSimulationDialogComponent, DialogSize.SIZE_LG, { simulationPackage: 'computerdatabase.advanced', simulationClass: 'AdvancedSimulationStep05', type: 'RUN', atOnce: false, }); expect(tasks.execute).toHaveBeenCalledWith(context); expect(eventBus.publish).toHaveBeenCalledWith(new OpenResultsEvent()); expect(eventBus.publish).toHaveBeenCalledWith(new OpenTasksEvent()); }); it('should debug', () => { storage.getContent.and.returnValue(of(` package computerdatabase.advanced import io.gatling.core.Predef._ import io.gatling.http.Predef._ import scala.concurrent.duration._ import java.util.concurrent.ThreadLocalRandom class AdvancedSimulationStep05 extends Simulation { setUp(scn.inject(atOnceUsers(1)).protocols(httpProtocol)) object Search { `)); const context = testExecutionContext(); dialogs.open.and.returnValue(of(context)); tasks.execute.and.returnValue(of('taskId')); service.debug(testStorageFileNode()); expect(dialogs.open).toHaveBeenCalledWith(ExecuteSimulationDialogComponent, DialogSize.SIZE_LG, { simulationPackage: 'computerdatabase.advanced', simulationClass: 'AdvancedSimulationStep05', type: 'DEBUG', atOnce: true, }); expect(tasks.execute).toHaveBeenCalledWith(context); expect(eventBus.publish).toHaveBeenCalledWith(new OpenResultsEvent()); expect(eventBus.publish).toHaveBeenCalledWith(new OpenTasksEvent()); }); it('should return isSimulationNode', () => { expect(service.isSimulationNode(null)).toBeFalsy(); expect(service.isSimulationNode(testStorageDirectoryNode())).toBeFalsy(); expect(service.isSimulationNode(testStorageFileNode())).toBeFalsy(); expect(service.isSimulationNode({ path: 'simulations/basic.scala', type: 'FILE', depth: 1, length: 42, lastModified: 1337 })).toBeTruthy(); }); it('should return isHarNode', () => { expect(service.isHarNode(null)).toBeFalsy(); expect(service.isHarNode(testStorageDirectoryNode())).toBeFalsy(); expect(service.isHarNode(testStorageFileNode())).toBeFalsy(); expect(service.isHarNode({ path: 'simulations/basic.har', type: 'FILE', depth: 1, length: 42, lastModified: 1337 })).toBeTruthy(); }); it('should uploadHar', () => { const importHar = spyOn(service, 'importHar'); dialogs.open.and.returnValue(of(['test.har'])); service.uploadHar(); expect(dialogs.open).toHaveBeenCalledWith(FileUploadDialogComponent, DialogSize.SIZE_MD, { endpoint: 'storageApiUrl/files/set/file?path=gatling/user-files/simulations', multiple: false, accept: '.har', title: 'Upload HAR File' }); expect(importHar).toHaveBeenCalledWith({path: 'gatling/user-files/simulations/test.har'} as any); }); it('should importHar', () => { const context = testExecutionContext(); dialogs.open.and.returnValue(of(context)); tasks.execute.and.returnValue(of('taskId')); service.importHar({path: 'gatling/user-files/simulations/test.har'} as any); expect(dialogs.open).toHaveBeenCalledWith(ImportHarDialogComponent, DialogSize.SIZE_MD, {harPath: 'gatling/user-files/simulations/test.har'}); expect(tasks.execute).toHaveBeenCalledWith(context); }); });
yegobox/kraken
frontend/projects/tabs/src/lib/tab-header/tab-header.component.spec.ts
import {async, ComponentFixture, inject, TestBed} from '@angular/core/testing'; import {ComponentType} from '@angular/cdk/portal/typings/portal'; import {ComponentPortal} from '@angular/cdk/portal'; import {faQuestionCircle} from '@fortawesome/free-solid-svg-icons'; import {library} from '@fortawesome/fontawesome-svg-core'; import {Component} from '@angular/core'; import { SIDE_HEADER_DATA, TAB_HEADER_DATA, TabHeaderComponent } from 'projects/tabs/src/lib/tab-header/tab-header.component'; import {Tab} from 'projects/tabs/src/lib/tab'; import {TabsModule} from 'projects/tabs/src/lib/tabs.module'; import {TabsSide} from 'projects/tabs/src/lib/tabs-side'; import {IconFa} from 'projects/icon/src/lib/icon-fa'; import {EventBusService} from 'projects/event/src/lib/event-bus.service'; import {TabSelectedEvent} from 'projects/tabs/src/lib/tab-selected-event'; import {TabUnselectedEvent} from 'projects/tabs/src/lib/tab-unselected-event'; import {TabsService} from 'projects/tabs/src/lib/tabs.service'; import {tabsServiceSpy} from 'projects/tabs/src/lib/tabs.service.spec'; import Spy = jasmine.Spy; library.add(faQuestionCircle); export const newTestTab = (component: ComponentType<any>) => { return new Tab(new ComponentPortal(component), 'TestStart', new IconFa(faQuestionCircle), 'TEST', false, ['test']); }; @Component({ selector: 'lib-test', template: `test` }) class TestComponent { } describe('TabHeaderComponent', () => { let component: TabHeaderComponent; let fixture: ComponentFixture<TabHeaderComponent>; let testTab: Tab; beforeEach(async(() => { testTab = newTestTab(TestComponent); TestBed.configureTestingModule({ imports: [TabsModule], declarations: [TestComponent], providers: [ {provide: TAB_HEADER_DATA, useValue: testTab}, {provide: SIDE_HEADER_DATA, useValue: TabsSide.LEFT}, {provide: TabsService, useValue: tabsServiceSpy()}, ] }) .compileComponents(); })); it('should create and select tab', inject([TabsService], (tabsService: TabsService) => { (tabsService.isSelected as Spy).and.returnValue(true); fixture = TestBed.createComponent(TabHeaderComponent); component = fixture.componentInstance; fixture.detectChanges(); expect(component).toBeTruthy(); expect(component.state).toBe('selected'); })); it('should create and not select tab', inject([EventBusService, TabsService], (eventBus: EventBusService, tabsService: TabsService) => { (tabsService.isSelected as Spy).and.returnValue(false); fixture = TestBed.createComponent(TabHeaderComponent); component = fixture.componentInstance; fixture.detectChanges(); expect(component).toBeTruthy(); expect(component.state).toBe(''); eventBus.publish(new TabSelectedEvent(testTab)); expect(component.state).toBe('selected'); eventBus.publish(new TabUnselectedEvent(testTab)); expect(component.state).toBe(''); })); });
yegobox/kraken
frontend/projects/gatling/src/app/simulations/simulation-dialogs/description-input/description-input.component.ts
import {Component, Input, OnInit} from '@angular/core'; import {FormControl, FormGroup, Validators} from '@angular/forms'; @Component({ selector: 'lib-description-input', templateUrl: './description-input.component.html', styleUrls: ['./description-input.component.scss'] }) export class DescriptionInputComponent implements OnInit { @Input() formGroup: FormGroup; @Input() value: string; ngOnInit() { this.formGroup.addControl('description', new FormControl(this.value, [Validators.required, Validators.pattern(/^[\w\s]+$/)])); } get description() { return this.formGroup.get('description'); } }
yegobox/kraken
frontend/projects/runtime/src/lib/runtime-task/tasks-table/tasks-table.component.spec.ts
import {async, ComponentFixture, TestBed} from '@angular/core/testing'; import {TasksTableComponent} from 'projects/runtime/src/lib/runtime-task/tasks-table/tasks-table.component'; import {CoreTestModule} from 'projects/commons/src/lib/core/core.module.spec'; import {RuntimeTaskService} from 'projects/runtime/src/lib/runtime-task/runtime-task.service'; import {EventBusService} from 'projects/event/src/lib/event-bus.service'; import {runtimeTaskServiceSpy} from 'projects/runtime/src/lib/runtime-task/runtime-task.service.spec'; import {testTask, testTasks} from 'projects/runtime/src/lib/entities/task.spec'; import {TaskSelectedEvent} from 'projects/runtime/src/lib/events/task-selected-event'; import {TasksRefreshEvent} from 'projects/runtime/src/lib/events/tasks-refresh-event'; import {of} from 'rxjs'; import * as _ from 'lodash'; import SpyObj = jasmine.SpyObj; import {DialogService} from 'projects/dialog/src/lib/dialog.service'; import {dialogsServiceSpy} from 'projects/dialog/src/lib/dialog.service.spec'; import {testContainers} from 'projects/runtime/src/lib/entities/container.spec'; import {Task} from 'projects/runtime/src/lib/entities/task'; describe('TaskTableComponent', () => { let component: TasksTableComponent; let fixture: ComponentFixture<TasksTableComponent>; let taskService: SpyObj<RuntimeTaskService>; let eventBus: EventBusService; let dialogs: SpyObj<DialogService>; beforeEach(async(() => { taskService = runtimeTaskServiceSpy(); dialogs = dialogsServiceSpy(); TestBed.configureTestingModule({ imports: [CoreTestModule], declarations: [TasksTableComponent], providers: [ {provide: RuntimeTaskService, useValue: taskService}, {provide: DialogService, useValue: dialogs}, EventBusService, ] }) .overrideTemplate(TasksTableComponent, '') .compileComponents(); taskService.list.and.returnValue(of(testTasks())); eventBus = TestBed.get(EventBusService); })); beforeEach(() => { fixture = TestBed.createComponent(TasksTableComponent); component = fixture.componentInstance; fixture.detectChanges(); }); afterEach(() => { component.ngOnDestroy(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should fire TaskSelectedEvent on selection change', () => { const task = testTask(); const publish = spyOn(eventBus, 'publish'); component._selection.select(task); expect(publish).toHaveBeenCalledWith(new TaskSelectedEvent(task)); }); it('should fire TaskSelectedEvent on selection change', () => { const task = testTask(); const publish = spyOn(eventBus, 'publish'); component._selection.select(task); expect(publish).toHaveBeenCalledWith(new TaskSelectedEvent(task)); }); it('should set tasks on TasksRefreshEvent', () => { const tasks = testTasks(); eventBus.publish(new TasksRefreshEvent(tasks)); expect(component.loading).toBeFalsy(); expect(component.dataSource.data).toBe(tasks); expect(component.dataSource.sort).toBe(component.sort); }); it('should refresh on init', () => { const refresh = spyOn(component, 'refresh'); component.ngOnInit(); expect(refresh).toHaveBeenCalled(); }); it('should list tasks on refresh', () => { component.refresh(); expect(taskService.list).toHaveBeenCalled(); }); it('should handle selection', () => { const task = testTask(); expect(component.hasSelection).toBeFalsy(); component.selection = task; expect(component.hasSelection).toBeTruthy(); expect(component.isSelected(task)).toBeTruthy(); component.selection = null; expect(component.hasSelection).toBeFalsy(); }); it('should set tasks update selection', () => { const tasks = testTasks(); const task = _.cloneDeep(tasks[0]); component.selection = task; component.tasks = tasks; expect(component.selection).toBe(tasks[0]); expect(component.selection).not.toBe(task); }); it('should set tasks unselect', () => { const tasks = []; component.selection = testTask(); component.tasks = tasks; expect(component.hasSelection).toBeFalse(); }); it('should set tasks update selection first not done', () => { const tasks: Task[] = [ { id: 'id1', startDate: 0, status: 'DONE', type: 'RUN', containers: testContainers(), expectedCount: 2, description: 'description1' }, { id: 'id2', startDate: 0, status: 'READY', type: 'RUN', containers: testContainers(), expectedCount: 2, description: 'description2' } ]; const task = _.cloneDeep(tasks[0]); component.selection = task; component.tasks = tasks; expect(component.selection).toBe(tasks[1]); }); it('should set tasks update selection current done', () => { const tasks: Task[] = [ { id: 'id1', startDate: 0, status: 'DONE', type: 'RUN', containers: testContainers(), expectedCount: 2, description: 'description1' }, { id: 'id2', startDate: 0, status: 'DONE', type: 'RUN', containers: testContainers(), expectedCount: 2, description: 'description2' } ]; const task = _.cloneDeep(tasks[0]); component.selection = task; component.tasks = tasks; expect(component.selection).toBe(tasks[0]); }); it('should cancel task', () => { dialogs.confirm.and.returnValue(of(null)); taskService.cancel.and.returnValue(of('taskId')); const task = testTask(); component.cancel(task); expect(taskService.cancel).toHaveBeenCalledWith(task); }); });
yegobox/kraken
frontend/projects/analysis/src/lib/results/results.module.ts
import {NgModule} from '@angular/core'; import {CommonModule} from '@angular/common'; import {ResultsTableComponent} from 'projects/analysis/src/lib/results/results-table/results-table.component'; import {StorageModule} from 'projects/storage/src/lib/storage.module'; import {VendorsModule} from 'projects/vendors/src/lib/vendors.module'; import {DateModule} from 'projects/date/src/lib/date.module'; import {IconModule} from 'projects/icon/src/lib/icon.module'; import {DialogModule} from 'projects/dialog/src/lib/dialog.module'; import {AnalysisModule} from 'projects/analysis/src/lib/analysis.module'; import {DebugModule} from 'projects/analysis/src/lib/results/debug/debug.module'; import {ResultsTableService} from 'projects/analysis/src/lib/results/results-table/results-table.service'; import {IsDebugEntryStorageNodePipe} from 'projects/analysis/src/lib/results/is-debug-entry-storage-node.pipe'; import {TreeModule} from 'projects/tree/src/lib/tree.module'; import {StorageListService} from 'projects/storage/src/lib/storage-list.service'; import {ComponentsModule} from 'projects/components/src/lib/components.module'; @NgModule({ declarations: [ResultsTableComponent, IsDebugEntryStorageNodePipe], exports: [ResultsTableComponent, DebugModule], entryComponents: [ResultsTableComponent], imports: [ CommonModule, StorageModule, VendorsModule, DateModule, IconModule, DialogModule, AnalysisModule, TreeModule, ComponentsModule ], providers: [ ResultsTableService, StorageListService, IsDebugEntryStorageNodePipe, ] }) export class ResultsModule { constructor(results: ResultsTableService) { results.init(); } }
yegobox/kraken
frontend/projects/storage/src/lib/entities/storage-watcher-event.ts
<filename>frontend/projects/storage/src/lib/entities/storage-watcher-event.ts import {StorageNode} from 'projects/storage/src/lib/entities/storage-node'; export interface StorageWatcherEvent { node: StorageNode; event: string; }
yegobox/kraken
frontend/projects/storage/src/lib/storage-dialogs/file-name-dialog/file-name-dialog.component.spec.ts
<filename>frontend/projects/storage/src/lib/storage-dialogs/file-name-dialog/file-name-dialog.component.spec.ts<gh_stars>1-10 import {async, ComponentFixture, TestBed} from '@angular/core/testing'; import {FileNameDialogComponent} from './file-name-dialog.component'; import {MAT_DIALOG_DATA, MatDialogRef} from '@angular/material'; import {dialogRefSpy} from 'projects/commons/src/lib/mock/material.mock.spec'; import {VendorsModule} from 'projects/vendors/src/lib/vendors.module'; describe('FileNameDialogComponent', () => { let component: FileNameDialogComponent; let fixture: ComponentFixture<FileNameDialogComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ imports: [VendorsModule], declarations: [FileNameDialogComponent], providers: [ {provide: MAT_DIALOG_DATA, useValue: {title: 'title', name: 'name'}}, {provide: MatDialogRef, useValue: dialogRefSpy()}, ] }) .overrideTemplate(FileNameDialogComponent, '') .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(FileNameDialogComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); expect(component.fileName.value).toBe('name'); }); });
yegobox/kraken
frontend/projects/tree/src/lib/toggle-button/toggle-button.component.spec.ts
import {async, ComponentFixture, TestBed} from '@angular/core/testing'; import {ToggleButtonComponent} from './toggle-button.component'; import {TreeModule} from '../tree.module'; import {CdkTree, CdkTreeNode} from '@angular/cdk/tree'; import {CoreTestModule} from 'projects/commons/src/lib/core/core.module.spec'; describe('ToggleButtonComponent', () => { let component: ToggleButtonComponent; let fixture: ComponentFixture<ToggleButtonComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ imports: [CoreTestModule, TreeModule], providers: [ {provide: CdkTree, useValue: jasmine.createSpyObj('CdkTree', [''])}, {provide: CdkTreeNode, useValue: jasmine.createSpyObj('CdkTreeNode', [''])}, ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(ToggleButtonComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should set expanded', () => { component.expanded = true; expect(component.state).toBe('expanded'); }); it('should set collapsed', () => { component.expanded = false; expect(component.state).toBe('collapsed'); }); });
yegobox/kraken
frontend/projects/components/src/lib/message/message.component.spec.ts
import {async, ComponentFixture, TestBed} from '@angular/core/testing'; import {MessageComponent} from 'projects/components/src/lib/message/message.component'; import {CoreTestModule} from 'projects/commons/src/lib/core/core.module.spec'; import {ComponentsModule} from 'projects/components/src/lib/components.module'; describe('MessageComponent', () => { let component: MessageComponent; let fixture: ComponentFixture<MessageComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ imports: [CoreTestModule, ComponentsModule] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(MessageComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
yegobox/kraken
frontend/projects/storage/src/lib/storage-editor/storage-editor/storage-editor.component.spec.ts
import {async, ComponentFixture, TestBed} from '@angular/core/testing'; import {StorageEditorComponent} from './storage-editor.component'; import {STORAGE_ID} from 'projects/storage/src/lib/storage-id'; import {LocalStorageService} from 'projects/tools/src/lib/local-storage.service'; import {StorageService} from 'projects/storage/src/lib/storage.service'; import {EventBusService} from 'projects/event/src/lib/event-bus.service'; import {localStorageServiceSpy} from 'projects/tools/src/lib/local-storage.service.spec'; import {storageServiceSpy} from 'projects/storage/src/lib/storage.service.spec'; import {eventBusSpy} from 'projects/event/src/lib/event-bus.service.spec'; import * as _ from 'lodash'; import {StorageNode} from 'projects/storage/src/lib/entities/storage-node'; import {SelectNodeEvent} from 'projects/storage/src/lib/events/select-node-event'; import {OpenNodeEvent} from 'projects/storage/src/lib/events/open-node-event'; import {StorageEditorService} from 'projects/storage/src/lib/storage-editor/storage-editor.service'; import {storageEditorServiceSpy} from 'projects/storage/src/lib/storage-editor/storage-editor.service.spec'; import {NodeDeletedEvent} from 'projects/storage/src/lib/events/node-deleted-event'; import {SaveNodeEvent} from 'projects/storage/src/lib/events/save-node-event'; import Spy = jasmine.Spy; import {NodePendingSaveEvent} from 'projects/storage/src/lib/events/node-pending-save-event'; import {testStorageFileNode, testStorageNodes} from 'projects/storage/src/lib/entities/storage-node.spec'; import {StorageNodeToPredicatePipe} from 'projects/storage/src/lib/storage-pipes/storage-node-to-predicate.pipe'; import SpyObj = jasmine.SpyObj; import {cold, getTestScheduler} from 'jasmine-marbles'; import {StorageConfigurationService} from 'projects/storage/src/lib/storage-configuration.service'; import {storageConfigurationServiceSpy} from 'projects/storage/src/lib/storage-configuration.service.spec'; import {SelectHelpEvent} from 'projects/help/src/lib/help-panel/select-help-event'; describe('StorageEditorComponent', () => { let component: StorageEditorComponent; let fixture: ComponentFixture<StorageEditorComponent>; let storage: SpyObj<StorageService>; let eventBus: EventBusService; let editorService: StorageEditorService; let configuration: SpyObj<StorageConfigurationService>; let nodes: StorageNode[]; beforeEach(async(() => { TestBed.configureTestingModule({ providers: [ {provide: STORAGE_ID, useValue: 'test'}, {provide: LocalStorageService, useValue: localStorageServiceSpy()}, {provide: StorageService, useValue: storageServiceSpy()}, {provide: EventBusService, useValue: eventBusSpy()}, {provide: StorageEditorService, useValue: storageEditorServiceSpy()}, {provide: StorageConfigurationService, useValue: storageConfigurationServiceSpy()}, StorageNodeToPredicatePipe, ], declarations: [StorageEditorComponent] }) .overrideTemplate(StorageEditorComponent, '') .compileComponents(); nodes = testStorageNodes(); storage = TestBed.get(StorageService); storage.filterExisting.and.returnValue(cold('---x|', {x: nodes})); eventBus = TestBed.get(EventBusService); editorService = TestBed.get(StorageEditorService); configuration = TestBed.get(StorageConfigurationService); })); beforeEach(() => { fixture = TestBed.createComponent(StorageEditorComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should filter existing nodes', () => { component.nodes.next([]); component.selectedIndex.next(42); getTestScheduler().flush(); expect(component.nodes.value).toEqual(nodes); expect(component.selectedIndex.value).toBe(nodes.length - 1); }); it('should filter existing nodes and select readme', () => { nodes.length = 0; component.nodes.next([]); component.selectedIndex.next(42); getTestScheduler().flush(); expect(component.nodes.value).toEqual([configuration.readmeNode]); expect(component.selectedIndex.value).toBe(0); }); it('should close node', () => { component.nodes.next(_.cloneDeep(nodes)); component.selectedIndex.next(2); component.closeNode(4); expect(component.nodes.value.length).toBe(nodes.length - 1); expect(component.selectedIndex.value).toBe(2); }); it('should close selected node', () => { component.nodes.next(_.cloneDeep(nodes)); component.selectedIndex.next(2); component.closeNode(2); expect(component.nodes.value.length).toBe(nodes.length - 1); expect(component.selectedIndex.value).toBe(2); }); it('should close selected node and update index', () => { component.nodes.next(_.cloneDeep(nodes)); const index = nodes.length - 1; component.selectedIndex.next(index); component.closeNode(index); expect(component.nodes.value.length).toBe(nodes.length - 1); expect(component.selectedIndex.value).toBe(index - 1); }); it('should selectIndex', () => { component.nodes.next(nodes); component.selectedIndex.next(0); component.selectIndex(2); expect(eventBus.publish).toHaveBeenCalledWith(new SelectNodeEvent(nodes[2])); expect(eventBus.publish).toHaveBeenCalledWith(new SelectHelpEvent('TEST')); }); it('should selectIndex -1', () => { component.nodes.next(nodes); component.selectedIndex.next(0); component.selectIndex(-1); expect(eventBus.publish).not.toHaveBeenCalled(); }); it('should _openNode select tab', () => { component.nodes.next(nodes); component.selectedIndex.next(0); component._openNode(new OpenNodeEvent(nodes[5])); expect(component.selectedIndex.value).toBe(5); }); it('should _openNode add tab', () => { const node = testStorageFileNode(); component.nodes.next([]); component.selectedIndex.next(-1); component._openNode(new OpenNodeEvent(node)); expect(component.nodes.value).toEqual([node]); expect(component.selectedIndex.value).toBe(0); }); it('should return node editor', () => { const node = testStorageFileNode(); const editor: any = {key: 'value'}; (editorService.getNodeEditor as Spy).and.returnValue(editor); expect(component.getNodeEditor(node)).toBe(editor); expect(component.getNodeEditor(node)).toBe(editor); expect(editorService.getNodeEditor).toHaveBeenCalledTimes(1); }); it('should close deleted node', () => { spyOn(component, 'closeNode'); component.nodes.next(nodes); component._closeDeletedNode(new NodeDeletedEvent(nodes[1])); expect(component.closeNode).toHaveBeenCalledWith(1); }); it('should not close deleted node', () => { spyOn(component, 'closeNode'); component.nodes.next(nodes); component._closeDeletedNode(new NodeDeletedEvent({ path: 'other/file/that/wont/be/found', type: 'DIRECTORY', depth: 0, length: 0, lastModified: 0 })); expect(component.closeNode).not.toHaveBeenCalled(); }); it('should save on ctrl + s', () => { const binding = component._saveKeyBinding; component.nodes.next(nodes); component.selectedIndex.next(2); expect(binding.binding(null)).toBe(true); expect(eventBus.publish).toHaveBeenCalledWith(new SaveNodeEvent(nodes[2])); }); it('should not save on ctrl + s if no nodes', () => { const binding = component._saveKeyBinding; component.nodes.next([]); component.selectedIndex.next(0); expect(binding.binding(null)).toBe(true); expect(eventBus.publish).not.toHaveBeenCalled(); }); it('should handle pending save state', () => { const node = testStorageFileNode(); expect(component.isPendingSave(node)).toBeFalsy(); component._tagPendingSaveNode(new NodePendingSaveEvent(node, true)); expect(component.isPendingSave(node)).toBeTruthy(); component._tagPendingSaveNode(new NodePendingSaveEvent(node, false)); expect(component.isPendingSave(node)).toBeFalsy(); }); it('should close others', () => { component.nodes.next(nodes); component.selectedIndex.next(1); component.closeOthers(); expect(component.nodes.value.length).toBe(1); expect(component.selectedIndex.value).toBe(0); }); it('should close all', () => { component.nodes.next(nodes); component.selectedIndex.next(1); component.closeAll(); expect(component.nodes.value.length).toBe(0); expect(component.selectedIndex.value).toBe(-1); }); });
yegobox/kraken
frontend/projects/runtime/src/lib/runtime-task/runtime-task.module.ts
import {NgModule} from '@angular/core'; import {RuntimeContainerService} from 'projects/runtime/src/lib/runtime-task/runtime-container.service'; import {RuntimeTaskService} from 'projects/runtime/src/lib/runtime-task/runtime-task.service'; import {TasksTableComponent} from 'projects/runtime/src/lib/runtime-task/tasks-table/tasks-table.component'; import {ComponentsModule} from 'projects/components/src/lib/components.module'; import {VendorsModule} from 'projects/vendors/src/lib/vendors.module'; import {IconModule} from 'projects/icon/src/lib/icon.module'; import {DateModule} from 'projects/date/src/lib/date.module'; import {ToolsModule} from 'projects/tools/src/lib/tools.module'; import { ContainersTableComponent } from './containers-table/containers-table.component'; import {RuntimeHostModule} from 'projects/runtime/src/lib/runtime-host/runtime-host.module'; import { ContainerStatusComponent } from './container-status/container-status.component'; import {CommonModule} from '@angular/common'; @NgModule({ declarations: [ TasksTableComponent, ContainersTableComponent, ContainerStatusComponent ], imports: [ CommonModule, ComponentsModule, VendorsModule, IconModule, DateModule, ToolsModule, RuntimeHostModule, ], exports: [ TasksTableComponent, ContainersTableComponent ], providers: [ RuntimeContainerService, RuntimeTaskService, ], entryComponents: [ TasksTableComponent, ContainersTableComponent ] }) export class RuntimeTaskModule { }
yegobox/kraken
frontend/projects/storage/src/lib/storage-json.service.spec.ts
<gh_stars>1-10 import {TestBed} from '@angular/core/testing'; import {StorageJsonService} from './storage-json.service'; import {Injectable, OnDestroy} from '@angular/core'; import {StorageService} from 'projects/storage/src/lib/storage.service'; import {StorageListService} from 'projects/storage/src/lib/storage-list.service'; import {StorageNode} from 'projects/storage/src/lib/entities/storage-node'; import {testStorageDirectoryNode, testStorageFileNode} from 'projects/storage/src/lib/entities/storage-node.spec'; import {storageServiceSpy} from 'projects/storage/src/lib/storage.service.spec'; import {storageListServiceSpy} from 'projects/storage/src/lib/storage-list.service.spec'; import SpyObj = jasmine.SpyObj; import {of} from 'rxjs'; import * as _ from 'lodash'; export class TestValue { id: string; } @Injectable() export class TestStorageJsonService extends StorageJsonService<TestValue> implements OnDestroy { constructor( storage: StorageService, storageList: StorageListService, ) { super(storage, storageList, node => node.path, value => value.id); super.init('rootPath', 'matcher', 42); } ngOnDestroy(): void { super.clearSubscriptions(); } } describe('StorageJsonService', () => { let service: TestStorageJsonService; let storage: SpyObj<StorageService>; let storageList: SpyObj<StorageListService>; let node: StorageNode; let value: TestValue; beforeEach(() => { node = testStorageFileNode(); value = {id: node.path}; storage = storageServiceSpy(); storageList = storageListServiceSpy(); TestBed.configureTestingModule({ providers: [ {provide: StorageService, useValue: storage}, {provide: StorageListService, useValue: storageList}, TestStorageJsonService, ] }); service = TestBed.get(TestStorageJsonService); }); afterEach(() => { service.ngOnDestroy(); }); it('should be created', () => { expect(service).toBeTruthy(); expect(storageList.init).toHaveBeenCalledWith('rootPath', 'matcher', 42); }); it('should set/get values', () => { const values = [value]; service.values = values; expect(service.values).toBe(values); }); it('should find', () => { service.values = [value]; expect(service.find(node)).toBe(value); }); it('should _nodesListed', () => { const nodes = [node]; const values = [value]; storage.listJSON.and.returnValue(of(values)); storageList.nodesListed.emit(nodes); expect(service.values).toBe(values); }); it('should _nodeCreated', () => { const values = [value]; storage.getJSON.and.returnValue(of(value)); storageList.nodeCreated.emit(node); expect(service.values).toEqual(values); }); it('should _nodeCreated no duplicates', () => { const values = [value]; service.values = values; storage.getJSON.and.returnValue(of(value)); storageList.nodeCreated.emit(node); expect(service.values.length).toBe(1); }); it('should _nodesDeleted', () => { const values = [value]; service.values = values; storageList.nodesDeleted.emit([node]); expect(service.values).toEqual([]); }); it('should _nodesDeleted nope', () => { const values = [value]; service.values = values; storageList.nodesDeleted.emit([testStorageDirectoryNode()]); expect(service.values).toBe(values); }); it('should _nodeModified', () => { service.values = [value]; const modified = _.cloneDeep(node); modified.length = 666; modified.lastModified = 666; const modifiedValue = {id: modified.path}; storage.getJSON.and.returnValue(of(modifiedValue)); storageList.nodeModified.emit(modified); expect(service.values[0]).toBe(modifiedValue); }); it('should _nodeModified nope', () => { service.values = [value]; storageList.nodeModified.emit(testStorageDirectoryNode()); expect(service.values[0]).toBe(value); }); });
yegobox/kraken
frontend/projects/components/src/lib/router-progress/router-progress.component.spec.ts
import {async, ComponentFixture, fakeAsync, TestBed, tick} from '@angular/core/testing'; import {NavigationCancel, NavigationEnd, NavigationError, NavigationStart, Router} from '@angular/router'; import {of} from 'rxjs'; import {RouterProgressComponent} from 'projects/components/src/lib/router-progress/router-progress.component'; import {CoreTestModule} from 'projects/commons/src/lib/core/core.module.spec'; import {VendorsModule} from 'projects/vendors/src/lib/vendors.module'; import {routerSpy} from 'projects/commons/src/lib/mock/router.mock.spec'; describe('RouterProgressComponent', () => { let component: RouterProgressComponent; let fixture: ComponentFixture<RouterProgressComponent>; let router: any; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [RouterProgressComponent], imports: [VendorsModule, CoreTestModule], providers: [ {provide: Router, useValue: routerSpy()} ] }) .compileComponents(); router = TestBed.get(Router); })); it('should update loading state true', () => { router.events = of(new NavigationStart(null, null)); fixture = TestBed.createComponent(RouterProgressComponent); component = fixture.componentInstance; fixture.detectChanges(); expect(component.loading).toBe(true); }); it('should update loading state false', () => { router.events = of( new NavigationEnd(null, null, null), new NavigationCancel(null, null, null), new NavigationError(null, null, null), ); fixture = TestBed.createComponent(RouterProgressComponent); component = fixture.componentInstance; fixture.detectChanges(); expect(component.loading).toBe(false); }); it('should update loading state false', fakeAsync(() => { router.events = of( new NavigationEnd(null, null, null), new NavigationCancel(null, null, null), new NavigationError(null, null, null), ); const spyHTML: any = {outerHTML: 'someText', setAttribute: jasmine.createSpy('setAttribute')}; spyOn(document, 'getElementById').and.returnValue(spyHTML); fixture = TestBed.createComponent(RouterProgressComponent); component = fixture.componentInstance; fixture.detectChanges(); expect(component.loading).toBe(false); tick(600); expect(spyHTML.outerHTML).toBe(''); expect(spyHTML.setAttribute).toHaveBeenCalledWith('class', 'fade-out'); })); });
yegobox/kraken
frontend/projects/gatling/src/app/simulations/debug-simulation-node-button/debug-simulation-node-button.component.spec.ts
import {async, ComponentFixture, TestBed} from '@angular/core/testing'; import {DebugSimulationNodeButtonComponent} from 'projects/gatling/src/app/simulations/debug-simulation-node-button/debug-simulation-node-button.component'; import {SimulationService} from 'projects/gatling/src/app/simulations/simulation.service'; import {simulationServiceSpy} from 'projects/gatling/src/app/simulations/simulation.service.spec'; describe('DebugSimulationNodeButtonComponent', () => { let component: DebugSimulationNodeButtonComponent; let fixture: ComponentFixture<DebugSimulationNodeButtonComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [DebugSimulationNodeButtonComponent], providers: [ {provide: SimulationService, useValue: simulationServiceSpy()}, ] }) .overrideTemplate(DebugSimulationNodeButtonComponent, '') .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(DebugSimulationNodeButtonComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
yegobox/kraken
frontend/projects/runtime/src/lib/runtime-host/hosts-table/hosts-table.component.ts
<filename>frontend/projects/runtime/src/lib/runtime-host/hosts-table/hosts-table.component.ts import {Component, OnDestroy, OnInit, ViewChild} from '@angular/core'; import {MatTableDataSource} from '@angular/material/table'; import {Host} from 'projects/runtime/src/lib/entities/host'; import {MatSort} from '@angular/material/sort'; import {Subscription} from 'rxjs'; import {REFRESH_ICON} from 'projects/icon/src/lib/icons'; import {RuntimeHostService} from 'projects/runtime/src/lib/runtime-host/runtime-host.service'; @Component({ selector: 'lib-hosts-table', templateUrl: './hosts-table.component.html', styleUrls: ['./hosts-table.component.scss'] }) export class HostsTableComponent implements OnInit, OnDestroy { readonly refreshIcon = REFRESH_ICON; readonly displayedColumns: string[] = ['id', 'name', 'addresses', 'capacity']; loading = true; dataSource: MatTableDataSource<Host>; @ViewChild(MatSort, { static: true }) sort: MatSort; private subscription: Subscription; constructor(private hostService: RuntimeHostService) { this.dataSource = new MatTableDataSource([]); this.subscription = this.hostService.hostsSubject.subscribe((hosts) => this.hosts = hosts); } ngOnInit() { this.refresh(); } ngOnDestroy() { this.subscription.unsubscribe(); } refresh() { this.loading = true; this.hostService.hosts().subscribe(); } set hosts(hosts: Host[]) { this.dataSource = new MatTableDataSource(hosts); this.dataSource.sort = this.sort; this.loading = false; } }
yegobox/kraken
frontend/projects/gatling/src/app/simulations/simulation-dialogs/import-har-dialog/import-har-dialog.component.ts
import {Component, Inject, ViewChild} from '@angular/core'; import {FormBuilder, FormGroup, Validators} from '@angular/forms'; import {MAT_DIALOG_DATA, MatDialogRef} from '@angular/material/dialog'; import {ExecutionContext} from 'projects/runtime/src/lib/entities/execution-context'; import {HostsSelectorComponent} from 'projects/runtime/src/lib/runtime-host/hosts-selector/hosts-selector.component'; export interface ImportHarDialogComponentData { harPath: string; } @Component({ selector: 'app-record-har-dialog', templateUrl: './import-har-dialog.component.html', }) export class ImportHarDialogComponent { recordForm: FormGroup; @ViewChild('hostsSelector', {static: true}) hostsSelector: HostsSelectorComponent; constructor(public dialogRef: MatDialogRef<ImportHarDialogComponent>, @Inject(MAT_DIALOG_DATA) public data: ImportHarDialogComponentData, private fb: FormBuilder) { this.recordForm = this.fb.group({ simulationClass: ['', [ Validators.required, Validators.pattern(/^[\w]+$/) ]], simulationPackage: ['', [ Validators.required, Validators.pattern(/^(\w+\.)*\w+$/) ]], }); } get simulationClass() { return this.recordForm.get('simulationClass'); } get simulationPackage() { return this.recordForm.get('simulationPackage'); } import() { const hostId: string = this.hostsSelector.hostId; const hosts = {}; hosts[hostId] = {}; const context = new ExecutionContext( 'RECORD', `Import har ${this.simulationPackage.value}.${this.simulationClass.value}`, { KRAKEN_GATLING_SIMULATION_CLASS: this.simulationClass.value, KRAKEN_GATLING_SIMULATION_PACKAGE: this.simulationPackage.value, KRAKEN_GATLING_HAR_PATH_REMOTE: this.data.harPath }, hosts ); this.dialogRef.close(context); } }
yegobox/kraken
frontend/projects/runtime/src/lib/entities/execution-context.ts
<filename>frontend/projects/runtime/src/lib/entities/execution-context.ts import {TaskType} from 'projects/runtime/src/lib/entities/task-type'; export class ExecutionContext { constructor(public readonly taskType: TaskType, public readonly description: string, public readonly environment: { [key in string]: string }, public readonly hosts: { [hostId in string]: { [key in string]: string } }, ) { } }
yegobox/kraken
frontend/projects/tabs/src/lib/tabs-header/tabs-header.component.spec.ts
<reponame>yegobox/kraken import {async, ComponentFixture, fakeAsync, inject, TestBed, tick} from '@angular/core/testing'; import {TabsHeaderComponent} from './tabs-header.component'; import {TabsModule} from '../tabs.module'; import {Component, NgModule} from '@angular/core'; import {CoreTestModule} from 'projects/commons/src/lib/core/core.module.spec'; import {WindowService} from 'projects/tools/src/lib/window.service'; import {windowSpy} from 'projects/tools/src/lib/window.service.spec'; import {newTestTab} from 'projects/tabs/src/lib/tab-header/tab-header.component.spec'; import {TabsSide} from 'projects/tabs/src/lib/tabs-side'; import {LocalStorageService} from 'projects/tools/src/lib/local-storage.service'; import {EventBusService} from 'projects/event/src/lib/event-bus.service'; import {TabsContentComponent} from 'projects/tabs/src/lib/tabs-content/tabs-content.component'; import {TabsContentInitializedEvent} from 'projects/tabs/src/lib/tabs-content/tabs-content-initialized-event'; import {TabsPosition} from 'projects/tabs/src/lib/tabs-position'; import {TabsService} from 'projects/tabs/src/lib/tabs.service'; import {tabsServiceSpy} from 'projects/tabs/src/lib/tabs.service.spec'; import {ComponentPortal} from '@angular/cdk/portal'; import {IconFa} from 'projects/icon/src/lib/icon-fa'; import {faQuestionCircle} from '@fortawesome/free-solid-svg-icons'; import {Tab} from 'projects/tabs/src/lib/tab'; @Component({ selector: 'lib-test', template: `test` }) class TestComponent { } @NgModule({ imports: [CoreTestModule, TabsModule], declarations: [TestComponent], entryComponents: [ TestComponent, ], providers: [ {provide: WindowService, useValue: windowSpy()} ] }) class TestModule { } describe('TabsHeaderComponent', () => { let component: TabsHeaderComponent; let fixture: ComponentFixture<TabsHeaderComponent>; let eventBus: EventBusService; beforeEach(async(() => { TestBed.configureTestingModule({ imports: [TestModule], providers: [ {provide: TabsService, useValue: tabsServiceSpy()} ] }) .compileComponents(); })); beforeEach(() => { eventBus = TestBed.get(EventBusService); fixture = TestBed.createComponent(TabsHeaderComponent); component = fixture.componentInstance; component.tabs = [ newTestTab(TestComponent), new Tab(new ComponentPortal(TestComponent), 'TestStart', new IconFa(faQuestionCircle), 'TEST', false, ['test'], TestComponent) ]; component.side = TabsSide.TOP; component.position = TabsPosition.START; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should init content on bus event', fakeAsync(() => { const content = new TabsContentComponent(null, eventBus); content.headerSide = TabsSide.TOP; content.headerPosition = TabsPosition.START; eventBus.publish(new TabsContentInitializedEvent(content)); tick(1); expect(component.content).toBe(content); })); it('should (un)select', inject([LocalStorageService, EventBusService], (storage: LocalStorageService, bus: EventBusService) => { const content = new TabsContentComponent(storage, bus); content.tabs = component.tabs; component.content = content; fixture.detectChanges(); fixture.nativeElement.querySelector('button').click(); expect(component.content.selectedTab).toBe(component.tabs[0]); fixture.nativeElement.querySelector('button').click(); expect(component.content.selectedTab).toBeNull(); expect(TestBed.get(WindowService).resizeNow).toHaveBeenCalled(); })); });
yegobox/kraken
frontend/projects/commons/src/lib/config/runtime-application-id.service.ts
<filename>frontend/projects/commons/src/lib/config/runtime-application-id.service.ts<gh_stars>0 import {Injectable} from '@angular/core'; import {ConfigurationService} from 'projects/commons/src/lib/config/configuration.service'; import {ApplicationIdHeaderInterceptor} from 'projects/commons/src/lib/config/application-id-header-interceptor.service'; @Injectable() export class RuntimeApplicationIdService extends ApplicationIdHeaderInterceptor { constructor(configuration: ConfigurationService) { super(configuration, () => [configuration.runtimeApiUrl]); } }
yegobox/kraken
frontend/projects/runtime/src/lib/runtime-host/host-id-to-description.pipe.ts
import {Pipe, PipeTransform} from '@angular/core'; import {RuntimeHostService} from 'projects/runtime/src/lib/runtime-host/runtime-host.service'; import {AddressesToStringPipe} from 'projects/runtime/src/lib/runtime-host/addresses-to-string.pipe'; import {CapacityToStringPipe} from 'projects/runtime/src/lib/runtime-host/capacity-to-string.pipe'; @Pipe({ name: 'hostIdToDescription' }) export class HostIdToDescriptionPipe implements PipeTransform { constructor(private hostService: RuntimeHostService, private addressesToStringPipe: AddressesToStringPipe, private capacityToStringPipe: CapacityToStringPipe) { } transform(id: string): string { const host = this.hostService.host(id); return host ? `Addresses: ${this.addressesToStringPipe.transform(host.addresses)} - Capacity: ${this.capacityToStringPipe.transform(host.capacity)}` : id; } }
yegobox/kraken
frontend/projects/dialog/src/lib/dialog.service.spec.ts
<filename>frontend/projects/dialog/src/lib/dialog.service.spec.ts import {TestBed} from '@angular/core/testing'; import {DialogService} from './dialog.service'; import { MatDialog } from '@angular/material/dialog'; import {Component} from '@angular/core'; import SpyObj = jasmine.SpyObj; import {InspectDialogComponent} from 'projects/dialog/src/lib/inspect-dialog/inspect-dialog.component'; import {DeleteDialogComponent} from 'projects/dialog/src/lib/delete-dialog/delete-dialog.component'; import {LogsDialogComponent} from 'projects/dialog/src/lib/logs-dialog/logs-dialog.component'; import {WaitDialogComponent} from 'projects/dialog/src/lib/wait-dialog/wait-dialog.component'; import {DialogSize} from 'projects/dialog/src/lib/dialog-size'; import {of} from 'rxjs'; import {ConfirmDialogComponent} from 'projects/dialog/src/lib/confirm-dialog/confirm-dialog.component'; export const dialogsServiceSpy = () => { const spy = jasmine.createSpyObj('DialogService', [ 'open', 'inspect', 'delete', 'confirm', 'logs', ]); return spy; }; @Component({ selector: 'lib-test', template: `test` }) class TestComponent { } describe('DialogService', () => { let service: DialogService; let dialog: SpyObj<MatDialog>; beforeEach(() => { TestBed.configureTestingModule({ providers: [ {provide: MatDialog, useValue: jasmine.createSpyObj('MatDialog', ['open'])}, DialogService ] }); service = TestBed.get(DialogService); dialog = TestBed.get(MatDialog); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should open/close dialog', () => { dialog.open.and.returnValue({ afterClosed: () => of('result') } as any); service.open(TestComponent, DialogSize.SIZE_MD, {key: 'value'}).subscribe((result) => expect(result).toBe('result')); expect(dialog.open).toHaveBeenCalledWith(TestComponent, { panelClass: DialogSize.SIZE_MD, data: {key: 'value'} }); }); it('should open/dismiss dialog', () => { dialog.open.and.returnValue({ afterClosed: () => of(undefined) } as any); service.open(TestComponent).subscribe(() => fail('should not call callback on dismiss')); expect(dialog.open).toHaveBeenCalledWith(TestComponent, { panelClass: DialogSize.SIZE_SM, data: undefined, }); }); it('should inspect', () => { service.inspect('name', '{}', 'TEST'); expect(dialog.open).toHaveBeenCalledWith(InspectDialogComponent, { panelClass: DialogSize.SIZE_LG, data: { object: '{}', name: 'name', helpPageId: 'TEST' } }); }); it('should logsComponents', () => { service.logs('title', 'logs'); expect(dialog.open).toHaveBeenCalledWith(LogsDialogComponent, { panelClass: DialogSize.SIZE_FULL, data: { title: 'title', logs: 'logs', } }); }); it('should delete', () => { const spy = spyOn(service, 'open'); service.delete('name', ['item'], 'TEST'); expect(spy).toHaveBeenCalledWith( DeleteDialogComponent, DialogSize.SIZE_MD, { name: 'name', items: ['item'], helpPageId: 'TEST' }); }); it('should confirm', () => { const spy = spyOn(service, 'open'); service.confirm('title', 'message'); expect(spy).toHaveBeenCalledWith( ConfirmDialogComponent, DialogSize.SIZE_MD, { title: 'title', message: 'message' }); }); it('should wait', () => { service.wait({title: 'title', progress: 50}); expect(dialog.open).toHaveBeenCalledWith(WaitDialogComponent, { panelClass: DialogSize.SIZE_MD, data: {title: 'title', progress: 50}, disableClose: true, }); }); });
yegobox/kraken
frontend/projects/gatling/src/app/simulations/simulation-dialogs/execute-simulation-dialog/execute-simulation-dialog.component.spec.ts
import {async, ComponentFixture, TestBed} from '@angular/core/testing'; import {ExecuteSimulationDialogComponent} from './execute-simulation-dialog.component'; import {VendorsModule} from 'projects/vendors/src/lib/vendors.module'; import {MAT_DIALOG_DATA, MatDialogRef} from '@angular/material/dialog'; import {dialogRefSpy} from 'projects/commons/src/lib/mock/material.mock.spec'; import {ExecutionContext} from 'projects/runtime/src/lib/entities/execution-context'; import SpyObj = jasmine.SpyObj; describe('ExecuteSimulationDialogComponent', () => { let component: ExecuteSimulationDialogComponent; let fixture: ComponentFixture<ExecuteSimulationDialogComponent>; let dialogRef: SpyObj<MatDialogRef<ExecuteSimulationDialogComponent>>; beforeEach(async(() => { dialogRef = dialogRefSpy(); TestBed.configureTestingModule({ imports: [VendorsModule], declarations: [ExecuteSimulationDialogComponent], providers: [ { provide: MAT_DIALOG_DATA, useValue: { simulationPackage: 'simulationPackage', simulationClass: 'simulationClass', type: 'RUN', atOnce: true, } }, {provide: MatDialogRef, useValue: dialogRef}, ] }) .overrideTemplate(ExecuteSimulationDialogComponent, '') .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(ExecuteSimulationDialogComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should return simulationName', () => { expect(component.simulationName.value).toBe('simulationPackage.simulationClass'); }); it('should run', () => { component.descriptionInput = { description: { value: 'description' } } as any; component.envVarList = { environment: {FOO: 'BAR'}, hosts: { 'local': {} } } as any; component.run(); expect(dialogRef.close).toHaveBeenCalledWith(new ExecutionContext( 'RUN', 'description', {FOO: 'BAR', KRAKEN_GATLING_SIMULATION: 'simulationPackage.simulationClass'}, { 'local': {} } )); }); });
yegobox/kraken
frontend/projects/analysis/src/lib/results/debug/compare/debug-entry-selector/debug-entry-selector.component.ts
import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core'; import {Result} from 'projects/analysis/src/lib/entities/result'; import {DebugEntry} from 'projects/analysis/src/lib/entities/debug-entry'; import * as _ from 'lodash'; @Component({ selector: 'lib-debug-entry-selector', templateUrl: './debug-entry-selector.component.html', styleUrls: ['./debug-entry-selector.component.scss'] }) export class DebugEntrySelectorComponent implements OnInit { @Input() results: Result[]; @Input() debugEntries: DebugEntry[]; @Input() debugEntryId: string; @Input() resultId: string; @Output() debugSelected: EventEmitter<DebugEntry> = new EventEmitter(); private _sortedEntries: DebugEntry[]; public entry: DebugEntry; public result: Result; ngOnInit() { this._sortedEntries = _.sortBy(this.debugEntries, 'date'); this.debugEntrySelected(this.resultId + ':' + this.debugEntryId); } filter(resultId: string): DebugEntry[] { return _.filter(this._sortedEntries, {resultId}); } debugEntrySelected(compositeId: string) { const ids = compositeId.split(':', 2); const resultId = ids[0]; const entryId = ids[1]; const entry1: DebugEntry = _.find(this._sortedEntries, {resultId: resultId, id: entryId}) as DebugEntry; this.result = _.find(this.results, {id: resultId}); this.debugSelected.emit(entry1); } }
yegobox/kraken
frontend/projects/storage/src/lib/storage-menu/menu-items/rename-menu-item/rename-menu-item.component.spec.ts
<filename>frontend/projects/storage/src/lib/storage-menu/menu-items/rename-menu-item/rename-menu-item.component.spec.ts import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { RenameMenuItemComponent } from './rename-menu-item.component'; import {NewFileMenuItemComponent} from 'projects/storage/src/lib/storage-menu/menu-items/new-file-menu-item/new-file-menu-item.component'; import {StorageService} from 'projects/storage/src/lib/storage.service'; import {storageServiceSpy} from 'projects/storage/src/lib/storage.service.spec'; import {StorageTreeControlService} from 'projects/storage/src/lib/storage-tree/storage-tree-control.service'; import {storageTreeControlServiceSpy} from 'projects/storage/src/lib/storage-tree/storage-tree-control.service.spec'; import {StorageTreeDataSourceService} from 'projects/storage/src/lib/storage-tree/storage-tree-data-source.service'; import {storageTreeDataSourceServiceSpy} from 'projects/storage/src/lib/storage-tree/storage-tree-data-source.service.spec'; describe('RenameMenuItemComponent', () => { let component: RenameMenuItemComponent; let fixture: ComponentFixture<RenameMenuItemComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [RenameMenuItemComponent], providers: [ {provide: StorageTreeDataSourceService, useValue: storageTreeDataSourceServiceSpy()}, {provide: StorageService, useValue: storageServiceSpy()}, {provide: StorageTreeControlService, useValue: storageTreeControlServiceSpy()}, ] }) .overrideTemplate(RenameMenuItemComponent, '') .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(RenameMenuItemComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
yegobox/kraken
frontend/projects/runtime/src/lib/runtime-task/tasks-table/tasks-table.component.ts
<reponame>yegobox/kraken<gh_stars>0 import {Component, OnDestroy, OnInit, ViewChild} from '@angular/core'; import {SelectionModel} from '@angular/cdk/collections'; import {Task} from 'projects/runtime/src/lib/entities/task'; import {REFRESH_ICON, STOP_ICON} from 'projects/icon/src/lib/icons'; import {MatTableDataSource} from '@angular/material/table'; import {MatSort} from '@angular/material/sort'; import {Subscription} from 'rxjs'; import {RuntimeTaskService} from 'projects/runtime/src/lib/runtime-task/runtime-task.service'; import {EventBusService} from 'projects/event/src/lib/event-bus.service'; import {TasksRefreshEvent} from 'projects/runtime/src/lib/events/tasks-refresh-event'; import {flatMap, map, tap} from 'rxjs/operators'; import {TaskSelectedEvent} from 'projects/runtime/src/lib/events/task-selected-event'; import * as _ from 'lodash'; import {TaskCancelledEvent} from 'projects/runtime/src/lib/events/task-cancelled-event'; import {DialogService} from 'projects/dialog/src/lib/dialog.service'; @Component({ selector: 'lib-tasks-table', templateUrl: './tasks-table.component.html', styleUrls: ['./tasks-table.component.scss'] }) export class TasksTableComponent implements OnInit, OnDestroy { readonly _selection: SelectionModel<Task> = new SelectionModel(false); private _subscriptions: Subscription[] = []; readonly refreshIcon = REFRESH_ICON; readonly stopIcon = STOP_ICON; readonly displayedColumns: string[] = [/*'id',*/ 'startDate', 'status', 'type', 'description', 'containers', 'buttons']; loading = true; dataSource: MatTableDataSource<Task>; @ViewChild(MatSort, {static: true}) sort: MatSort; constructor(private taskService: RuntimeTaskService, private eventBus: EventBusService, private dialogs: DialogService) { this._subscriptions.push(eventBus.of<TasksRefreshEvent>(TasksRefreshEvent.CHANNEL) .pipe(map(event => event.tasks)).subscribe(tasks => this.tasks = tasks)); this._subscriptions.push(this._selection.changed.subscribe(value => { this.eventBus.publish(new TaskSelectedEvent(this._selection.selected[0])); })); } ngOnInit() { this.refresh(); } ngOnDestroy() { _.invokeMap(this._subscriptions, 'unsubscribe'); } refresh() { this.loading = true; this.taskService.list().subscribe(); } public isSelected(task: Task): boolean { return this.hasSelection && this.selection.id === task.id; } public get hasSelection(): boolean { return this._selection.hasValue(); } public set selection(task: Task) { if (task) { this._selection.select(task); } else { this._selection.clear(); } } public get selection(): Task | null { return this.hasSelection ? this._selection.selected[0] : null; } public cancel(task: Task) { this.dialogs.confirm('Cancel Task', 'Are you sure you want to cancel this task execution?') .subscribe(() => this.taskService.cancel(task).subscribe()); } set tasks(tasks: Task[]) { const taskId = this.hasSelection ? this.selection.id : null; const first = _.first(_.filter(tasks, (task: Task) => task.status !== 'DONE')); const currentNotDone = _.find(tasks, (task: Task) => task.id === taskId && task.status !== 'DONE'); const current = _.find(tasks, {id: taskId}); this.selection = currentNotDone || first || current; this.dataSource = new MatTableDataSource(tasks); this.dataSource.sort = this.sort; this.loading = false; } }
yegobox/kraken
frontend/projects/analysis/src/lib/results/debug/headers-table/headers-table.component.spec.ts
import {async, ComponentFixture, TestBed} from '@angular/core/testing'; import {HeadersTableComponent} from 'projects/analysis/src/lib/results/debug/headers-table/headers-table.component'; describe('HeadersTableComponent', () => { let component: HeadersTableComponent; let fixture: ComponentFixture<HeadersTableComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [HeadersTableComponent] }) .overrideTemplate(HeadersTableComponent, '') .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(HeadersTableComponent); component = fixture.componentInstance; component.headers = [ {key: 'key1', value: 'value1'}, {key: 'key2', value: 'value2'}, ]; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should init dataSource', () => { expect(component.dataSource).toBeTruthy(); expect(component.dataSource.data).toBe(component.headers); }); });
yegobox/kraken
frontend/projects/editor/src/lib/code-editor/code-editor.component.spec.ts
<gh_stars>1-10 import {async, ComponentFixture, inject, TestBed} from '@angular/core/testing'; import * as _ from 'lodash'; import {CodeEditorComponent} from 'projects/editor/src/lib/code-editor/code-editor.component'; import {CodeService} from 'projects/editor/src/lib/code.service'; import {codeServiceSpy} from 'projects/editor/src/lib/code.service.spec'; import {EditorModule} from 'projects/editor/src/lib/editor.module'; import {ChangeDetectorRef, Input} from '@angular/core'; import SpyObj = jasmine.SpyObj; import {changeDetectorSpy} from 'projects/commons/src/lib/mock/angular.mock.spec'; import {VariablesAutoCompleter} from 'projects/editor/src/lib/variables-auto-completer'; describe('CodeEditorComponent', () => { let component: CodeEditorComponent; let fixture: ComponentFixture<CodeEditorComponent>; let codeService: CodeService; let changeDetector: SpyObj<ChangeDetectorRef>; beforeEach(async(() => { codeService = codeServiceSpy(); changeDetector = changeDetectorSpy(); TestBed .configureTestingModule({ imports: [EditorModule], providers: [ {provide: CodeService, useValue: codeService}, {provide: ChangeDetectorRef, useValue: changeDetector} ] }) .overrideComponent(CodeEditorComponent, { set: { providers: [ {provide: CodeService, useValue: codeService} ] } }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(CodeEditorComponent); component = fixture.componentInstance; component.variablesAutoCompleter = jasmine.createSpyObj('VariablesAutoCompleter', ['autoCompleteVariableNames']); fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should init editorComponent', inject([CodeService], (service: CodeService) => { component.ngAfterViewInit(); expect(service.initCodeEditorComponent).toHaveBeenCalledWith(component._editor, component.variablesAutoCompleter); })); it('should init editorComponent with tab size', inject([CodeService], (service: CodeService) => { component.tabsSize = 42; spyOn(component._editor.getSession(), 'setTabSize'); component.ngAfterViewInit(); expect(service.initCodeEditorComponent).toHaveBeenCalledWith(component._editor, component.variablesAutoCompleter); expect(component._editor.getSession().setTabSize).toHaveBeenCalledWith(42); })); it('should fire change event', () => { spyOn(component.contentChange, 'emit'); spyOn(component._onChange, 'emit'); spyOn(component._onTouched, 'emit'); component.writeValue('test'); expect(component.contentChange.emit).toHaveBeenCalledWith('test'); expect(component._onChange.emit).toHaveBeenCalledWith('test'); expect(component._onTouched.emit).toHaveBeenCalled(); }); it('should register change event', () => { spyOn(component._onChange, 'subscribe'); spyOn(component._onTouched, 'subscribe'); component.registerOnChange(_.noop); component.registerOnTouched(_.noop); expect(component._onChange.subscribe).toHaveBeenCalled(); expect(component._onTouched.subscribe).toHaveBeenCalled(); }); it('should set disabled state', () => { component.setDisabledState(true); expect(component._editor.getReadOnly()).toBe(true); }); it('should set mode', () => { const spy = spyOn(component._editor.getSession(), 'setMode'); component.mode = 'java'; expect(component._mode).toBe('java'); expect(spy).toHaveBeenCalledWith('ace/mode/java'); }); it('should set mode no editor', () => { const comp = new CodeEditorComponent(null, null, null); comp.mode = 'java'; expect(comp._mode).toBe('java'); }); it('should resize', () => { const spy = spyOn(component._editor, 'resize'); component.resize(); expect(spy).toHaveBeenCalledWith(true); }); it('should set and get value', () => { component.value = 'new value'; expect(component.value).toBe('new value'); }); it('should set value no editor', () => { const comp = new CodeEditorComponent(null, null, null); comp.value = 'new value'; expect(comp._value).toBe('new value'); }); it('should append text no editor', () => { const comp = new CodeEditorComponent(null, null, null); comp._value = 'foo'; comp.appendText('bar'); expect(comp._value).toBe('foobar'); }); it('should append text', () => { component.appendText('appended'); }); });
yegobox/kraken
frontend/projects/help/src/lib/help-anchor/help-anchor.component.spec.ts
<reponame>yegobox/kraken import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { HelpAnchorComponent } from './help-anchor.component'; describe('HelpAnchorComponent', () => { let component: HelpAnchorComponent; let fixture: ComponentFixture<HelpAnchorComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ HelpAnchorComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(HelpAnchorComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
yegobox/kraken
frontend/projects/gatling/src/app/simulations/run-simulation-menu-item/run-simulation-menu-item.component.spec.ts
<reponame>yegobox/kraken<filename>frontend/projects/gatling/src/app/simulations/run-simulation-menu-item/run-simulation-menu-item.component.spec.ts import {async, ComponentFixture, TestBed} from '@angular/core/testing'; import {RunSimulationMenuItemComponent} from './run-simulation-menu-item.component'; import {StorageTreeControlService} from 'projects/storage/src/lib/storage-tree/storage-tree-control.service'; import {storageTreeControlServiceSpy} from 'projects/storage/src/lib/storage-tree/storage-tree-control.service.spec'; import {SimulationService} from 'projects/gatling/src/app/simulations/simulation.service'; import {simulationServiceSpy} from 'projects/gatling/src/app/simulations/simulation.service.spec'; describe('RunSimulationMenuItemComponent', () => { let component: RunSimulationMenuItemComponent; let fixture: ComponentFixture<RunSimulationMenuItemComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [RunSimulationMenuItemComponent], providers: [ {provide: StorageTreeControlService, useValue: storageTreeControlServiceSpy()}, {provide: SimulationService, useValue: simulationServiceSpy()}, ] }) .overrideTemplate(RunSimulationMenuItemComponent, '') .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(RunSimulationMenuItemComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
yegobox/kraken
frontend/projects/storage/src/lib/storage-editor/storage-editor/storage-editor.component.ts
import {Component, Inject, InjectionToken, OnDestroy, Optional} from '@angular/core'; import {StorageNode} from 'projects/storage/src/lib/entities/storage-node'; import {LocalStorageService} from 'projects/tools/src/lib/local-storage.service'; import {StorageService} from 'projects/storage/src/lib/storage.service'; import {BehaviorSubject, Subscription} from 'rxjs'; import {EventBusService} from 'projects/event/src/lib/event-bus.service'; import {OpenNodeEvent} from 'projects/storage/src/lib/events/open-node-event'; import * as _ from 'lodash'; import {WindowService} from 'projects/tools/src/lib/window.service'; import {STORAGE_ID} from 'projects/storage/src/lib/storage-id'; import {SelectNodeEvent} from 'projects/storage/src/lib/events/select-node-event'; import {StorageEditorService} from 'projects/storage/src/lib/storage-editor/storage-editor.service'; import {ComponentPortal} from '@angular/cdk/portal'; import {StorageNodeEditor} from 'projects/storage/src/lib/storage-editor/storage-node-editors/storage-node-editor'; import {NodeDeletedEvent} from 'projects/storage/src/lib/events/node-deleted-event'; import {NodePendingSaveEvent} from 'projects/storage/src/lib/events/node-pending-save-event'; import {KeyBinding, KeyBindingsService} from 'projects/tools/src/lib/key-bindings.service'; import {SaveNodeEvent} from 'projects/storage/src/lib/events/save-node-event'; import {StorageNodeToPredicatePipe} from 'projects/storage/src/lib/storage-pipes/storage-node-to-predicate.pipe'; import {StorageConfigurationService} from 'projects/storage/src/lib/storage-configuration.service'; import {SelectHelpEvent} from 'projects/help/src/lib/help-panel/select-help-event'; export const STORAGE_EDITOR_README_NODE = new InjectionToken<StorageNode>('StorageEditorReadmeNode'); @Component({ selector: 'lib-storage-editor', templateUrl: './storage-editor.component.html', styleUrls: ['./storage-editor.component.scss'] }) export class StorageEditorComponent implements OnDestroy { public readonly selectedIndex: BehaviorSubject<number>; public readonly nodes: BehaviorSubject<StorageNode[]>; public editors: { [key in string]: ComponentPortal<StorageNodeEditor> } = {}; _saveKeyBinding: KeyBinding; private readonly indexId: string; private readonly nodesId: string; private pendingSaveMap: { [key in string]: boolean } = {}; // node.path => pendingSave state private subscriptions: Subscription[] = []; constructor(@Inject(STORAGE_ID) private id: string, @Inject(STORAGE_EDITOR_README_NODE) @Optional() readmeNode: StorageNode, private localStorage: LocalStorageService, private storage: StorageService, private eventBus: EventBusService, public windowService: WindowService, private editorService: StorageEditorService, private keys: KeyBindingsService, private toPredicate: StorageNodeToPredicatePipe, storageConfiguration: StorageConfigurationService) { // Init ids this.indexId = this.id + '-index'; this.nodesId = this.id + '-nodes'; // Bind _openNode to bus event this.subscriptions.push(this.eventBus.of(OpenNodeEvent.CHANNEL).subscribe(this._openNode.bind(this))); this.subscriptions.push(this.eventBus.of(NodeDeletedEvent.CHANNEL).subscribe(this._closeDeletedNode.bind(this))); this.subscriptions.push(this.eventBus.of(NodePendingSaveEvent.CHANNEL).subscribe(this._tagPendingSaveNode.bind(this))); this._saveKeyBinding = new KeyBinding('ctrl + s', () => { if (this.nodes.value.length) { this.eventBus.publish(new SaveNodeEvent(this.nodes.value[this.selectedIndex.value])); } return true; }, null, true, true, ['UNFOCUSED']); this.keys.add([this._saveKeyBinding]); const nodes = this.localStorage.getItem(this.nodesId, []); const selectedIndex = this.localStorage.getNumber(this.indexId, 0); // Init subjects with blank values this.selectedIndex = new BehaviorSubject<number>(0); this.nodes = new BehaviorSubject<StorageNode[]>([]); // Update local storage on subjects change this.selectedIndex.subscribe((index) => this.localStorage.set(this.indexId, index)); this.nodes.subscribe((_nodes) => this.localStorage.setItem(this.nodesId, _nodes)); // Filter existing nodes this.storage.filterExisting(nodes).subscribe((existingNodes: StorageNode[]) => { if (existingNodes.length === 0) { this.nodes.next([storageConfiguration.readmeNode]); this.selectedIndex.next(0); } else { this.nodes.next(existingNodes); this.selectedIndex.next(Math.max(existingNodes.length - 1, selectedIndex)); } }); } ngOnDestroy() { _.invokeMap(this.subscriptions, 'unsubscribe'); this.keys.remove([this._saveKeyBinding]); } public closeNode(index: number) { const nodes = this.nodes.value; nodes.splice(index, 1); this.nodes.next(nodes); if (this.selectedIndex.value === index) { this.selectIndex(Math.min(Math.max(index, 0), nodes.length - 1)); } } public selectIndex(index: number) { this.selectedIndex.next(index); const node = this.nodes.value[index]; if (node) { this.eventBus.publish(new SelectNodeEvent(node)); this.eventBus.publish(new SelectHelpEvent(this.editorService.getHelpPageId(node))); } } public getNodeEditor(node: StorageNode): ComponentPortal<StorageNodeEditor> { let editor = this.editors[node.path]; if (editor) { return editor; } editor = this.editorService.getNodeEditor(node); this.editors[node.path] = editor; return editor; } public isPendingSave(node: StorageNode): boolean { return this.pendingSaveMap[node.path]; } _tagPendingSaveNode(event: NodePendingSaveEvent) { this.pendingSaveMap[event.node.path] = event.pendingSave; } _openNode(event: OpenNodeEvent) { const node = event.node; const nodes = this.nodes.value; const index = _.findIndex(nodes, {path: node.path}); if (index !== -1) { this.selectedIndex.next(index); } else { nodes.push(node); this.nodes.next(nodes); this.selectedIndex.next(nodes.length - 1); } } _closeDeletedNode(event: NodeDeletedEvent) { const nodes = this.nodes.value; const predicate = this.toPredicate.transform(event.node); _.filter(nodes, predicate).forEach((node: StorageNode) => { const index = _.indexOf(nodes, node); this.closeNode(index); }); } closeOthers() { const nodes = this.nodes.value; this.nodes.next([nodes[this.selectedIndex.value]]); this.selectedIndex.next(0); } closeAll() { this.nodes.next([]); this.selectedIndex.next(-1); } }
yegobox/kraken
frontend/projects/storage/src/lib/storage-tree/storage-tree/storage-tree.component.spec.ts
<gh_stars>1-10 import {async, ComponentFixture, TestBed} from '@angular/core/testing'; import {STORAGE_CONTEXTUAL_MENU, StorageTreeComponent} from './storage-tree.component'; import {StorageTreeControlService} from 'projects/storage/src/lib/storage-tree/storage-tree-control.service'; import {StorageTreeDataSourceService} from 'projects/storage/src/lib/storage-tree/storage-tree-data-source.service'; import {storageTreeControlServiceSpy} from 'projects/storage/src/lib/storage-tree/storage-tree-control.service.spec'; import {storageTreeDataSourceServiceSpy} from 'projects/storage/src/lib/storage-tree/storage-tree-data-source.service.spec'; import {CopyPasteService} from 'projects/storage/src/lib/storage-tree/copy-paste.service'; import {copyPasteServiceSpy} from 'projects/storage/src/lib/storage-tree/copy-paste.service.spec'; import { testStorageDirectoryNode, testStorageFileNode, testStorageNodes } from 'projects/storage/src/lib/entities/storage-node.spec'; import {StorageNode} from 'projects/storage/src/lib/entities/storage-node'; import {StorageContextualMenuComponent} from 'projects/storage/src/lib/storage-menu/storage-contextual-menu/storage-contextual-menu.component'; import {STORAGE_ID} from 'projects/storage/src/lib/storage-id'; import {StorageListService} from 'projects/storage/src/lib/storage-list.service'; import {storageListServiceSpy} from 'projects/storage/src/lib/storage-list.service.spec'; import {StorageService} from 'projects/storage/src/lib/storage.service'; import {storageServiceSpy} from 'projects/storage/src/lib/storage.service.spec'; import {EventBusService} from 'projects/event/src/lib/event-bus.service'; import {eventBusSpy} from 'projects/event/src/lib/event-bus.service.spec'; import SpyObj = jasmine.SpyObj; import {SelectHelpEvent} from 'projects/help/src/lib/help-panel/select-help-event'; describe('StorageTreeComponent', () => { let component: StorageTreeComponent; let fixture: ComponentFixture<StorageTreeComponent>; let treeControl: StorageTreeControlService; let dataSource: StorageTreeDataSourceService; let eventBus: SpyObj<EventBusService>; let fileNode: StorageNode; let directoryNode: StorageNode; beforeEach(async(() => { treeControl = storageTreeControlServiceSpy(); dataSource = storageTreeDataSourceServiceSpy(); eventBus = eventBusSpy(); TestBed.configureTestingModule({ declarations: [StorageTreeComponent], providers: [ {provide: StorageService, useValue: storageServiceSpy()}, {provide: STORAGE_CONTEXTUAL_MENU, useValue: StorageContextualMenuComponent}, {provide: STORAGE_ID, useValue: 'storage'}, {provide: EventBusService, useValue: eventBus} ] }) .overrideProvider(StorageListService, {useValue: storageListServiceSpy()}) .overrideProvider(StorageTreeControlService, {useValue: treeControl}) .overrideProvider(StorageTreeDataSourceService, {useValue: dataSource}) .overrideProvider(CopyPasteService, {useValue: copyPasteServiceSpy()}) .overrideTemplate(StorageTreeComponent, '') .compileComponents(); fileNode = testStorageFileNode(); directoryNode = testStorageDirectoryNode(); })); beforeEach(() => { dataSource.data = testStorageNodes(); fixture = TestBed.createComponent(StorageTreeComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should return hasChild', () => { expect(component.hasChild(null, fileNode)).toBeFalsy(); expect(component.hasChild(null, directoryNode)).toBeTruthy(); }); it('should selectHelpPage', () => { component.selectHelpPage(); expect(eventBus.publish).toHaveBeenCalledWith(new SelectHelpEvent('storage' as any)); }); });
yegobox/kraken
frontend/projects/components/src/lib/header/header.component.ts
<reponame>yegobox/kraken import {Component} from '@angular/core'; import { faCaretRight, faCloudDownloadAlt, faCogs, faCreditCard, faHome, faSignOutAlt, faUserEdit, faUserShield } from '@fortawesome/free-solid-svg-icons'; import {library} from '@fortawesome/fontawesome-svg-core'; library.add(faCaretRight, faCogs, faCloudDownloadAlt, faCreditCard, faHome, faSignOutAlt, faUserEdit, faUserShield); @Component({ selector: 'lib-header', templateUrl: './header.component.html', styleUrls: ['./header.component.scss'] }) export class HeaderComponent { readonly projectsIcon = faHome; }
yegobox/kraken
frontend/projects/storage/src/lib/storage-editor/storage-node-editors/storage-node-editors.module.ts
import {NgModule} from '@angular/core'; import {CommonModule} from '@angular/common'; import {DefaultStorageNodeEditorComponent} from './default-storage-node-editor/default-storage-node-editor.component'; import {MarkdownStorageNodeEditorComponent} from './markdown-storage-node-editor/markdown-storage-node-editor.component'; import {EditorModule} from 'projects/editor/src/lib/editor.module'; import {StoragePipesModule} from 'projects/storage/src/lib/storage-pipes/storage-pipes.module'; import {ComponentsModule} from 'projects/components/src/lib/components.module'; import {ToolsModule} from 'projects/tools/src/lib/tools.module'; import {VendorsModule} from 'projects/vendors/src/lib/vendors.module'; import { EditorMessagesComponent } from './editor-messages/editor-messages.component'; @NgModule({ declarations: [ DefaultStorageNodeEditorComponent, MarkdownStorageNodeEditorComponent, EditorMessagesComponent, ], imports: [ CommonModule, EditorModule, StoragePipesModule, ComponentsModule, ToolsModule, VendorsModule, ], entryComponents: [ DefaultStorageNodeEditorComponent, MarkdownStorageNodeEditorComponent, ], exports: [ EditorMessagesComponent, ] }) export class StorageNodeEditorsModule { }
yegobox/kraken
frontend/projects/commons/src/lib/config/configuration.service.spec.ts
import {TestBed} from '@angular/core/testing'; import {ConfigurationService, loadConfiguration} from './configuration.service'; import {HttpClientTestingModule, HttpTestingController} from '@angular/common/http/testing'; import {HttpClient} from '@angular/common/http'; import {fail} from 'assert'; import {Configuration} from './configuration'; import {ENVIRONMENT} from 'projects/commons/src/lib/config/configuration-environment'; import SpyObj = jasmine.SpyObj; export const configurationServiceMock = (): ConfigurationService => { return new ConfigurationService(null, null); }; export const configurationServiceSpy = (): SpyObj<ConfigurationService> => { return jasmine.createSpyObj('ConfigurationService', ['url', 'value']); }; describe('ConfigurationService', () => { let httpClient: HttpClient; let httpTestingController: HttpTestingController; let service: ConfigurationService; beforeEach(() => { TestBed.configureTestingModule({ imports: [HttpClientTestingModule], providers: [ ConfigurationService, { provide: ENVIRONMENT, // you can also use InjectionToken useValue: {configUrl: 'assets/config.json'} }, ] }); httpClient = TestBed.get(HttpClient); httpTestingController = TestBed.get(HttpTestingController); service = TestBed.get(ConfigurationService); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should load config', () => { const testConf: Configuration = { version: 'version', applicationId: 'application', runtimeApiUrl: 'runtimeApiUrl', storageApiUrl: 'storageApiUrl', docUrl: 'docUrl' }; service.load().then(config => expect(config).toBeDefined(), () => fail('load failed')); const req = httpTestingController.expectOne('assets/config.json'); expect(req.request.method).toEqual('GET'); req.flush(testConf); expect(service._config.value).toEqual(testConf); }); it('should loadConfiguration hook', () => { const configService = configurationServiceMock(); spyOn(configService, 'load'); loadConfiguration(configService)(); expect(configService.load).toHaveBeenCalled(); }); it('should return applicationId', () => { expect(service.applicationId).toBe('application'); }); it('should return runtime API URL', () => { expect(service.runtimeApiUrl).toBe('runtimeApiUrl'); }); it('should return value', () => { expect(service.value('docUrl')).toBe('docUrl'); }); it('should return storage API URL', () => { expect(service.storageApiUrl).toBe('storageApiUrl'); }); it('should return runtime API URL', () => { expect(service.runtimeApiUrl).toBe('runtimeApiUrl'); }); it('should return Doc URL', () => { expect(service.docUrl('/path')).toBe('docUrl/path'); }); it('should return version', () => { expect(service.version('key')).toBe('version_key'); }); });
yegobox/kraken
frontend/projects/help/src/lib/help-panel/help.service.spec.ts
<gh_stars>1-10 import {TestBed, inject} from '@angular/core/testing'; import {HelpService} from 'projects/help/src/lib/help-panel/help.service'; import {EventBusService} from 'projects/event/src/lib/event-bus.service'; import {OpenHelpEvent} from 'projects/help/src/lib/help-panel/open-help-event'; import {SelectHelpEvent} from 'projects/help/src/lib/help-panel/select-help-event'; describe('HelpService', () => { beforeEach(() => { TestBed.configureTestingModule({ providers: [HelpService, EventBusService] }); }); it('should be created', inject([HelpService], (service: HelpService) => { expect(service).toBeTruthy(); expect(service.lastPage.getValue()).toBe('HOME'); service.ngOnDestroy(); })); it('should store last pageId', inject([HelpService, EventBusService], (service: HelpService, eventBus: EventBusService) => { eventBus.publish(new OpenHelpEvent('TEST')); expect(service.lastPage.getValue()).toBe('TEST'); eventBus.publish(new SelectHelpEvent('HOME')); expect(service.lastPage.getValue()).toBe('HOME'); })); });
yegobox/kraken
frontend/projects/storage/src/lib/storage-dialogs/delete-files-dialog/delete-files-dialog.component.ts
<reponame>yegobox/kraken import {Component, Inject, OnInit} from '@angular/core'; import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog'; import * as _ from 'lodash'; import {StorageNode} from 'projects/storage/src/lib/entities/storage-node'; export interface DeleteFilesDialogData { nodes: StorageNode[]; } @Component({ selector: 'lib-delete-files-dialog', templateUrl: './delete-files-dialog.component.html', styleUrls: ['./delete-files-dialog.component.scss'], }) export class DeleteFilesDialogComponent implements OnInit { public filesCount: number; public directoriesCount: number; constructor(public dialogRef: MatDialogRef<DeleteFilesDialogComponent>, @Inject(MAT_DIALOG_DATA) public data: DeleteFilesDialogData) { } ngOnInit() { this.directoriesCount = _.filter(this.data.nodes, (node: StorageNode) => node.type === 'DIRECTORY').length; this.filesCount = this.data.nodes.length - this.directoriesCount; } }
yegobox/kraken
frontend/projects/runtime/src/lib/runtime-host/environment-variables-list/environment-variables-list.component.ts
import {Component, ElementRef, Input, OnInit, QueryList, ViewChildren} from '@angular/core'; import {FormArray, FormBuilder, FormGroup, Validators} from '@angular/forms'; import {ADD_ICON, DELETE_ICON} from 'projects/icon/src/lib/icons'; import {LocalStorageService} from 'projects/tools/src/lib/local-storage.service'; import * as _ from 'lodash'; interface FlatVariable { key: string; value: string; scope: string; } @Component({ selector: 'lib-environment-variables-list', templateUrl: './environment-variables-list.component.html', styleUrls: ['./environment-variables-list.component.scss'] }) export class EnvironmentVariablesListComponent implements OnInit { private static readonly ID_PREFIX = 'environment-variables-list-'; readonly addVariableIcon = ADD_ICON; readonly removeVariableIcon = DELETE_ICON; @Input() formGroup: FormGroup; @Input() hostIds: string[]; @Input() storageId: string; envExpanded = false; @ViewChildren('key') envKeyChildren: QueryList<ElementRef>; constructor(private fb: FormBuilder, private localStorage: LocalStorageService) { } ngOnInit(): void { this.formGroup.addControl('variables', this.fb.array([])); const variables = this.variables; const flatVariables = this.localStorage.getItem<FlatVariable[]>(EnvironmentVariablesListComponent.ID_PREFIX + this.storageId, []); _.forEach(flatVariables, item => { variables.push(this.newVariableFormGroup(item.key, item.value, item.scope)); }); this.envExpanded = flatVariables.length > 0; } get variables(): FormArray { return this.formGroup.get('variables') as FormArray; } addVariableIfEmpty() { if (!this.variables.controls.length) { this.addVariable(); } } addVariable() { this.variables.push(this.newVariableFormGroup()); this.focusOnVariable(); } focusOnVariable() { setTimeout(() => { this.envKeyChildren.last.nativeElement.focus(); }, 100); } removeVariable(i: number) { this.variables.removeAt(i); } getKey(i: number) { return this.variables.controls[i].get('key'); } getValue(i: number) { return this.variables.controls[i].get('value'); } get environment(): { [key in string]: string } { const flatVariables = this.flatVariables; this.saveFlatVariables(flatVariables); const global = _.filter(flatVariables, variable => !variable.scope); return this.flatVariablesToObject(global); } get hosts(): { [hostId in string]: { [key in string]: string } } { const flatVariables = this.flatVariables; this.saveFlatVariables(flatVariables); const hosts = {}; _.forEach(this.hostIds, hostId => { const currentVariables = _.filter(flatVariables, variable => variable.scope === hostId); hosts[hostId] = this.flatVariablesToObject(currentVariables); }); return hosts; } private newVariableFormGroup(key = '', value = '', scope = '') { return this.fb.group( { key: [key, [Validators.required, Validators.pattern(/^\w+$/)]], value: [value, [Validators.required, Validators.pattern(/^\w+$/)]], scope: [scope, []], }); } private get flatVariables(): FlatVariable[] { const variables = this.variables; return variables.controls.map(control => { return { key: control.get('key').value, value: control.get('value').value, scope: control.get('scope').value, }; }); } private saveFlatVariables(flatVariables: FlatVariable[]) { this.localStorage.setItem(EnvironmentVariablesListComponent.ID_PREFIX + this.storageId, flatVariables); } private flatVariablesToObject(flatVariables: FlatVariable[]): { [key in string]: string } { return _.chain(flatVariables) .keyBy('key') .mapValues('value') .value(); } }
yegobox/kraken
frontend/projects/storage/src/lib/storage-editor/storage-node-editors/storage-node-editor-content.service.spec.ts
<filename>frontend/projects/storage/src/lib/storage-editor/storage-node-editors/storage-node-editor-content.service.spec.ts import {fakeAsync, TestBed, tick} from '@angular/core/testing'; import {StorageNodeEditorContentService} from './storage-node-editor-content.service'; import {EventEmitter} from '@angular/core'; import {CoreTestModule} from 'projects/commons/src/lib/core/core.module.spec'; import {HttpTestingController} from '@angular/common/http/testing'; import {EventBusService} from 'projects/event/src/lib/event-bus.service'; import {NodePendingSaveEvent} from 'projects/storage/src/lib/events/node-pending-save-event'; import {NodeModifiedEvent} from 'projects/storage/src/lib/events/node-modified-event'; import * as _ from 'lodash'; import {SaveNodeEvent} from 'projects/storage/src/lib/events/save-node-event'; import Spy = jasmine.Spy; import {testStorageDirectoryNode, testStorageFileNode} from 'projects/storage/src/lib/entities/storage-node.spec'; import {StorageService} from 'projects/storage/src/lib/storage.service'; import {storageServiceSpy} from 'projects/storage/src/lib/storage.service.spec'; import SpyObj = jasmine.SpyObj; import {of, throwError} from 'rxjs'; import {StorageConfigurationService} from 'projects/storage/src/lib/storage-configuration.service'; import {storageConfigurationServiceSpy} from 'projects/storage/src/lib/storage-configuration.service.spec'; export const storageNodeEditorContentServiceSpy = () => { const spy = jasmine.createSpyObj('StorageNodeEditorContentService', [ 'load', 'ngOnDestroy', ]); spy.contentChanged = new EventEmitter<string>(); spy.content = ''; return spy; }; describe('StorageNodeEditorContentService', () => { let service: StorageNodeEditorContentService; let httpTestingController: HttpTestingController; let eventBus: EventBusService; let publish: Spy; let storage: SpyObj<StorageService>; beforeEach(() => { TestBed.configureTestingModule({ imports: [CoreTestModule], providers: [ {provide: StorageConfigurationService, useValue: storageConfigurationServiceSpy()}, {provide: StorageService, useValue: storageServiceSpy()}, StorageNodeEditorContentService, ] }); service = TestBed.get(StorageNodeEditorContentService); storage = TestBed.get(StorageService); httpTestingController = TestBed.get(HttpTestingController); eventBus = TestBed.get(EventBusService); publish = spyOn(eventBus, 'publish'); publish.and.callThrough(); }); it('should be created', () => { expect(service).toBeTruthy(); service.ngOnDestroy(); }); it('should set and get content', () => { service.content = 'content'; expect(service.content).toBe('content'); }); it('should load node', () => { const node = testStorageFileNode(); storage.getContent.and.returnValue(of('content')); service.load(node); expect(service.state).toBe('loaded'); expect(service.content).toBe('content'); }); it('should fail to load node', () => { const node = testStorageFileNode(); storage.getContent.and.returnValue(throwError('error')); service.load(node); expect(service.state).toBe('error'); }); it('should save', () => { const fileNode = testStorageFileNode(); const directoryNode = testStorageDirectoryNode(); service._contentSubject.next('content'); service._node = fileNode; service.save(); const req = httpTestingController.expectOne(request => request.url === 'storageApiUrl/files/set/content'); expect(req.request.method).toBe('POST'); expect(req.request.params.get('path')).toEqual(fileNode.path); expect(req.request.body).toEqual('content'); req.flush(directoryNode); httpTestingController.verify(); expect(service._node).toBe(directoryNode); expect(publish).toHaveBeenCalledWith(new NodePendingSaveEvent(directoryNode, false)); }); it('should handle _nodeModified', () => { const fileNode = testStorageFileNode(); service._node = fileNode; service._nodeModified(new NodeModifiedEvent(fileNode)); const req = httpTestingController.expectOne(request => request.url === 'storageApiUrl/files/get/content'); expect(req.request.method).toBe('GET'); expect(req.request.params.get('path')).toEqual(fileNode.path); req.flush('content'); httpTestingController.verify(); expect(service.content).toBe('content'); }); it('should filter NodeModifiedEvent (other file)', fakeAsync(() => { service._node = testStorageDirectoryNode(); eventBus.publish(new NodeModifiedEvent(testStorageFileNode())); tick(StorageNodeEditorContentService.DEBOUNCE_DELAY); httpTestingController.verify(); })); it('should filter NodeModifiedEvent (same lastModified)', fakeAsync(() => { const node = testStorageFileNode(); service._node = node; eventBus.publish(new NodeModifiedEvent(node)); tick(StorageNodeEditorContentService.DEBOUNCE_DELAY); httpTestingController.verify(); })); it('should not filter NodeModifiedEvent', fakeAsync(() => { service._node = testStorageFileNode(); eventBus.publish(new NodeModifiedEvent(_.assign(testStorageFileNode(), {lastModified: 99999}))); tick(StorageNodeEditorContentService.DEBOUNCE_DELAY); const req = httpTestingController.expectOne(request => request.url === 'storageApiUrl/files/get/content'); expect(req.request.method).toBe('GET'); req.flush('content'); httpTestingController.verify(); })); it('should filter SaveNodeEvent (no node)', () => { eventBus.publish(new SaveNodeEvent(testStorageFileNode())); httpTestingController.verify(); }); it('should filter SaveNodeEvent (other node)', () => { service._node = testStorageDirectoryNode(); eventBus.publish(new SaveNodeEvent(testStorageFileNode())); httpTestingController.verify(); }); it('should not filter SaveNodeEvent', () => { const node = testStorageFileNode(); service._node = node; eventBus.publish(new SaveNodeEvent(node)); const req = httpTestingController.expectOne(request => request.url === 'storageApiUrl/files/set/content'); expect(req.request.method).toBe('POST'); req.flush(node); httpTestingController.verify(); }); it('should filter content next (no node)', fakeAsync(() => { service._contentSubject.next('content'); tick(StorageNodeEditorContentService.DEBOUNCE_DELAY); httpTestingController.verify(); })); it('should filter content next (null content)', fakeAsync(() => { service._node = testStorageFileNode(); service._contentSubject.next(null); tick(StorageNodeEditorContentService.DEBOUNCE_DELAY); httpTestingController.verify(); })); it('should not filter content next', fakeAsync(() => { const node = testStorageFileNode(); service._node = node; service._contentSubject.next('content'); tick(StorageNodeEditorContentService.DEBOUNCE_DELAY); expect(eventBus.publish).toHaveBeenCalledWith(new NodePendingSaveEvent(node, true)); const req = httpTestingController.expectOne(request => request.url === 'storageApiUrl/files/set/content'); expect(req.request.method).toBe('POST'); req.flush(node); httpTestingController.verify(); })); });
yegobox/kraken
frontend/projects/runtime/src/lib/runtime-host/capacity-to-string.pipe.ts
import {Pipe, PipeTransform} from '@angular/core'; import * as _ from 'lodash'; @Pipe({ name: 'capacityToString' }) export class CapacityToStringPipe implements PipeTransform { transform(capacity: { [key in string]: string }): string { return _.keys(capacity).map(key => `${key}=${capacity[key]}`).join(', '); } }
yegobox/kraken
frontend/projects/gatling/src/app/simulations/simulation-editor/completion/gatling-variables-auto-completer.spec.ts
<filename>frontend/projects/gatling/src/app/simulations/simulation-editor/completion/gatling-variables-auto-completer.spec.ts import {Component, ElementRef, Input, OnInit} from '@angular/core'; import {Ace, edit} from 'ace-builds'; import {async, ComponentFixture, TestBed} from '@angular/core/testing'; import {GatlingVariablesAutoCompleter} from 'projects/gatling/src/app/simulations/simulation-editor/completion/gatling-variables-auto-completer'; import {VendorsModule} from 'projects/vendors/src/lib/vendors.module'; import {CompletionCallback} from 'projects/editor/src/lib/completion-callback'; import {CompletionCommandResult} from 'projects/gatling/src/app/simulations/simulation-editor/completion/completion-command-result'; import * as _ from 'lodash'; @Component({ selector: 'app-test', template: '' }) class TestComponent implements OnInit { public editor: Ace.Editor; @Input() value: string; constructor(private elRef: ElementRef) { } ngOnInit() { this.editor = edit(this.elRef.nativeElement, { value: this.value, } as any); } } describe('GatlingVariablesAutoCompleter', () => { let component: TestComponent; let fixture: ComponentFixture<TestComponent>; let completer: GatlingVariablesAutoCompleter; let callback: CompletionCallback; let results: CompletionCommandResult[] = []; beforeEach(async(() => { TestBed .configureTestingModule({ imports: [VendorsModule], declarations: [ TestComponent, ], providers: [ GatlingVariablesAutoCompleter ] }) .compileComponents(); callback = (error: string | null, _results: { name: string, value: string, score: number, meta: string }[]) => { results = _results as any; }; completer = TestBed.get(GatlingVariablesAutoCompleter); })); beforeEach(() => { fixture = TestBed.createComponent(TestComponent); component = fixture.componentInstance; component.value = `/* * Copyright 2011-2019 GatlingCorp (https://gatling.io) */ package computerdatabase import io.gatling.core.Predef._ import io.gatling.http.Predef._ import scala.concurrent.duration._ class BasicSimulation extends Simulation { val httpProtocol = http .baseUrl("http://computer-database.gatling.io") // Here is the root for all relative URLs .acceptHeader("text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8") // Here are the common headers .doNotTrackHeader("1") .acceptLanguageHeader("en-US,en;q=0.5") .acceptEncodingHeader("gzip, deflate") .userAgentHeader("Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:16.0) Gecko/20100101 Firefox/16.0") val headers_10 = Map("Content-Type" -> "application/x-www-form-urlencoded") // Note the headers specific to a given request val scn = scenario("Scenario Name") // A scenario is a chain of requests and pauses .exec(http("request_1") .get("/")) .pause(7) // Note that Gatling has recorded real time pauses .exec(http("request_2") .get("/computers?f=macbook")) .pause(2) .exec(http("request_3") .get("/computers/6")) .pause(3) .exec(http("request_4") .get("/")) .pause(2) .exec(http("request_5") .get("/computers?p=1")) .pause(670 milliseconds) .exec(http("request_6") .get("/computers?p=2")) .pause(629 milliseconds) .exec(http("request_7") .get("/computers?p=3")) .pause(734 milliseconds) .exec(http("request_8") .get("/computers?p=4")) .pause(5) .exec(http("request_9") .get("/computers/new")) .pause(1) .exec(http("request_10") // Here's an example of a POST request .post("/computers") .headers(headers_10) .formParam("name", "<NAME>") .formParam("introduced", "2012-05-30") .formParam("discontinued", "") .formParam("company", "37")) setUp(scn.inject(atOnceUsers(1)).protocols(httpProtocol)) }`; fixture.detectChanges(); }); it('should call callback with Scenario completion', () => { completer.autoCompleteVariableNames(component.editor, component.editor.session, {row: 0, column: 0}, '', callback); const result = _.find(results, {name: 'scenario'}); expect(result).toBeDefined(); (result as any).completer.insertMatch(component.editor, result); expect(component.editor.session.getLine(0)).toEqual('scenario(name)/*'); }); it('should call callback with http completion', () => { completer.autoCompleteVariableNames(component.editor, component.editor.session, {row: 23, column: 12}, '', callback); const result = _.find(results, {command: 'http(name)'}); expect(result).toBeDefined(); component.editor.gotoLine(24, 12, false); (result as any).completer.insertMatch(component.editor, result); expect(component.editor.session.getLine(23)).toEqual(' .exec(http(name)tp("request_1")'); }); it('should call callback with exec completion', () => { completer.autoCompleteVariableNames(component.editor, component.editor.session, {row: 25, column: 5}, '', callback); const result = _.find(results, {name: 'exec'}); expect(result).toBeDefined(); component.editor.gotoLine(26, 5, false); (result as any).completer.insertMatch(component.editor, result); expect(component.editor.session.getLine(25)).toEqual(' .exec()pause(7) // Note that Gatling has recorded real time pauses'); }); });
yegobox/kraken
frontend/projects/storage/src/lib/storage-menu/menu-items/paste-menu-item/paste-menu-item.component.spec.ts
<reponame>yegobox/kraken<filename>frontend/projects/storage/src/lib/storage-menu/menu-items/paste-menu-item/paste-menu-item.component.spec.ts import {async, ComponentFixture, TestBed} from '@angular/core/testing'; import {PasteMenuItemComponent} from './paste-menu-item.component'; import {StorageTreeControlService} from 'projects/storage/src/lib/storage-tree/storage-tree-control.service'; import {storageTreeControlServiceSpy} from 'projects/storage/src/lib/storage-tree/storage-tree-control.service.spec'; import {CopyPasteService} from 'projects/storage/src/lib/storage-tree/copy-paste.service'; import {copyPasteServiceSpy} from 'projects/storage/src/lib/storage-tree/copy-paste.service.spec'; import {StorageNode} from 'projects/storage/src/lib/entities/storage-node'; import {testStorageDirectoryNode} from 'projects/storage/src/lib/entities/storage-node.spec'; import SpyObj = jasmine.SpyObj; import {STORAGE_ID} from 'projects/storage/src/lib/storage-id'; describe('PasteMenuItemComponent', () => { let component: PasteMenuItemComponent; let fixture: ComponentFixture<PasteMenuItemComponent>; let directoryNode: StorageNode; let treeControl: SpyObj<StorageTreeControlService>; let copyPaste: SpyObj<CopyPasteService>; beforeEach(async(() => { treeControl = storageTreeControlServiceSpy(); copyPaste = copyPasteServiceSpy(); directoryNode = testStorageDirectoryNode(); TestBed.configureTestingModule({ declarations: [PasteMenuItemComponent], providers: [ {provide: StorageTreeControlService, useValue: treeControl}, {provide: CopyPasteService, useValue: copyPaste}, {provide: STORAGE_ID, useValue: 'storage'}, ] }) .overrideTemplate(PasteMenuItemComponent, '') .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(PasteMenuItemComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should paste key binding multi file _selection', () => { const ctrl = component.treeControl as any; ctrl.hasSingleOrNoSelection = true; ctrl.selectedDirectory = directoryNode; const binding = component.binding; expect(binding.key).toBe('ctrl + v'); expect(binding.binding(null)).toBe(true); expect(copyPaste.paste).toHaveBeenCalledWith(directoryNode); }); it('should paste key no selection', () => { const ctrl = component.treeControl as any; ctrl.hasSingleOrNoSelection = false; const binding = component.binding; expect(binding.key).toBe('ctrl + v'); expect(binding.binding(null)).toBe(false); expect(copyPaste.paste).not.toHaveBeenCalled(); }); });
yegobox/kraken
frontend/projects/tools/src/lib/query-params-to-string.pipe.spec.ts
import { QueryParamsToStringPipe } from './query-params-to-string.pipe'; describe('QueryParamsToStringPipe', () => { it('create an instance', () => { const pipe = new QueryParamsToStringPipe(); expect(pipe).toBeTruthy(); expect(pipe.transform()).toBe(''); expect(pipe.transform({})).toBe(''); expect(pipe.transform({key: 'value'})).toBe('?key=value'); expect(pipe.transform({key1: 'value1', key2: 'value2'})).toBe('?key1=value1&key2=value2'); }); });
yegobox/kraken
frontend/projects/storage/src/lib/storage-tree/storage-tree-control.service.spec.ts
<filename>frontend/projects/storage/src/lib/storage-tree/storage-tree-control.service.spec.ts import {TestBed} from '@angular/core/testing'; import {StorageTreeControlService} from './storage-tree-control.service'; import {SelectionModel} from '@angular/cdk/collections'; import {EventBusService} from 'projects/event/src/lib/event-bus.service'; import {eventBusSpy} from 'projects/event/src/lib/event-bus.service.spec'; import {eventSpy} from 'projects/commons/src/lib/mock/event.mock.spec'; import { STORAGE_ROOT_NODE, StorageTreeDataSourceService } from 'projects/storage/src/lib/storage-tree/storage-tree-data-source.service'; import {storageTreeDataSourceServiceSpy} from 'projects/storage/src/lib/storage-tree/storage-tree-data-source.service.spec'; import {StorageNode} from 'projects/storage/src/lib/entities/storage-node'; import {OpenNodeEvent} from 'projects/storage/src/lib/events/open-node-event'; import {NodeDeletedEvent} from 'projects/storage/src/lib/events/node-deleted-event'; import {STORAGE_ID} from 'projects/storage/src/lib/storage-id'; import {LocalStorageService} from 'projects/tools/src/lib/local-storage.service'; import {localStorageServiceSpy} from 'projects/tools/src/lib/local-storage.service.spec'; import * as _ from 'lodash'; import { testStorageDirectoryNode, testStorageFileNode, testStorageNodes, testStorageRootNode } from 'projects/storage/src/lib/entities/storage-node.spec'; import SpyObj = jasmine.SpyObj; import Spy = jasmine.Spy; import {StorageNodeToPredicatePipe} from 'projects/storage/src/lib/storage-pipes/storage-node-to-predicate.pipe'; import {StorageListService} from 'projects/storage/src/lib/storage-list.service'; import {storageListServiceSpy} from 'projects/storage/src/lib/storage-list.service.spec'; export const storageTreeControlServiceSpy = () => { const spy = jasmine.createSpyObj('StorageTreeControlService', [ 'nodeClick', 'nodeDoubleClick', 'nodeContextMenu', 'clearSelection', 'clearExpansion', 'isSelected', 'isExpanded', 'selectOne', 'loadExpansion', 'ngOnDestroy', ]); spy.expansionModel = new SelectionModel<StorageNode>(); return spy; }; describe('StorageTreeControlService', () => { let service: StorageTreeControlService; let selection: SpyObj<SelectionModel<StorageNode>>; let eventBus: EventBusService; let dataSource: StorageTreeDataSourceService; let localStorage: LocalStorageService; let fileNode: StorageNode; let rootNode: StorageNode; let directoryNode: StorageNode; let storageNodes: StorageNode[]; beforeEach(() => { selection = jasmine.createSpyObj('_selection', ['clear', 'select', 'toggle', 'isSelected', 'hasValue']); rootNode = testStorageRootNode(); TestBed.configureTestingModule({ providers: [ {provide: EventBusService, useValue: eventBusSpy()}, {provide: StorageTreeDataSourceService, useValue: storageTreeDataSourceServiceSpy()}, {provide: StorageListService, useValue: storageListServiceSpy()}, {provide: LocalStorageService, useValue: localStorageServiceSpy()}, {provide: STORAGE_ID, useValue: 'test'}, {provide: STORAGE_ROOT_NODE, useValue: rootNode}, StorageTreeControlService, StorageNodeToPredicatePipe, ] }); eventBus = TestBed.get(EventBusService); dataSource = TestBed.get(StorageTreeDataSourceService); localStorage = TestBed.get(LocalStorageService); service = TestBed.get(StorageTreeControlService); service._selection = selection as any; fileNode = testStorageFileNode(); directoryNode = testStorageDirectoryNode(); storageNodes = testStorageNodes(); }); afterEach(() => { service.ngOnDestroy(); }); it('should be created', () => { expect(service).toBeTruthy(); service.ngOnDestroy(); }); it('should toggle _selection no key', () => { spyOn(service, 'selectOne'); service._toggleSelection({ctrlKey: false, shiftKey: false} as any, directoryNode); expect(service.selectOne).toHaveBeenCalledWith(directoryNode); }); it('should toggle _selection shift key no last _selection', () => { spyOn(service, 'selectOne'); service._toggleSelection({ctrlKey: false, shiftKey: true} as any, directoryNode); expect(service.selectOne).toHaveBeenCalledWith(directoryNode); }); it('should toggle _selection ctrl key', () => { (selection as any).selected = [directoryNode]; service._toggleSelection({ctrlKey: true, shiftKey: false} as any, directoryNode); expect(selection.toggle).toHaveBeenCalledWith(directoryNode); expect(service._lastSelection).toBe(directoryNode); }); it('should toggle _selection shift key', () => { service._lastSelection = directoryNode; const nodes: StorageNode[] = [ directoryNode, { path: 'root/path/file1.css', type: 'FILE', depth: 2, length: 42, lastModified: 1337 }, { path: 'root/path/file2.css', type: 'FILE', depth: 2, length: 42, lastModified: 1337 }, ]; dataSource.data = nodes; service._toggleSelection({ctrlKey: false, shiftKey: true} as any, nodes[2]); expect(selection.clear).toHaveBeenCalled(); expect(selection.select).toHaveBeenCalledTimes(3); expect(service._lastSelection).toBe(directoryNode); }); it('should handle tree click', () => { service.clearSelection(); expect(selection.clear).toHaveBeenCalled(); expect(service._lastSelection).toBeNull(); }); it('should return is selected', () => { (selection as any).selected = [directoryNode]; expect(service.isSelected(directoryNode)).toBe(true); expect(service.isSelected(fileNode)).toBe(false); expect(service.isSelected(undefined)).toBe(false); }); it('should handle double click on file', () => { const node = fileNode; const event = eventSpy(); selection.isSelected.and.returnValue(true); service.nodeDoubleClick(event, node); expect(event.stopPropagation).toHaveBeenCalled(); expect(eventBus.publish).toHaveBeenCalledWith(new OpenNodeEvent(node)); }); it('should handle double click on directory', () => { const node = directoryNode; const event = eventSpy(); spyOn(service, 'toggle'); selection.isSelected.and.returnValue(true); service.nodeDoubleClick(event, node); expect(event.stopPropagation).toHaveBeenCalled(); expect(service.toggle).toHaveBeenCalledWith(node); }); it('should handle click toggle _selection', () => { const node = directoryNode; const event = eventSpy(); spyOn(service, '_toggleSelection'); service.nodeClick(event, node); expect(event.stopPropagation).toHaveBeenCalled(); expect(service._toggleSelection).toHaveBeenCalledWith(event, node); }); it('should handle context menu', () => { service._lastSelection = directoryNode; const node = fileNode; const event = eventSpy(); (selection.isSelected).and.returnValue(false); service.nodeContextMenu(event, node); expect(event.stopPropagation).toHaveBeenCalled(); expect(selection.clear).toHaveBeenCalled(); expect(service._lastSelection).toBe(node); expect(selection.select).toHaveBeenCalledWith(node); }); it('should handle context menu selected node', () => { service._lastSelection = directoryNode; const node = fileNode; const event = eventSpy(); spyOn(service, 'isSelected').and.returnValue(true); service.nodeContextMenu(event, node); expect(event.stopPropagation).toHaveBeenCalled(); expect(selection.clear).not.toHaveBeenCalled(); expect(service._lastSelection).not.toBe(node); expect(selection.select).toHaveBeenCalledWith(node); }); it('should handle context menu null', () => { const event = eventSpy(); (selection.isSelected).and.returnValue(false); service.nodeContextMenu(event, null); expect(event.stopPropagation).toHaveBeenCalled(); expect(selection.clear).toHaveBeenCalled(); expect(service._lastSelection).toBeNull(); expect(selection.select).not.toHaveBeenCalled(); }); it('should return selected', () => { const selected = [directoryNode]; service._selection = {selected} as any; expect(service.selected).toBe(selected); }); it('should return has _selection', () => { (selection.hasValue).and.returnValue(true); expect(service.hasSelection).toBe(true); }); it('should return has _selection', () => { (selection.hasValue).and.returnValue(true); expect(service.hasSelection).toBe(true); }); it('should return has single or no _selection', () => { service._selection = {selected: [fileNode]} as any; expect(service.hasSingleOrNoSelection).toBe(true); service._selection = {selected: []} as any; expect(service.hasSingleOrNoSelection).toBe(true); }); it('should return has single _selection', () => { const selected = [fileNode]; service._selection = {selected} as any; expect(service.hasSingleSelection).toBe(true); expect(service.hasMultiSelection).toBe(false); }); it('should return has multi _selection', () => { const selected = [fileNode, directoryNode]; service._selection = {selected} as any; expect(service.hasSingleSelection).toBe(false); expect(service.hasMultiSelection).toBe(true); }); it('should return has single file _selection', () => { const selected = [fileNode]; service._selection = {selected} as any; expect(service.hasSingleFileSelection).toBe(true); expect(service.hasSingleDirectorySelection).toBe(false); }); it('should return has single directory _selection', () => { const selected = [directoryNode]; service._selection = {selected} as any; expect(service.hasSingleFileSelection).toBe(false); expect(service.hasSingleDirectorySelection).toBe(true); }); it('should return empty _selection', () => { const selected = []; service._selection = {selected} as any; expect(service.hasSingleSelection).toBe(false); expect(service.hasSingleFileSelection).toBe(false); expect(service.hasSingleDirectorySelection).toBe(false); }); it('should return selected directory no _selection', () => { selection.hasValue.and.returnValue(false); expect(service.selectedDirectory).toEqual(rootNode); }); it('should return selected directory first dir', () => { (selection as any).selected = [directoryNode]; selection.hasValue.and.returnValue(true); expect(service.selectedDirectory).toBe(directoryNode); }); it('should return selected directory parent dir', () => { (selection as any).selected = [fileNode]; selection.hasValue.and.returnValue(true); const nodes = [ directoryNode, fileNode, ]; dataSource.data = nodes; expect(service.selectedDirectory).toBe(directoryNode); }); it('should return selected directory parent root dir', () => { const rootFile: StorageNode = { path: 'file.ts', type: 'FILE', depth: 0, length: 42, lastModified: 1337 }; (selection as any).selected = [rootFile]; selection.hasValue.and.returnValue(true); const nodes: StorageNode[] = [ directoryNode, fileNode, rootFile, ]; dataSource.data = nodes; expect(service.selectedDirectory).toEqual(rootNode); }); it('should remove deleted files from selection', () => { service._selection = new SelectionModel<StorageNode>(true); service._lastSelection = fileNode; service._selection.select(fileNode); service._nodeDeleted(new NodeDeletedEvent(fileNode)); expect(service._lastSelection).toBeNull(); expect(service._selection.hasValue()).toBeFalsy(); }); it('should loadExpansion', () => { (localStorage.getItem as Spy).and.returnValue(_.cloneDeep([storageNodes[0], storageNodes[1]])); service.loadExpansion(storageNodes); expect(service.expansionModel.selected.length).toBe(2); expect(service.expansionModel.selected[0]).toBe(storageNodes[0]); expect(service.expansionModel.selected[1]).toBe(storageNodes[1]); }); it('should clearExpansion', () => { spyOn(service.expansionModel, 'clear'); service.clearExpansion(); expect(service.expansionModel.clear).toHaveBeenCalled(); }); it('should selectOne', () => { (dataSource.parentNode as Spy).and.returnValues(directoryNode, rootNode); service.selectOne(fileNode); expect(selection.clear).toHaveBeenCalled(); expect(selection.select).toHaveBeenCalledWith(fileNode); expect(service._lastSelection).toBe(fileNode); expect(service.expansionModel.isSelected(directoryNode)).toBeTruthy(); }); });
yegobox/kraken
frontend/projects/storage/src/lib/storage-list.service.ts
<gh_stars>1-10 import {EventEmitter, Injectable, OnDestroy} from '@angular/core'; import {StorageService} from 'projects/storage/src/lib/storage.service'; import {EventBusService} from 'projects/event/src/lib/event-bus.service'; import {BehaviorSubject, Subscription} from 'rxjs'; import * as _ from 'lodash'; import {StorageNode} from 'projects/storage/src/lib/entities/storage-node'; import {NodeEvent} from 'projects/storage/src/lib/events/node-event'; import {NodeCreatedEvent} from 'projects/storage/src/lib/events/node-created-event'; import {filter, map} from 'rxjs/operators'; import {NodeDeletedEvent} from 'projects/storage/src/lib/events/node-deleted-event'; import {NodeModifiedEvent} from 'projects/storage/src/lib/events/node-modified-event'; import {NodeEventToNodePipe} from 'projects/storage/src/lib/storage-pipes/node-event-to-node.pipe'; import {StorageNodeToNamePipe} from 'projects/storage/src/lib/storage-pipes/storage-node-to-name.pipe'; import {StorageNodeToPredicatePipe} from 'projects/storage/src/lib/storage-pipes/storage-node-to-predicate.pipe'; import {StorageNodeToParentPathPipe} from 'projects/storage/src/lib/storage-pipes/storage-node-to-parent-path.pipe'; import {StorageWatcherService} from 'projects/storage/src/lib/storage-watcher.service'; @Injectable() export class StorageListService implements OnDestroy { public readonly nodesSubject: BehaviorSubject<StorageNode[]> = new BehaviorSubject([]); public readonly nodeCreated: EventEmitter<StorageNode> = new EventEmitter<StorageNode>(); public readonly nodeModified: EventEmitter<StorageNode> = new EventEmitter<StorageNode>(); public readonly nodesDeleted: EventEmitter<StorageNode[]> = new EventEmitter<StorageNode[]>(); public readonly nodesListed: EventEmitter<StorageNode[]> = new EventEmitter<StorageNode[]>(); private readonly _eventSubscriptions: Subscription[] = []; private readonly _watcherSubscription: Subscription; private rootPath: string; private matcher: string; private maxDepth: number; constructor(private storage: StorageService, private eventBus: EventBusService, private toNode: NodeEventToNodePipe, private toName: StorageNodeToNamePipe, private toParentPath: StorageNodeToParentPathPipe, private toPredicate: StorageNodeToPredicatePipe, watcher: StorageWatcherService) { this._watcherSubscription = watcher.reconnected.subscribe(this._refresh.bind(this)); } init(rootPath: string, matcher?: string, maxDepth?: number) { this.nodes = []; this.rootPath = rootPath; this.matcher = matcher; this.maxDepth = maxDepth; this._refresh(); } private _refresh() { // This method may be called multiple times. We must clear all subscriptions to avoid handling events multiple times. this._clearEventSubscriptions(); this.storage.find(this.rootPath, this.matcher, this.maxDepth).subscribe(nodes => { this.nodes = nodes; this.nodesListed.emit(this.nodes); const matcherRegexp = new RegExp(this.matcher || '.*'); const filterNode = (node: StorageNode) => { return node.path.startsWith(this.rootPath) && !!this.toName.transform(node).match(matcherRegexp); }; this._eventSubscriptions.push(this.eventBus.of<NodeEvent>(NodeCreatedEvent.CHANNEL) .pipe(map(this.toNode.transform), filter(filterNode)) .subscribe(this._nodeCreated.bind(this))); this._eventSubscriptions.push(this.eventBus.of(NodeDeletedEvent.CHANNEL) .pipe(map(this.toNode.transform)) .subscribe(this._nodeDeleted.bind(this))); this._eventSubscriptions.push(this.eventBus.of(NodeModifiedEvent.CHANNEL) .pipe(map(this.toNode.transform), filter(filterNode)) .subscribe(this._nodeModified.bind(this))); }); } ngOnDestroy() { this._watcherSubscription.unsubscribe(); this._clearEventSubscriptions(); } private _clearEventSubscriptions() { _.invokeMap(this._eventSubscriptions, 'unsubscribe'); this._eventSubscriptions.length = 0; } set nodes(nodes: StorageNode[]) { this.sortedNodes = _.sortBy(nodes, this._nodeSorter.bind(this)); } set sortedNodes(nodes: StorageNode[]) { this.nodesSubject.next(nodes); } get nodes(): StorageNode[] { return this.nodesSubject.value; } private _nodeCreated(node: StorageNode) { // check if node already exists (may happen if a node is created while we list the nodes) const existing = _.find(this.nodes, {path: node.path}); if (existing && node.lastModified > existing.lastModified) { existing.length = node.length; existing.lastModified = node.lastModified; this.nodeModified.emit(existing); return; } const nodes = this.nodes; const index = _.sortedIndexBy(nodes, node, this._nodeSorter.bind(this)); nodes.splice(index, 0, node); this.sortedNodes = nodes; this.nodeCreated.emit(node); } private _nodeDeleted(node: StorageNode) { const nodes = this.nodes; const deleted = _.remove(nodes, this.toPredicate.transform(node)); if (deleted.length) { this.sortedNodes = nodes; this.nodesDeleted.emit(deleted); } } private _nodeModified(modified: StorageNode) { const node = _.find(this.nodes, {path: modified.path}); node.length = modified.length; node.lastModified = modified.lastModified; this.nodeModified.emit(modified); } private _nodeSorter(node: StorageNode): string { if (node.type === 'DIRECTORY') { return node.path; } if (node.depth === 0) { return `\u27BF${this.toName.transform(node)}`; } else { const parentPath = this.toParentPath.transform(node); return `${parentPath}/\u27BF${this.toName.transform(node)}`; } } }
yegobox/kraken
frontend/projects/help/src/lib/inline-help/inline-help.component.ts
<gh_stars>1-10 import {Component, Input} from '@angular/core'; import {faQuestionCircle} from '@fortawesome/free-regular-svg-icons'; import {library} from '@fortawesome/fontawesome-svg-core'; import {IconFa} from 'projects/icon/src/lib/icon-fa'; library.add(faQuestionCircle); @Component({ selector: 'lib-inline-help', templateUrl: './inline-help.component.html', styleUrls: ['./inline-help.component.scss'] }) export class InlineHelpComponent { readonly helpIcon = new IconFa(faQuestionCircle, 'accent'); @Input() tooltip: string; }
yegobox/kraken
frontend/projects/runtime/src/lib/entities/execution-context.spec.ts
<gh_stars>0 import {ExecutionContext} from 'projects/runtime/src/lib/entities/execution-context'; export const testExecutionContext: () => ExecutionContext = () => { return new ExecutionContext( 'RUN', 'description', {foo: 'bar'}, {hostId: {key: 'value'}}, ); };
yegobox/kraken
frontend/projects/storage/src/lib/storage-menu/menu-items/delete-menu-item/delete-menu-item.component.spec.ts
<gh_stars>1-10 import {async, ComponentFixture, TestBed} from '@angular/core/testing'; import {DeleteMenuItemComponent} from './delete-menu-item.component'; import {StorageTreeControlService} from 'projects/storage/src/lib/storage-tree/storage-tree-control.service'; import {storageTreeControlServiceSpy} from 'projects/storage/src/lib/storage-tree/storage-tree-control.service.spec'; import {StorageService} from 'projects/storage/src/lib/storage.service'; import {storageServiceSpy} from 'projects/storage/src/lib/storage.service.spec'; import {STORAGE_ID} from 'projects/storage/src/lib/storage-id'; describe('DeleteMenuItemComponent', () => { let component: DeleteMenuItemComponent; let fixture: ComponentFixture<DeleteMenuItemComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [DeleteMenuItemComponent], providers: [ {provide: StorageService, useValue: storageServiceSpy()}, {provide: StorageTreeControlService, useValue: storageTreeControlServiceSpy()}, {provide: STORAGE_ID, useValue: 'storage'}, ] }) .overrideTemplate(DeleteMenuItemComponent, '') .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(DeleteMenuItemComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should delete key binding', () => { const binding = component.binding; expect(binding.key).toBe('Delete'); spyOn(component, '_handleKey'); binding.binding(null); expect(component._handleKey).toHaveBeenCalledWith(jasmine.any(Function)); }); });
yegobox/kraken
frontend/projects/gatling/src/app/app.module.ts
<reponame>yegobox/kraken import {NgModule} from '@angular/core'; import {AppComponent} from './app.component'; import {CoreModule} from 'projects/commons/src/lib/core/core.module'; import {ConfigurationModule} from 'projects/commons/src/lib/config/configuration.module'; import {environment} from 'projects/gatling/src/environments/environment'; import {AppRoutingModule} from 'projects/gatling/src/app/app-routing.module'; import {ComponentsModule} from 'projects/components/src/lib/components.module'; import {AnalysisModule} from 'projects/analysis/src/lib/analysis.module'; import {RuntimeHostService} from 'projects/runtime/src/lib/runtime-host/runtime-host.service'; import {HighlightModule} from 'projects/help/src/lib/highlight/highlight.module'; @NgModule({ declarations: [ AppComponent ], imports: [ AnalysisModule, // For header interceptor CoreModule, ConfigurationModule.forRoot(environment), AppRoutingModule, ComponentsModule, HighlightModule, ], bootstrap: [AppComponent], providers: [ RuntimeHostService ] }) export class AppModule { }
yegobox/kraken
frontend/projects/dialog/src/lib/inspect-dialog/inspect-dialog.component.ts
<reponame>yegobox/kraken import {Component, Inject} from '@angular/core'; import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog'; import {HelpPageId} from 'projects/help/src/lib/help-panel/help-page-id'; export interface InspectDialogData { object: string; name: string; helpPageId: HelpPageId; } @Component({ selector: 'lib-inspect-dialog', templateUrl: './inspect-dialog.component.html', styleUrls: ['./inspect-dialog.component.scss'] }) export class InspectDialogComponent { constructor(public dialogRef: MatDialogRef<InspectDialogComponent>, @Inject(MAT_DIALOG_DATA) public data: InspectDialogData) { } }
yegobox/kraken
frontend/projects/analysis/src/lib/analysis-application-id.service.spec.ts
import {HttpHandler, HttpRequest} from '@angular/common/http'; import {ConfigurationService} from 'projects/commons/src/lib/config/configuration.service'; import {configurationServiceMock} from 'projects/commons/src/lib/config/configuration.service.spec'; import {AnalysisApplicationIdService} from 'projects/analysis/src/lib/analysis-application-id.service'; import {AnalysisConfigurationService} from 'projects/analysis/src/lib/analysis-configuration.service'; import {analysisConfigurationServiceSpy} from 'projects/analysis/src/lib/analysis-configuration.service.spec'; describe('AnalysisApplicationIdService', () => { let interceptor: AnalysisApplicationIdService; let next: HttpHandler; let configuration: ConfigurationService; let analysisConfiguration: AnalysisConfigurationService; beforeEach(() => { configuration = configurationServiceMock(); analysisConfiguration = analysisConfigurationServiceSpy(); interceptor = new AnalysisApplicationIdService(configuration, analysisConfiguration); next = jasmine.createSpyObj('next', ['handle']); }); it('should be created', () => { expect(interceptor).toBeTruthy(); }); it('should intercept', () => { const req = new HttpRequest('GET', analysisConfiguration.analysisApiUrl('/path')); const intercepted = req.clone({ headers: req.headers.set('ApplicationId', configuration.applicationId) }); interceptor.intercept(req, next); expect(next.handle).toHaveBeenCalledWith(intercepted); }); it('should not intercept', () => { const req = new HttpRequest('GET', 'apiUrl/path'); interceptor.intercept(req, next); expect(next.handle).toHaveBeenCalledWith(req); }); });
yegobox/kraken
frontend/projects/storage/src/lib/storage-pipes/storage-node-to-name.pipe.ts
<filename>frontend/projects/storage/src/lib/storage-pipes/storage-node-to-name.pipe.ts import {Pipe, PipeTransform} from '@angular/core'; import {StorageNode} from 'projects/storage/src/lib/entities/storage-node'; import * as _ from 'lodash'; @Pipe({ name: 'storageNodeToName' }) export class StorageNodeToNamePipe implements PipeTransform { transform(node: StorageNode, args?: any): string { return _.last(_.split(node.path, '/')); } }
yegobox/kraken
frontend/projects/tools/src/lib/window.service.spec.ts
import {TestBed, inject, fakeAsync, tick} from '@angular/core/testing'; import {WindowService} from './window.service'; import {of, throwError} from 'rxjs'; export const windowSpy = () => jasmine.createSpyObj('WindowService', ['resize', 'resizeNow', 'open']); describe('WindowService', () => { beforeEach(() => { TestBed.configureTestingModule({ providers: [WindowService] }); }); it('should be created', inject([WindowService], (service: WindowService) => { expect(service).toBeTruthy(); })); it('should open', fakeAsync(() => { const service = new WindowService(); const tab: any = { location: { href: '' } }; const open = spyOn(service.window, 'open'); open.and.returnValue(tab); service.open(of('url')); expect(open).toHaveBeenCalled(); expect(tab.location.href).toBe('url'); })); it('should open fail', fakeAsync(() => { const service = new WindowService(); const tab: any = { close: jasmine.createSpy('close') }; const open = spyOn(service.window, 'open'); open.and.returnValue(tab); service.open(throwError('fail')); expect(open).toHaveBeenCalled(); expect(tab.close).toHaveBeenCalled(); })); it('should resize', fakeAsync(() => { const service = new WindowService(); const dispatch = spyOn(service.window, 'dispatchEvent'); dispatch.and.callThrough(); service.resize(); tick(51); expect(dispatch).toHaveBeenCalledWith(new Event('resize')); })); it('should resize now', fakeAsync(() => { const service = new WindowService(); const dispatch = spyOn(service.window, 'dispatchEvent'); dispatch.and.callThrough(); service.resizeNow(); tick(1); expect(dispatch).toHaveBeenCalledWith(new Event('resize')); })); });
yegobox/kraken
frontend/projects/storage/src/lib/storage-tree/storage-tree.module.ts
import {NgModule} from '@angular/core'; import {CommonModule} from '@angular/common'; import {StorageNodeComponent} from 'projects/storage/src/lib/storage-tree/storage-node/storage-node.component'; import {StorageTreeComponent} from 'projects/storage/src/lib/storage-tree/storage-tree/storage-tree.component'; import {VendorsModule} from 'projects/vendors/src/lib/vendors.module'; import {IconModule} from 'projects/icon/src/lib/icon.module'; import {TreeModule} from 'projects/tree/src/lib/tree.module'; import {DialogModule} from 'projects/dialog/src/lib/dialog.module'; import {ComponentsModule} from 'projects/components/src/lib/components.module'; import {StorageTreeDataSourceService} from 'projects/storage/src/lib/storage-tree/storage-tree-data-source.service'; import {StorageTreeControlService} from 'projects/storage/src/lib/storage-tree/storage-tree-control.service'; import {CopyPasteService} from 'projects/storage/src/lib/storage-tree/copy-paste.service'; import {StoragePipesModule} from 'projects/storage/src/lib/storage-pipes/storage-pipes.module'; import {LinkSelectionButtonComponent} from './link-selection-button/link-selection-button.component'; import {DateModule} from 'projects/date/src/lib/date.module'; import {ToolsModule} from 'projects/tools/src/lib/tools.module'; import {FileNameDialogComponent} from 'projects/storage/src/lib/storage-dialogs/file-name-dialog/file-name-dialog.component'; import {DeleteFilesDialogComponent} from 'projects/storage/src/lib/storage-dialogs/delete-files-dialog/delete-files-dialog.component'; import {FileUploadDialogComponent} from 'projects/storage/src/lib/storage-dialogs/file-upload-dialog/file-upload-dialog.component'; import {StorageMenuModule} from 'projects/storage/src/lib/storage-menu/storage-menu.module'; @NgModule({ declarations: [ StorageNodeComponent, StorageTreeComponent, LinkSelectionButtonComponent, ], imports: [ CommonModule, VendorsModule, IconModule, TreeModule, DialogModule, ComponentsModule, StoragePipesModule, StorageMenuModule, DateModule, ToolsModule, ], exports: [ StorageTreeComponent, ], entryComponents: [ StorageTreeComponent, FileNameDialogComponent, DeleteFilesDialogComponent, FileUploadDialogComponent, ] }) export class StorageTreeModule { }
yegobox/kraken
frontend/projects/runtime/src/lib/runtime-task/containers-table/containers-table.component.ts
import {Component, OnDestroy, ViewChild} from '@angular/core'; import {Subscription} from 'rxjs'; import {MatTableDataSource} from '@angular/material/table'; import {MatSort} from '@angular/material/sort'; import {EventBusService} from 'projects/event/src/lib/event-bus.service'; import {map} from 'rxjs/operators'; import {TaskSelectedEvent} from 'projects/runtime/src/lib/events/task-selected-event'; import * as _ from 'lodash'; import {RuntimeContainerService} from 'projects/runtime/src/lib/runtime-task/runtime-container.service'; import {Container} from 'projects/runtime/src/lib/entities/container'; import {LOGS_ICON} from 'projects/icon/src/lib/icons'; @Component({ selector: 'lib-containers-table', templateUrl: './containers-table.component.html', styleUrls: ['./containers-table.component.scss'] }) export class ContainersTableComponent implements OnDestroy { private _subscriptions: Subscription[] = []; readonly displayedColumns: string[] = [/*'id',*/ 'startDate', 'hostId', 'status', 'label', 'name', 'logs']; readonly logsIcon = LOGS_ICON; dataSource: MatTableDataSource<Container>; private taskId: string; @ViewChild(MatSort, {static: true}) sort: MatSort; constructor(private containerService: RuntimeContainerService, private eventBus: EventBusService) { this._subscriptions.push(eventBus.of<TaskSelectedEvent>(TaskSelectedEvent.CHANNEL) .pipe(map(event => event.task)).subscribe(task => { if (task) { this.taskId = task.id; this.containers = task.containers; } else { this.taskId = null; this.containers = []; } })); } ngOnDestroy() { _.invokeMap(this._subscriptions, 'unsubscribe'); } set containers(containers: Container[]) { this.dataSource = new MatTableDataSource(containers); this.dataSource.sort = this.sort; } logs(container: Container) { this.containerService.attachLogs(this.taskId, container).subscribe(); } }
yegobox/kraken
frontend/projects/gatling/src/app/simulations/debug-simulation-menu-item/debug-simulation-menu-item.component.ts
import {Component, OnInit} from '@angular/core'; import {StorageTreeControlService} from 'projects/storage/src/lib/storage-tree/storage-tree-control.service'; import {SimulationService} from 'projects/gatling/src/app/simulations/simulation.service'; import {DEBUG_ICON, PLAY_ICON} from 'projects/icon/src/lib/icons'; @Component({ selector: 'app-debug-simulation-menu-item', templateUrl: './debug-simulation-menu-item.component.html', }) export class DebugSimulationMenuItemComponent { readonly debugIcon = DEBUG_ICON; constructor(public treeControl: StorageTreeControlService, public simulation: SimulationService) { } }
yegobox/kraken
frontend/projects/analysis/src/lib/results/debug/debug-editor/debug-editor.component.ts
import {Component, Inject, OnInit, ViewChild} from '@angular/core'; import {DefaultStorageNodeEditorComponent} from 'projects/storage/src/lib/storage-editor/storage-node-editors/default-storage-node-editor/default-storage-node-editor.component'; import {STORAGE_NODE} from 'projects/storage/src/lib/storage-editor/storage-node-editors/storage-node-editor'; import {StorageNode} from 'projects/storage/src/lib/entities/storage-node'; import {DebugEditorContentService} from 'projects/analysis/src/lib/results/debug/debug-editor/debug-editor-content.service'; import {StorageNodeEditorContentService} from 'projects/storage/src/lib/storage-editor/storage-node-editors/storage-node-editor-content.service'; import {IconFa} from 'projects/icon/src/lib/icon-fa'; import {faExternalLinkAlt} from '@fortawesome/free-solid-svg-icons/faExternalLinkAlt'; import {library} from '@fortawesome/fontawesome-svg-core'; import {faInfoCircle} from '@fortawesome/free-solid-svg-icons/faInfoCircle'; import {Portal} from '@angular/cdk/portal'; import {SplitPane} from 'projects/split/src/lib/split-pane'; import {DialogService} from 'projects/dialog/src/lib/dialog.service'; import {StringToolsService} from 'projects/tools/src/lib/string-tools.service'; library.add(faExternalLinkAlt, faInfoCircle); @Component({ selector: 'lib-debug-editor', templateUrl: './debug-editor.component.html', styleUrls: ['./debug-editor.component.scss'], providers: [ {provide: StorageNodeEditorContentService, useClass: DebugEditorContentService} ] }) export class DebugEditorComponent extends DefaultStorageNodeEditorComponent implements OnInit { readonly newTabIcon = new IconFa(faExternalLinkAlt, 'primary'); readonly sessionIcon = new IconFa(faInfoCircle, 'accent'); public debug: DebugEditorContentService; public splits: SplitPane[]; @ViewChild('requestPortal', { static: true }) requestPortal: Portal<any>; @ViewChild('responsePortal', { static: true }) responsePortal: Portal<any>; constructor(@Inject(STORAGE_NODE) node: StorageNode, public contentService: StorageNodeEditorContentService, private dialogs: DialogService, private strings: StringToolsService) { super(node, contentService); this.debug = contentService as DebugEditorContentService; } ngOnInit() { super.ngOnInit(); this.splits = [new SplitPane(this.requestPortal, 50, 20), new SplitPane(this.responsePortal, 50, 20)]; } public inspectSession() { this.dialogs.inspect('Gatling Session', this.strings.replaceAll(this.debug.entry.session, ',', ',\n\t')); } }
yegobox/kraken
frontend/projects/storage/src/lib/storage-dialogs/file-upload-dialog/file-upload-dialog.component.spec.ts
<filename>frontend/projects/storage/src/lib/storage-dialogs/file-upload-dialog/file-upload-dialog.component.spec.ts import {async, ComponentFixture, TestBed} from '@angular/core/testing'; import {FileUploadDialogComponent} from './file-upload-dialog.component'; import {MAT_DIALOG_DATA, MatDialogRef} from '@angular/material'; import {dialogRefSpy} from 'projects/commons/src/lib/mock/material.mock.spec'; import {FileUploadService} from 'projects/storage/src/lib/storage-dialogs/file-upload-dialog/file-upload.service'; import {fileUploadServiceSpy} from 'projects/storage/src/lib/storage-dialogs/file-upload-dialog/file-upload.service.spec'; describe('FileUploadDialogComponent', () => { let component: FileUploadDialogComponent; let fixture: ComponentFixture<FileUploadDialogComponent>; let uploadService: FileUploadService; let dialogRef: MatDialogRef<FileUploadDialogComponent>; let fileInput; beforeEach(async(() => { uploadService = fileUploadServiceSpy(); dialogRef = dialogRefSpy(); fileInput = { nativeElement: { files: { 0: {name: 'file-0'}, 1: {name: 'file-1'}, length: 2, item: 'somehing', }, click: jasmine.createSpy('click'), } }; TestBed.configureTestingModule({ declarations: [FileUploadDialogComponent], providers: [ {provide: MAT_DIALOG_DATA, useValue: {endpoint: 'endpoint'}}, {provide: MatDialogRef, useValue: dialogRef}, {provide: FileUploadService, useValue: uploadService} ] }) .overrideProvider(FileUploadService, {useValue: uploadService}) .overrideTemplate(FileUploadDialogComponent, '') .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(FileUploadDialogComponent); component = fixture.componentInstance; component._fileInput = fileInput; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should addFiles click on hidden files input', () => { component.addFiles(); expect(fileInput.nativeElement.click).toHaveBeenCalled(); }); it('should upload on files added', () => { component.onFilesAdded(); expect(uploadService.upload).toHaveBeenCalledWith([fileInput.nativeElement.files[0], fileInput.nativeElement.files[1]], 'endpoint'); expect(dialogRef.close).toHaveBeenCalled(); }); });
yegobox/kraken
frontend/projects/analysis/src/lib/results/results-table/results-table.component.spec.ts
import {async, ComponentFixture, TestBed} from '@angular/core/testing'; import {ResultsTableComponent} from 'projects/analysis/src/lib/results/results-table/results-table.component'; import {GatlingResultService} from 'projects/analysis/src/lib/results/results-table/gatling-result.service'; import {gatlingResultServiceSpy} from 'projects/analysis/src/lib/results/results-table/gatling-result.service.spec'; import {ResultsTableService} from 'projects/analysis/src/lib/results/results-table/results-table.service'; import SpyObj = jasmine.SpyObj; import { resultsTableServiceSpy, testResult } from 'projects/analysis/src/lib/results/results-table/results-table.service.spec'; describe('ResultsListComponent', () => { let component: ResultsTableComponent; let fixture: ComponentFixture<ResultsTableComponent>; let results: SpyObj<ResultsTableService>; let gatling: SpyObj<GatlingResultService>; beforeEach(async(() => { results = resultsTableServiceSpy(); gatling = gatlingResultServiceSpy(); TestBed.configureTestingModule({ declarations: [ResultsTableComponent], providers: [ {provide: GatlingResultService, useValue: gatling}, {provide: ResultsTableService, useValue: results} ] }) .overrideProvider(GatlingResultService, {useValue: gatling}) .overrideTemplate(ResultsTableComponent, '') .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(ResultsTableComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); expect(results.init).toHaveBeenCalled(); }); it('should init datasource', () => { results.valuesSubject.next([testResult()]); expect(component.dataSource).toBeTruthy(); }); });
yegobox/kraken
frontend/projects/gatling/src/app/simulations/simulation-editor/simulation-editor.component.spec.ts
import {async, ComponentFixture, TestBed} from '@angular/core/testing'; import {SimulationEditorComponent} from './simulation-editor.component'; import {SimulationService} from 'projects/gatling/src/app/simulations/simulation.service'; import {simulationServiceSpy} from 'projects/gatling/src/app/simulations/simulation.service.spec'; import {StorageNodeEditorContentService} from 'projects/storage/src/lib/storage-editor/storage-node-editors/storage-node-editor-content.service'; import {storageNodeEditorContentServiceSpy} from 'projects/storage/src/lib/storage-editor/storage-node-editors/storage-node-editor-content.service.spec'; import {STORAGE_NODE} from 'projects/storage/src/lib/storage-editor/storage-node-editors/storage-node-editor'; import {testStorageFileNode} from 'projects/storage/src/lib/entities/storage-node.spec'; describe('SimulationEditorComponent', () => { let component: SimulationEditorComponent; let fixture: ComponentFixture<SimulationEditorComponent>; beforeEach(async(() => { const contentService = storageNodeEditorContentServiceSpy(); TestBed.configureTestingModule({ declarations: [SimulationEditorComponent], providers: [ {provide: StorageNodeEditorContentService, useValue: contentService}, {provide: SimulationService, useValue: simulationServiceSpy()}, {provide: STORAGE_NODE, useValue: testStorageFileNode()}, ] }) .overrideTemplate(SimulationEditorComponent, '') .overrideProvider(StorageNodeEditorContentService, {useValue: contentService}) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(SimulationEditorComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
yegobox/kraken
frontend/projects/help/src/lib/highlight/highlight.service.ts
import {Injectable, Injector} from '@angular/core'; import {Overlay} from '@angular/cdk/overlay'; import {ComponentPortal, PortalInjector} from '@angular/cdk/portal'; import {OverlayRef} from '@angular/cdk/overlay/typings/overlay-ref'; import { HIGHLIGHT_DURATION_DATA, HIGHLIGHT_RECT_DATA, HighlightBackdropComponent } from 'projects/help/src/lib/highlight/highlight-backdrop/highlight-backdrop.component'; @Injectable({ providedIn: 'root' }) export class HighlightService { document = document; overlayRef: OverlayRef; constructor( private injector: Injector, private overlay: Overlay) { this.overlayRef = this.overlay.create({ width: '100%', height: '100%', }); } highlight( selector: string, duration = 800 ) { // Min duration is 300ms because of fade in/out animations duration = Math.max(duration, 300); const element: HTMLElement = this.document.querySelector(selector); if (!element) { return; } const rect = element.getBoundingClientRect(); const injectorTokens = new WeakMap(); injectorTokens.set(HIGHLIGHT_RECT_DATA, rect); injectorTokens.set(HIGHLIGHT_DURATION_DATA, duration); const portal = new ComponentPortal(HighlightBackdropComponent, null, new PortalInjector(this.injector, injectorTokens)); this.overlayRef.attach(portal); setTimeout(() => { this.overlayRef.detach(); }, duration); } }