Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AddProjectScreen.test.ts

171 lines6.4 KB

1import * as NodeFS from "node:fs";
2import * as NodeFSP from "node:fs/promises";
3import * as NodeOS from "node:os";
4import * as NodePath from "node:path";
5import { AuthOrchestrationOperateScope, AuthSourceControlWriteScope } from "@t3tools/contracts";
6import * as Cause from "effect/Cause";
7import { AsyncResult } from "effect/reactivity";
8import { isValidElement, type ReactNode } from "react";
9import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
10​
11const state = vi.hoisted(() => ({
12 scopes: new Set<string>(),
13 baseDirectory: "",
14 projects: [] as string[],
15}));
16​
17vi.mock("react", async (importOriginal) => ({
18 ...(await importOriginal<typeof import("react")>()),
19 useCallback: (callback: unknown) => callback,
20 useMemo: (factory: () => unknown) => factory(),
21 useState: (initial: unknown) => [typeof initial === "function" ? initial() : initial, () => {}],
22 useRef: (current: unknown) => ({ current }),
23 useEffect: () => {},
24}));
25vi.mock("../../components/ui/NavigationRow", () => ({ NavigationRow: "NavigationRow" }));
26vi.mock("../../components/ui/Button", () => ({ Button: "Button" }));
27vi.mock("../../components/ui/ScreenScrollView", () => ({ ScreenScrollView: "ScrollView" }));
28vi.mock("../settings/components/SettingsScreen", () => ({ SettingsScreen: "SettingsScreen" }));
29vi.mock("../../components/ui/ThemedSwitch", () => ({ ThemedSwitch: "Switch" }));
30vi.mock("react-native", () => ({
31 Platform: { OS: "ios" },
32 ActivityIndicator: "ActivityIndicator",
33 Alert: { alert: () => {} },
34 Pressable: "Pressable",
35 ScrollView: "ScrollView",
36 View: "View",
37}));
38vi.mock("@react-navigation/native", () => ({
39 useNavigation: () => ({ dispatch: () => {} }),
40 CommonActions: { reset: (input: unknown) => input },
41 StackActions: {},
42}));
43vi.mock("react-native-safe-area-context", () => ({
44 useSafeAreaInsets: () => ({ bottom: 0 }),
45}));
46vi.mock("../../components/ui/AppSymbol", () => ({ SymbolView: "SymbolView" }));
47vi.mock("../../components/ui/AppText", () => ({ AppText: "Text", AppTextInput: "TextInput" }));
48vi.mock("../../components/EnvironmentMachineSymbol", () => ({
49 EnvironmentMachineSymbol: "EnvironmentMachineSymbol",
50}));
51vi.mock("../../components/ui/ErrorBanner", () => ({ ErrorBanner: "ErrorBanner" }));
52vi.mock("./SourceControlIcon", () => ({ SourceControlIcon: "SourceControlIcon" }));
53vi.mock("../../lib/uuid", () => ({ uuidv4: () => "project" }));
54vi.mock("../../state/session", () => ({
55 useEnvironmentScope: (_environmentId: string, scope: string) => state.scopes.has(scope),
56 readEnvironmentScope: (_environmentId: string, scope: string) => state.scopes.has(scope),
57}));
58vi.mock("../../state/entities", () => ({
59 useProjects: () => [],
60 useServerConfigs: () =>
61 new Map([
62 [
63 "environment",
64 {
65 environment: { platform: { os: "linux" }, capabilities: {} },
66 settings: { addProjectBaseDirectory: state.baseDirectory },
67 },
68 ],
69 ]),
70}));
71vi.mock("../../state/use-remote-environment-registry", () => ({
72 useRemoteEnvironmentRuntime: () => ({ connectionState: "connected" }),
73 useRemoteConnectionStatus: () => ({
74 connectedEnvironments: [{ environmentId: "environment", connectionState: "connected" }],
75 }),
76 useSavedRemoteConnections: () => ({
77 savedConnectionsById: {
78 connection: { environmentId: "environment", environmentLabel: "Environment" },
79 },
80 }),
81}));
82vi.mock("../../state/use-atom-command", () => ({ useAtomCommand: (command: unknown) => command }));
83vi.mock("../../state/use-atom-query-runner", () => ({ useAtomQueryRunner: () => () => {} }));
84vi.mock("../../state/query", () => ({ useEnvironmentQuery: () => ({ data: null }) }));
85vi.mock("../../state/presentation", () => ({
86 useEnvironmentPresentation: () => ({ isReady: true, presentation: null }),
87}));
88vi.mock("../../state/filesystem", () => ({ filesystemEnvironment: {} }));
89vi.mock("../../state/sourceControl", () => ({
90 sourceControlEnvironment: {
91 cloneRepository: async ({ input }: { input: { destinationPath: string } }) => {
92 NodeFS.mkdirSync(input.destinationPath);
93 return AsyncResult.success({ cwd: input.destinationPath });
94 },
95 },
96}));
97vi.mock("../../state/projects", () => ({
98 projectEnvironment: {
99 create: async ({ input }: { input: { workspaceRoot: string } }) => {
100 if (!state.scopes.has(AuthOrchestrationOperateScope)) {
101 return AsyncResult.failure(Cause.fail(new Error("Project creation denied")));
102 }
103 state.projects.push(input.workspaceRoot);
104 return AsyncResult.success(undefined);
105 },
106 },
107}));
108​
109import { AddProjectDestinationScreen } from "./AddProjectScreen";
110​
111function findAction(node: ReactNode, label: string): (() => unknown) | null {
112 if (Array.isArray(node)) {
113 for (const child of node) {
114 const action = findAction(child, label);
115 if (action) return action;
116 }
117 return null;
118 }
119 if (!isValidElement<{ label?: string; onPress?: () => unknown; children?: ReactNode }>(node)) {
120 return null;
121 }
122 if (node.props.label === label) return node.props.onPress ?? null;
123 return findAction(node.props.children, label);
125​
126function cloneAction() {
127 const action = findAction(
128 AddProjectDestinationScreen({
129 environmentId: "environment",
130 remoteUrl: "https://example.com/repo.git",
131 repositoryName: "repo",
132 }),
133 "Clone project",
134 );
135 if (!action) throw new Error("Clone action missing");
136 return action;
138​
139describe("clone project permissions", () => {
140 beforeEach(async () => {
141 state.baseDirectory = await NodeFSP.mkdtemp(
142 NodePath.join(NodeOS.tmpdir(), "t3-clone-permissions-"),
143 );
144 state.scopes = new Set([AuthSourceControlWriteScope]);
145 state.projects = [];
146 });
147​
148 afterEach(async () => {
149 await NodeFSP.rm(state.baseDirectory, { recursive: true, force: true });
150 });
151​
152 it("does not leave a clone on disk when project creation is denied", async () => {
153 await cloneAction()();
154​
155 expect(NodeFS.existsSync(NodePath.join(state.baseDirectory, "repo"))).toBe(false);
156 expect(state.projects).toEqual([]);
157 });
158​
159 it.each([AuthSourceControlWriteScope, AuthOrchestrationOperateScope])(
160 "rechecks %s before a retained clone action creates a directory",
161 async (scope) => {
162 state.scopes.add(AuthOrchestrationOperateScope);
163 const submit = cloneAction();
164 state.scopes.delete(scope);
165 await submit();
166​
167 expect(NodeFS.existsSync(NodePath.join(state.baseDirectory, "repo"))).toBe(false);
168 expect(state.projects).toEqual([]);
169 },
170 );
171});