Reformatting code.

This commit is contained in:
Roland 2025-12-06 14:49:46 -07:00 • committed by lrnselfreliance
parent 5b29144d70
commit 8a7f0737f0
42 changed files with 306 additions and 238 deletions

View file

@ -2,7 +2,6 @@ import React, {useEffect} from 'react';
import {useRecurringTimeout} from "./hooks/customHooks";
import {ApiDownError, getEvents} from "./api";
import {toast} from "react-semantic-toasts-2";
import {StatusContext} from "./contexts/contexts";
const apiEventName = 'apiEvent';

View file

@ -1,7 +1,16 @@
import {emptyToNull} from "./components/Common";
import {toast} from "react-semantic-toasts-2";
import _ from "lodash";
import {API_URI, ARCHIVES_API, COLLECTIONS_API, DEFAULT_LIMIT, Downloaders, OTP_API, VIDEOS_API, ZIM_API} from "./components/Vars";
import {
API_URI,
ARCHIVES_API,
COLLECTIONS_API,
DEFAULT_LIMIT,
Downloaders,
OTP_API,
VIDEOS_API,
ZIM_API
} from "./components/Vars";
function timeoutPromise(ms, promise) {
// Create a timeout wrapper around a promise. If the timeout is reached, throw an error. Otherwise, return
@ -1674,4 +1683,4 @@ export async function triggerUpgrade() {
});
}
return response;
}
}

View file

@ -34,25 +34,27 @@ import {
textEllipsis,
useTitle
} from "./Common";
import {deleteArchives, deleteDomain, generateArchiveScreenshot, getCollectionTagInfo, postDownload, refreshDomain, tagDomain, tagFileGroup, untagFileGroup} from "../api";
import {
deleteArchives,
deleteDomain,
generateArchiveScreenshot,
getCollectionTagInfo,
postDownload,
refreshDomain,
tagDomain,
tagFileGroup,
untagFileGroup
} from "../api";
import {CollectionTagModal} from "./collections/CollectionTagModal";
import {Link, Route, Routes, useLocation, useNavigate, useParams} from "react-router-dom";
import Message from "semantic-ui-react/dist/commonjs/collections/Message";
import {
useArchive,
useDomain,
useDomains,
useOneQuery,
useSearchArchives,
useSearchOrder
} from "../hooks/customHooks";
import {useArchive, useDomain, useDomains, useOneQuery, useSearchArchives, useSearchOrder} from "../hooks/customHooks";
import {FileCards, FileRowTagIcon, FilesView} from "./Files";
import Grid from "semantic-ui-react/dist/commonjs/collections/Grid";
import _ from "lodash";
import {Media, ThemeContext} from "../contexts/contexts";
import {Button, Card, CardIcon, darkTheme, Header, Loader, Placeholder, Popup, Segment, Tab, TabPane} from "./Theme";
import {SortableTable} from "./SortableTable";
import {taggedImageLabel, TagsSelector, TagsContext} from "../Tags";
import {Button, Card, CardIcon, darkTheme, Header, Loader, Popup, Segment, Tab, TabPane} from "./Theme";
import {taggedImageLabel, TagsSelector} from "../Tags";
import {toast} from "react-semantic-toasts-2";
import {API_ARCHIVE_UPLOAD_URI, Downloaders} from "./Vars";
import {CollectionTable} from "./collections/CollectionTable";
@ -363,7 +365,14 @@ const DOMAIN_COLUMNS = [
{key: 'domain', label: 'Domain', sortable: true, width: 7},
{key: 'tag_name', label: 'Tag', sortable: true, width: 2},
{key: 'archive_count', label: 'Archives', sortable: true, align: 'right', width: 2},
{key: 'min_download_frequency', label: 'Download Frequency', sortable: true, format: 'frequency', width: 2, hideOnMobile: true},
{
key: 'min_download_frequency',
label: 'Download Frequency',
sortable: true,
format: 'frequency',
width: 2,
hideOnMobile: true
},
{key: 'size', label: 'Size', sortable: true, align: 'right', format: 'bytes', width: 2, hideOnMobile: true},
{key: 'actions', label: 'Manage', sortable: false, type: 'actions', width: 1}
];

View file

@ -1,5 +1,5 @@
import React, {useState} from "react";
import {Grid, StatisticLabel, StatisticValue, TableCell, TableRow,} from "semantic-ui-react";
import {Grid, StatisticLabel, StatisticValue,} from "semantic-ui-react";
import {createChannel, deleteChannel, refreshChannel, tagChannel, tagChannelInfo} from "../api";
import {CollectionTagModal} from "./collections/CollectionTagModal";
import {
@ -10,7 +10,6 @@ import {
humanNumber,
InfoPopup,
SearchInput,
secondsToFrequency,
secondsToFullDuration,
SimpleAccordion,
useTitle,
@ -20,17 +19,7 @@ import {Link, useNavigate, useParams} from "react-router-dom";
import Message from "semantic-ui-react/dist/commonjs/collections/Message";
import {useChannel, useChannels, useOneQuery} from "../hooks/customHooks";
import _ from "lodash";
import {
Button,
Form,
Header,
Loader,
Modal,
ModalContent,
Segment,
Statistic
} from "./Theme";
import {Media, ThemeContext} from "../contexts/contexts";
import {Button, Form, Header, Loader, Modal, ModalContent, Segment, Statistic} from "./Theme";
import {toast} from "react-semantic-toasts-2";
import {RecurringDownloadsTable} from "./admin/Downloads";
import {InputForm, ToggleForm} from "../hooks/useForm";
@ -43,7 +32,14 @@ const CHANNEL_COLUMNS = [
{key: 'name', label: 'Name', sortable: true, width: 7},
{key: 'tag_name', label: 'Tag', sortable: true, width: 2},
{key: 'video_count', label: 'Videos', sortable: true, align: 'right', width: 2},
{key: 'min_download_frequency', label: 'Download Frequency', sortable: true, format: 'frequency', width: 2, hideOnMobile: true},
{
key: 'min_download_frequency',
label: 'Download Frequency',
sortable: true,
format: 'frequency',
width: 2,
hideOnMobile: true
},
{key: 'total_size', label: 'Size', sortable: true, align: 'right', format: 'bytes', width: 2, hideOnMobile: true},
{key: 'actions', label: 'Manage', sortable: false, type: 'actions', width: 1}
];

View file

@ -1,5 +1,5 @@
import React from 'react';
import {render, screen, waitFor, act} from '@testing-library/react';
import {act, render, screen, waitFor} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import {DirectorySearch} from './Common';
@ -74,7 +74,7 @@ describe('DirectorySearch', () => {
describe('Rendering', () => {
it('renders with placeholder text', () => {
render(<DirectorySearch onSelect={mockOnSelect} value="" />);
render(<DirectorySearch onSelect={mockOnSelect} value=""/>);
const input = screen.getByPlaceholderText(/search directory names/i);
expect(input).toBeInTheDocument();
@ -86,14 +86,14 @@ describe('DirectorySearch', () => {
directoryName: 'videos/test',
});
render(<DirectorySearch onSelect={mockOnSelect} value="videos/test" />);
render(<DirectorySearch onSelect={mockOnSelect} value="videos/test"/>);
const input = screen.getByDisplayValue('videos/test');
expect(input).toBeInTheDocument();
});
it('applies disabled state correctly', () => {
render(<DirectorySearch onSelect={mockOnSelect} value="" disabled />);
render(<DirectorySearch onSelect={mockOnSelect} value="" disabled/>);
const input = screen.getByPlaceholderText(/search directory names/i);
expect(input).toBeDisabled();
@ -101,7 +101,7 @@ describe('DirectorySearch', () => {
it('displays with required indicator', () => {
const {container} = render(
<DirectorySearch onSelect={mockOnSelect} value="" required />
<DirectorySearch onSelect={mockOnSelect} value="" required/>
);
// Semantic UI doesn't add required attribute to Search input,
@ -112,7 +112,7 @@ describe('DirectorySearch', () => {
describe('Search Functionality', () => {
it('triggers setDirectoryName on value change', async () => {
render(<DirectorySearch onSelect={mockOnSelect} value="" />);
render(<DirectorySearch onSelect={mockOnSelect} value=""/>);
const input = screen.getByPlaceholderText(/search directory names/i);
await userEvent.type(input, 'videos');
@ -130,7 +130,7 @@ describe('DirectorySearch', () => {
loading: true,
});
render(<DirectorySearch onSelect={mockOnSelect} value="" />);
render(<DirectorySearch onSelect={mockOnSelect} value=""/>);
const searchContainer = screen.getByPlaceholderText(/search directory names/i)
.closest('.ui.search');
@ -143,7 +143,7 @@ describe('DirectorySearch', () => {
loading: false,
});
render(<DirectorySearch onSelect={mockOnSelect} value="" />);
render(<DirectorySearch onSelect={mockOnSelect} value=""/>);
const searchContainer = screen.getByPlaceholderText(/search directory names/i)
.closest('.ui.search');
@ -151,7 +151,7 @@ describe('DirectorySearch', () => {
});
it('displays categorized results', async () => {
render(<DirectorySearch onSelect={mockOnSelect} value="" />);
render(<DirectorySearch onSelect={mockOnSelect} value=""/>);
const input = screen.getByPlaceholderText(/search directory names/i);
// Click to open dropdown
@ -174,7 +174,7 @@ describe('DirectorySearch', () => {
directoryName: 'new/path',
});
render(<DirectorySearch onSelect={mockOnSelect} value="" />);
render(<DirectorySearch onSelect={mockOnSelect} value=""/>);
const input = screen.getByPlaceholderText(/search directory names/i);
await userEvent.click(input);
@ -193,7 +193,7 @@ describe('DirectorySearch', () => {
directoryName: 'videos/nature',
});
render(<DirectorySearch onSelect={mockOnSelect} value="" />);
render(<DirectorySearch onSelect={mockOnSelect} value=""/>);
const input = screen.getByPlaceholderText(/search directory names/i);
await userEvent.click(input);
@ -203,7 +203,7 @@ describe('DirectorySearch', () => {
});
it('debounces rapid typing (verifies setDirectoryName is called)', async () => {
render(<DirectorySearch onSelect={mockOnSelect} value="" />);
render(<DirectorySearch onSelect={mockOnSelect} value=""/>);
const input = screen.getByPlaceholderText(/search directory names/i);
@ -217,7 +217,7 @@ describe('DirectorySearch', () => {
describe('User Interactions', () => {
it('calls onSelect when result is clicked', async () => {
render(<DirectorySearch onSelect={mockOnSelect} value="" />);
render(<DirectorySearch onSelect={mockOnSelect} value=""/>);
const input = screen.getByPlaceholderText(/search directory names/i);
await userEvent.click(input);
@ -242,7 +242,7 @@ describe('DirectorySearch', () => {
});
// Render with empty value prop (different from directoryName)
const {container} = render(<DirectorySearch onSelect={mockOnSelect} value="" />);
const {container} = render(<DirectorySearch onSelect={mockOnSelect} value=""/>);
// Find the Search component container and trigger blur on it
const searchComponent = container.querySelector('.ui.search');
@ -264,7 +264,7 @@ describe('DirectorySearch', () => {
directoryName: 'existing/path',
});
render(<DirectorySearch onSelect={mockOnSelect} value="existing/path" />);
render(<DirectorySearch onSelect={mockOnSelect} value="existing/path"/>);
const input = screen.getByDisplayValue('existing/path');
@ -278,7 +278,7 @@ describe('DirectorySearch', () => {
});
it('disabled state prevents interactions', () => {
render(<DirectorySearch onSelect={mockOnSelect} value="" disabled />);
render(<DirectorySearch onSelect={mockOnSelect} value="" disabled/>);
const input = screen.getByPlaceholderText(/search directory names/i);
@ -287,7 +287,7 @@ describe('DirectorySearch', () => {
});
it('handles rapid selection changes', async () => {
render(<DirectorySearch onSelect={mockOnSelect} value="" />);
render(<DirectorySearch onSelect={mockOnSelect} value=""/>);
const input = screen.getByPlaceholderText(/search directory names/i);
await userEvent.click(input);
@ -308,7 +308,7 @@ describe('DirectorySearch', () => {
describe('Hook Integration', () => {
it('calls setDirectoryName from hook on search change', async () => {
render(<DirectorySearch onSelect={mockOnSelect} value="" />);
render(<DirectorySearch onSelect={mockOnSelect} value=""/>);
const input = screen.getByPlaceholderText(/search directory names/i);
await userEvent.type(input, 'archive');
@ -317,7 +317,7 @@ describe('DirectorySearch', () => {
});
it('displays results from hook state', async () => {
render(<DirectorySearch onSelect={mockOnSelect} value="" />);
render(<DirectorySearch onSelect={mockOnSelect} value=""/>);
const input = screen.getByPlaceholderText(/search directory names/i);
await userEvent.click(input);
@ -344,7 +344,7 @@ describe('DirectorySearch', () => {
});
// This should not throw an error
render(<DirectorySearch onSelect={mockOnSelect} value="" />);
render(<DirectorySearch onSelect={mockOnSelect} value=""/>);
const input = screen.getByPlaceholderText(/search directory names/i);
@ -361,7 +361,7 @@ describe('DirectorySearch', () => {
directoryName: '',
});
render(<DirectorySearch onSelect={mockOnSelect} value={null} />);
render(<DirectorySearch onSelect={mockOnSelect} value={null}/>);
const input = screen.getByPlaceholderText(/search directory names/i);
expect(input).toHaveValue('');
@ -376,7 +376,7 @@ describe('DirectorySearch', () => {
directoryName: '',
});
render(<DirectorySearch onSelect={mockOnSelect} value="" />);
render(<DirectorySearch onSelect={mockOnSelect} value=""/>);
const input = screen.getByPlaceholderText(/search directory names/i);
expect(input).toHaveValue('');
@ -389,19 +389,19 @@ describe('DirectorySearch', () => {
});
const {rerender} = render(
<DirectorySearch onSelect={mockOnSelect} value="videos/test" />
<DirectorySearch onSelect={mockOnSelect} value="videos/test"/>
);
expect(screen.getByDisplayValue('videos/test')).toBeInTheDocument();
// Remount with same value
rerender(<DirectorySearch onSelect={mockOnSelect} value="videos/test" />);
rerender(<DirectorySearch onSelect={mockOnSelect} value="videos/test"/>);
expect(screen.getByDisplayValue('videos/test')).toBeInTheDocument();
});
it('handles special characters in path', async () => {
render(<DirectorySearch onSelect={mockOnSelect} value="" />);
render(<DirectorySearch onSelect={mockOnSelect} value=""/>);
const input = screen.getByPlaceholderText(/search directory names/i);

View file

@ -1,8 +1,7 @@
import React from 'react';
import {render, renderInDarkMode, screen, waitFor, createTestForm} from '../test-utils';
import {createMockDomain, createTestForm, render, renderInDarkMode, screen, waitFor} from '../test-utils';
import userEvent from '@testing-library/user-event';
import {DomainEditPage} from './Archive';
import {createMockDomain} from '../test-utils';
// Mock useParams to return domain ID
jest.mock('react-router-dom', () => ({
@ -45,9 +44,11 @@ jest.mock('./collections/CollectionTagModal', () => ({
return (
<div data-testid="collection-tag-modal">
<div data-testid="modal-header">{currentTagName ? 'Modify Tag' : 'Add Tag'}</div>
<input type="text" data-testid="directory-input" defaultValue={originalDirectory || ''} />
<input type="text" data-testid="directory-input" defaultValue={originalDirectory || ''}/>
<button data-testid="cancel-button" onClick={onClose}>Cancel</button>
<button data-testid="save-button" onClick={() => onSave && onSave(currentTagName, originalDirectory)}>Save</button>
<button data-testid="save-button"
onClick={() => onSave && onSave(currentTagName, originalDirectory)}>Save
</button>
</div>
);
},
@ -79,7 +80,7 @@ describe('DomainEditPage', () => {
fetchDomain: jest.fn(),
});
render(<DomainEditPage />);
render(<DomainEditPage/>);
// Should show Semantic UI Loader with text
expect(screen.getByText(/loading domain/i)).toBeInTheDocument();
@ -103,7 +104,7 @@ describe('DomainEditPage', () => {
fetchDomain: jest.fn(),
});
render(<DomainEditPage />);
render(<DomainEditPage/>);
// Should NOT show loading message
expect(screen.queryByText(/loading domain/i)).not.toBeInTheDocument();
@ -128,7 +129,7 @@ describe('DomainEditPage', () => {
fetchDomain: jest.fn(),
});
render(<DomainEditPage />);
render(<DomainEditPage/>);
// Should show loading indicator in form (from mocked component)
// Multiple indicators due to Fresnel rendering for mobile and tablet+
@ -152,7 +153,7 @@ describe('DomainEditPage', () => {
fetchDomain: jest.fn(),
});
render(<DomainEditPage />);
render(<DomainEditPage/>);
// Should show loading screen when not ready
expect(screen.getByText(/loading domain/i)).toBeInTheDocument();
@ -177,7 +178,7 @@ describe('DomainEditPage', () => {
fetchDomain: jest.fn(),
});
render(<DomainEditPage />);
render(<DomainEditPage/>);
// Should show domain name (form is rendered)
// Multiple occurrences due to Fresnel rendering for mobile and tablet+
@ -205,7 +206,7 @@ describe('DomainEditPage', () => {
fetchDomain: jest.fn(),
});
render(<DomainEditPage />);
render(<DomainEditPage/>);
// useTitle should be called with domain name
expect(useTitle).toHaveBeenCalledWith('Edit Domain: example.com');
@ -224,7 +225,7 @@ describe('DomainEditPage', () => {
fetchDomain: jest.fn(),
});
render(<DomainEditPage />);
render(<DomainEditPage/>);
// useTitle should be called with placeholder
expect(useTitle).toHaveBeenCalledWith('Edit Domain: ...');
@ -248,7 +249,7 @@ describe('DomainEditPage', () => {
});
// Render in dark mode
renderInDarkMode(<DomainEditPage />);
renderInDarkMode(<DomainEditPage/>);
// CollectionEditForm should be rendered
expect(screen.getByTestId('collection-edit-form')).toBeInTheDocument();
@ -273,7 +274,7 @@ describe('DomainEditPage', () => {
});
// Default render (light mode)
render(<DomainEditPage />);
render(<DomainEditPage/>);
// CollectionEditForm should be rendered
expect(screen.getByTestId('collection-edit-form')).toBeInTheDocument();
@ -312,7 +313,7 @@ describe('DomainEditPage', () => {
conflict_message: null,
});
render(<DomainEditPage />);
render(<DomainEditPage/>);
// Click the Tag button to open modal
const tagButton = screen.getByText('Tag');
@ -352,7 +353,7 @@ describe('DomainEditPage', () => {
conflict_message: "A domain collection 'other.com' already uses this directory. Choose a different tag or directory.",
});
render(<DomainEditPage />);
render(<DomainEditPage/>);
// Open the modal
const tagButton = screen.getByText('Tag');
@ -383,7 +384,7 @@ describe('DomainEditPage', () => {
fetchDomain: jest.fn(),
});
render(<DomainEditPage />);
render(<DomainEditPage/>);
// Open modal
const tagButton = screen.getByText('Tag');
@ -421,7 +422,7 @@ describe('DomainEditPage', () => {
conflict_message: null,
});
render(<DomainEditPage />);
render(<DomainEditPage/>);
// Open modal
const tagButton = screen.getByText('Tag');

View file

@ -1,8 +1,7 @@
import React from 'react';
import {render, screen, createTestForm} from '../test-utils';
import {createMockDomain, createTestForm, render, screen} from '../test-utils';
import {CollectionEditForm} from './collections/CollectionEditForm';
import {DomainsPage} from './Archive';
import {createMockDomain} from '../test-utils';
// Mock the TagsContext
jest.mock('../Tags', () => ({
@ -66,14 +65,14 @@ jest.mock('./collections/CollectionTable', () => ({
<div data-testid="collection-table">
<table>
<tbody>
{collections?.map((domain) => (
<tr key={domain.id} data-testid={`domain-row-${domain.id}`}>
<td data-testid={`domain-name-${domain.id}`}>{domain.domain}</td>
<td data-testid={`domain-tag-${domain.id}`}>
{domain.tag_name || 'No tag'}
</td>
</tr>
))}
{collections?.map((domain) => (
<tr key={domain.id} data-testid={`domain-row-${domain.id}`}>
<td data-testid={`domain-name-${domain.id}`}>{domain.domain}</td>
<td data-testid={`domain-tag-${domain.id}`}>
{domain.tag_name || 'No tag'}
</td>
</tr>
))}
</tbody>
</table>
</div>
@ -163,7 +162,8 @@ describe('Domain Tagging Logic', () => {
useTitle.mockReset();
// Re-setup default mocks
useTitle.mockImplementation(() => {});
useTitle.mockImplementation(() => {
});
mockUseOneQuery.mockReturnValue(['', jest.fn()]);
});
@ -187,7 +187,7 @@ describe('Domain Tagging Logic', () => {
mockUseDomains.mockReturnValue([mockDomains, 2]);
render(<DomainsPage />);
render(<DomainsPage/>);
// Tagged domain should display its tag
expect(screen.getByTestId('domain-tag-1')).toHaveTextContent('News');
@ -223,7 +223,7 @@ describe('Domain Tagging Logic', () => {
mockUseDomains.mockReturnValue([mockDomains, 3]);
render(<DomainsPage />);
render(<DomainsPage/>);
// All domains should display their respective tags
expect(screen.getByTestId('domain-tag-1')).toHaveTextContent('News');

View file

@ -1,7 +1,6 @@
import React from 'react';
import {render, screen, waitFor} from '../test-utils';
import {createMockDomains, render, screen} from '../test-utils';
import {DomainsPage} from './Archive';
import {createMockDomains} from '../test-utils';
// Mock the custom hooks
jest.mock('../hooks/customHooks', () => ({
@ -54,7 +53,8 @@ describe('DomainsPage', () => {
jest.clearAllMocks();
// Default mock implementations
useTitle.mockImplementation(() => {});
useTitle.mockImplementation(() => {
});
useOneQuery.mockReturnValue(['', jest.fn()]);
});
@ -63,7 +63,7 @@ describe('DomainsPage', () => {
const mockDomains = createMockDomains(3);
useDomains.mockReturnValue([mockDomains, 3]);
render(<DomainsPage />);
render(<DomainsPage/>);
// Page should render without crashing
expect(screen.getByTestId('search-input')).toBeInTheDocument();
@ -74,7 +74,7 @@ describe('DomainsPage', () => {
const mockDomains = createMockDomains(2);
useDomains.mockReturnValue([mockDomains, 2]);
render(<DomainsPage />);
render(<DomainsPage/>);
expect(screen.getByTestId('collection-table')).toBeInTheDocument();
// Should have 6 columns defined in DOMAIN_COLUMNS
@ -85,7 +85,7 @@ describe('DomainsPage', () => {
const mockDomains = createMockDomains(1);
useDomains.mockReturnValue([mockDomains, 1]);
render(<DomainsPage />);
render(<DomainsPage/>);
const searchInput = screen.getByTestId('search-input');
expect(searchInput).toBeInTheDocument();
@ -98,7 +98,7 @@ describe('DomainsPage', () => {
const mockDomains = createMockDomains(5);
useDomains.mockReturnValue([mockDomains, 5]);
render(<DomainsPage />);
render(<DomainsPage/>);
// Should render all 5 domains
expect(screen.getByTestId('collection-count')).toHaveTextContent('5');
@ -116,7 +116,7 @@ describe('DomainsPage', () => {
];
useDomains.mockReturnValue([mockDomains, 3]);
render(<DomainsPage />);
render(<DomainsPage/>);
expect(screen.getByTestId('domain-name-1')).toHaveTextContent('example1.com');
expect(screen.getByTestId('domain-name-2')).toHaveTextContent('example2.com');
@ -127,7 +127,7 @@ describe('DomainsPage', () => {
const mockDomains = createMockDomains(3);
useDomains.mockReturnValue([mockDomains, 3]);
render(<DomainsPage />);
render(<DomainsPage/>);
// Each domain should have an Edit button
mockDomains.forEach((domain) => {
@ -139,7 +139,7 @@ describe('DomainsPage', () => {
const mockDomains = createMockDomains(1);
useDomains.mockReturnValue([mockDomains, 1]);
render(<DomainsPage />);
render(<DomainsPage/>);
const editButton = screen.getByTestId('edit-button-1');
expect(editButton).toHaveClass('ui');
@ -154,7 +154,7 @@ describe('DomainsPage', () => {
// Empty array indicates no domains
useDomains.mockReturnValue([[], 0]);
render(<DomainsPage />);
render(<DomainsPage/>);
// Should show empty state message
expect(screen.getByText(/no domains yet/i)).toBeInTheDocument();
@ -168,7 +168,7 @@ describe('DomainsPage', () => {
// undefined indicates error state
useDomains.mockReturnValue([undefined, 0]);
render(<DomainsPage />);
render(<DomainsPage/>);
// Should show error message
expect(screen.getByTestId('error-message')).toBeInTheDocument();
@ -182,7 +182,7 @@ describe('DomainsPage', () => {
const mockDomains = createMockDomains(2);
useDomains.mockReturnValue([mockDomains, 2]);
render(<DomainsPage />);
render(<DomainsPage/>);
// Domains are auto-created, so there should be no "New" button
expect(screen.queryByRole('button', {name: /new/i})).not.toBeInTheDocument();
@ -195,7 +195,7 @@ describe('DomainsPage', () => {
it('disables search when no domains', () => {
useDomains.mockReturnValue([[], 0]);
render(<DomainsPage />);
render(<DomainsPage/>);
const searchInput = screen.getByTestId('search-input');
expect(searchInput).toBeDisabled();
@ -205,7 +205,7 @@ describe('DomainsPage', () => {
const mockDomains = createMockDomains(3);
useDomains.mockReturnValue([mockDomains, 3]);
render(<DomainsPage />);
render(<DomainsPage/>);
const searchInput = screen.getByTestId('search-input');
expect(searchInput).not.toBeDisabled();
@ -218,7 +218,7 @@ describe('DomainsPage', () => {
const mockSetSearchStr = jest.fn();
useOneQuery.mockReturnValue(['example', mockSetSearchStr]);
render(<DomainsPage />);
render(<DomainsPage/>);
// Search string should be passed to table
expect(screen.getByTestId('search-filter')).toHaveTextContent('example');
@ -230,7 +230,7 @@ describe('DomainsPage', () => {
const mockDomains = createMockDomains(1);
useDomains.mockReturnValue([mockDomains, 1]);
render(<DomainsPage />);
render(<DomainsPage/>);
expect(useTitle).toHaveBeenCalledWith('Archive Domains');
});

View file

@ -38,7 +38,6 @@ import {
frequencyOptions,
weeklyOption
} from "./Vars";
import _ from "lodash";
export function DepthInputForm({form, required, name = 'depth', path = 'settings.depth'}) {
return <NumberInputForm
@ -271,7 +270,12 @@ function VideoDownloadCountLimit({form, name = 'video_count_limit', path = 'sett
/>
}
export function VideoResolutionSelectorForm({form, name = 'video_resolutions', path = 'settings.video_resolutions', onChange}) {
export function VideoResolutionSelectorForm({
form,
name = 'video_resolutions',
path = 'settings.video_resolutions',
onChange
}) {
const [inputProps, inputAttrs] = form.getSelectionProps({
name,
path,
@ -387,7 +391,14 @@ export function UseBrowserProfile({form}) {
/>
}
export function VideosDownloadForm({singleDownload = true, onCancel, onSuccess: propOnSuccess, download, submitter: propSubmitter, actions}) {
export function VideosDownloadForm({
singleDownload = true,
onCancel,
onSuccess: propOnSuccess,
download,
submitter: propSubmitter,
actions
}) {
const [showMessage, setShowMessage] = React.useState(false);
const [userChangedResolutions, setUserChangedResolutions] = React.useState(false);
const [config, setConfig] = React.useState(null);
@ -525,7 +536,8 @@ export function VideosDownloadForm({singleDownload = true, onCancel, onSuccess:
{showMessage && <SuccessfulDownloadSubmitMessage/>}
<Grid.Row>
<Grid.Column>
{actions ? actions({onCancel: localOnCancel, form}) : <DownloadFormButtons onCancel={localOnCancel} form={form}/>}
{actions ? actions({onCancel: localOnCancel, form}) :
<DownloadFormButtons onCancel={localOnCancel} form={form}/>}
</Grid.Column>
</Grid.Row>
</Grid>
@ -545,12 +557,12 @@ export function VideoMinimumDurationForm({form}) {
}
export function EditVideosDownloadForm({
download,
onCancel,
onSuccess,
onDelete,
actions = EditDownloadFormButtons,
}) {
download,
onCancel,
onSuccess,
onDelete,
actions = EditDownloadFormButtons,
}) {
const submitter = async (formData) => {
// Create a copy of settings without channel_url and channel_id
const settings = {...formData.settings};
@ -825,12 +837,12 @@ function SuccessfulDownloadSubmitMessage() {
}
export function EditArchiveDownloadForm({
download,
onCancel,
onSuccess,
onDelete,
actions = EditDownloadFormButtons,
}) {
download,
onCancel,
onSuccess,
onDelete,
actions = EditDownloadFormButtons,
}) {
const submitter = async (formData) => {
const downloadData = {
downloader: formData.downloader,
@ -907,7 +919,8 @@ export function ArchiveDownloadForm({download, onCancel, onSuccess: propOnSucces
{showMessage && <SuccessfulDownloadSubmitMessage/>}
<Grid.Row>
<Grid.Column textAlign='right'>
{actions ? actions({onCancel: localOnCancel, form}) : <DownloadFormButtons onCancel={localOnCancel} form={form}/>}
{actions ? actions({onCancel: localOnCancel, form}) :
<DownloadFormButtons onCancel={localOnCancel} form={form}/>}
</Grid.Column>
</Grid.Row>
</Grid>

View file

@ -34,7 +34,7 @@ describe('DestinationForm', () => {
{overrides: {ready: true, loading: false}}
);
render(<DestinationForm form={form} />);
render(<DestinationForm form={form}/>);
const input = screen.getByTestId('directory-search-input');
expect(input).toHaveValue('videos/test');
@ -46,7 +46,7 @@ describe('DestinationForm', () => {
{overrides: {ready: true, loading: false}}
);
render(<DestinationForm form={form} />);
render(<DestinationForm form={form}/>);
const input = screen.getByTestId('directory-search-input');
@ -66,7 +66,7 @@ describe('DestinationForm', () => {
{overrides: {ready: true, loading: false}}
);
render(<DestinationForm form={form} required />);
render(<DestinationForm form={form} required/>);
const input = screen.getByTestId('directory-search-input');
expect(input).toHaveAttribute('required');
@ -80,7 +80,7 @@ describe('DestinationForm', () => {
{overrides: {ready: true, loading: false}}
);
render(<DestinationForm form={form} label="Custom Folder" />);
render(<DestinationForm form={form} label="Custom Folder"/>);
expect(screen.getByText(/custom folder/i)).toBeInTheDocument();
});
@ -91,7 +91,7 @@ describe('DestinationForm', () => {
{overrides: {ready: true, loading: false}}
);
render(<DestinationForm form={form} />);
render(<DestinationForm form={form}/>);
expect(screen.getByText(/destination/i)).toBeInTheDocument();
});
@ -140,7 +140,7 @@ describe('DestinationForm', () => {
const getCustomPropsSpy = jest.spyOn(form, 'getCustomProps');
render(<DestinationForm form={form} required />);
render(<DestinationForm form={form} required/>);
expect(getCustomPropsSpy).toHaveBeenCalledWith({
name: 'destination',
@ -155,7 +155,7 @@ describe('DestinationForm', () => {
{overrides: {ready: true, loading: false}}
);
render(<DestinationForm form={form} />);
render(<DestinationForm form={form}/>);
const input = screen.getByTestId('directory-search-input');
@ -196,7 +196,7 @@ describe('DestinationForm', () => {
{overrides: {ready: true, loading: false}}
);
render(<DestinationForm form={form} />);
render(<DestinationForm form={form}/>);
const input = screen.getByTestId('directory-search-input');
@ -220,7 +220,7 @@ describe('DestinationForm', () => {
{overrides: {ready: true, loading: false}}
);
render(<DestinationForm form={form} />);
render(<DestinationForm form={form}/>);
const input = screen.getByTestId('directory-search-input');
expect(input).toHaveValue('');
@ -232,7 +232,7 @@ describe('DestinationForm', () => {
{overrides: {ready: true, loading: false}}
);
render(<DestinationForm form={form} />);
render(<DestinationForm form={form}/>);
const input = screen.getByTestId('directory-search-input');
expect(input).toHaveValue('');
@ -244,7 +244,7 @@ describe('DestinationForm', () => {
{overrides: {ready: true, loading: false}}
);
render(<DestinationForm form={form} />);
render(<DestinationForm form={form}/>);
const input = screen.getByTestId('directory-search-input');
expect(input).toHaveValue('');

View file

@ -3,10 +3,10 @@ import {
APIButton,
ErrorMessage,
HandPointMessage,
InfoPopup,
humanFileSize,
IframeViewer,
InfoMessage,
InfoPopup,
PageContainer,
TabLinks,
useTitle,

View file

@ -126,10 +126,10 @@ export function Upload({disabled}) {
<Grid.Row columns={1}>
<Grid.Column>
{progresses && Object.keys(progresses).length > 1 && <Progress progress
percent={overallProgress}
color='blue'
label='Overall Progress'
/>}
percent={overallProgress}
color='blue'
label='Overall Progress'
/>}
</Grid.Column>
</Grid.Row>
</Grid>

View file

@ -18,7 +18,7 @@ import {
import Grid from "semantic-ui-react/dist/commonjs/collections/Grid";
import Container from "semantic-ui-react/dist/commonjs/elements/Container";
import {VideoPlaceholder} from "./Placeholder";
import {useChannel, useVideoCaptions, useVideoExtras} from "../hooks/customHooks";
import {useChannel, useVideoExtras} from "../hooks/customHooks";
import {ThemeContext} from "../contexts/contexts";
import {Button, darkTheme, Header, Icon, Segment, Tab, TabPane} from "./Theme";
import {VideoCard} from "./Videos";

View file

@ -45,7 +45,13 @@ import {FileRowTagIcon, FilesView} from "./Files";
import Grid from "semantic-ui-react/dist/commonjs/collections/Grid";
import Icon from "semantic-ui-react/dist/commonjs/elements/Icon";
import {Button, Card, Header, Loader, Placeholder, Popup, Segment, Statistic, StatisticGroup} from "./Theme";
import {deleteVideos, fetchBrowserProfiles, fetchVideoDownloaderConfig, postVideoFileFormat, updateVideoDownloaderConfig} from "../api";
import {
deleteVideos,
fetchBrowserProfiles,
fetchVideoDownloaderConfig,
postVideoFileFormat,
updateVideoDownloaderConfig
} from "../api";
import {Media, QueryContext, ThemeContext} from "../contexts/contexts";
import _ from "lodash";
import {defaultFileOrder, defaultSearchOrder, HELP_VIEWER_URI} from "./Vars";

View file

@ -1,5 +1,5 @@
import React from "react";
import {ThemeContext} from "../../contexts/contexts";
import {SettingsContext, StatusContext} from "../../contexts/contexts";
import {checkUpgrade, postRestart, postShutdown, triggerUpgrade} from "../../api";
import {
Button,
@ -31,7 +31,6 @@ import QRCode from "react-qr-code";
import {useConfigs, useDockerized} from "../../hooks/customHooks";
import {toast} from "react-semantic-toasts-2";
import Grid from "semantic-ui-react/dist/commonjs/collections/Grid";
import {SettingsContext, StatusContext} from "../../contexts/contexts";
import {ConfigsTable} from "./Configs";
import {semanticUIColorMap} from "../Vars";
@ -134,13 +133,14 @@ function UpgradeSegment() {
return <Segment>
<Header as='h3'>System Upgrade</Header>
<p>Your WROLPi is up to date.</p>
<p>Version: <strong>v{status?.version}</strong> on branch <strong>{status?.git_branch || 'unknown'}</strong></p>
<p>Version: <strong>v{status?.version}</strong> on branch <strong>{status?.git_branch || 'unknown'}</strong>
</p>
<APIButton
color='blue'
onClick={handleCheckUpgrade}
disabled={checking}
>
{checking ? 'Checking...' : 'Check for Updates'}
{checking ? 'Checking...' : 'Check for Upgrades'}
</APIButton>
</Segment>;
}

View file

@ -1,6 +1,6 @@
import {Accordion, Header, Progress, Segment, Statistic, StatisticGroup, Table} from "../Theme";
import React, {useContext} from "react";
import {InfoHeader, humanBandwidth, humanFileSize, LoadStatistic, useTitle} from "../Common";
import {humanBandwidth, humanFileSize, InfoHeader, LoadStatistic, useTitle} from "../Common";
import {ProgressPlaceholder} from "../Placeholder";
import Grid from "semantic-ui-react/dist/commonjs/collections/Grid";
import {Media, SettingsContext, StatusContext, ThemeContext} from "../../contexts/contexts";

View file

@ -17,15 +17,15 @@ import {WROLModeMessage} from '../Common';
* @param {React.ReactNode} children - Form fields to render
*/
export function CollectionEditForm({
form,
onCancel,
onSubmit,
title,
wrolModeContent,
actionButtons,
appliedTagName,
children
}) {
form,
onCancel,
onSubmit,
title,
wrolModeContent,
actionButtons,
appliedTagName,
children
}) {
const {SingleTag} = React.useContext(TagsContext);
const handleSubmit = (e) => {

View file

@ -1,7 +1,14 @@
import React from 'react';
import {render, renderInDarkMode, renderInLightMode, hasInvertedStyling, screen, createTestForm} from '../../test-utils';
import {
createMockDomain,
createTestForm,
hasInvertedStyling,
render,
renderInDarkMode,
renderInLightMode,
screen
} from '../../test-utils';
import {CollectionEditForm} from './CollectionEditForm';
import {createMockDomain} from '../../test-utils';
// Mock the TagsContext
jest.mock('../../Tags', () => ({

View file

@ -3,8 +3,8 @@ import {Link} from 'react-router-dom';
import {Message, Placeholder, PlaceholderHeader, PlaceholderLine, Table, TableCell, TableRow} from 'semantic-ui-react';
import _ from 'lodash';
import {SortableTable} from '../SortableTable';
import {humanFileSize, formatFrequency} from '../Common';
import {ThemeContext, Media} from '../../contexts/contexts';
import {formatFrequency, humanFileSize} from '../Common';
import {Media, ThemeContext} from '../../contexts/contexts';
import {TagsContext} from '../../Tags';
/**
@ -78,7 +78,7 @@ function renderRow(collection, columns, routes, inverted, SingleTag, onRowClick)
// Special handling for tag_name column - render SingleTag component
if (col.key === 'tag_name' && value) {
value = <SingleTag name={value} />;
value = <SingleTag name={value}/>;
}
// Special handling for the primary column (usually domain/name)
@ -156,7 +156,14 @@ function MobileCollectionRow({collection, mobileColumns, routes}) {
* @param {Function} onRowClick - Optional callback when a row is clicked
* @param {String} emptyMessage - Message to display when there are no collections
*/
export function CollectionTable({collections, columns, routes = {}, searchStr = '', onRowClick, emptyMessage = 'No items yet'}) {
export function CollectionTable({
collections,
columns,
routes = {},
searchStr = '',
onRowClick,
emptyMessage = 'No items yet'
}) {
const {inverted} = useContext(ThemeContext);
const {SingleTag} = useContext(TagsContext);
@ -238,7 +245,8 @@ export function CollectionTable({collections, columns, routes = {}, searchStr =
<SortableTable
tableProps={{striped: true, size: 'small', unstackable: true}}
data={filteredCollections}
rowFunc={(collection) => <MobileCollectionRow key={collection.id} collection={collection} mobileColumns={mobileColumns} routes={routes}/>}
rowFunc={(collection) => <MobileCollectionRow key={collection.id} collection={collection}
mobileColumns={mobileColumns} routes={routes}/>}
rowKey='id'
tableHeaders={mobileHeaders}
defaultSortColumn={defaultSortColumn}

View file

@ -1,7 +1,6 @@
import React from 'react';
import {render, screen, renderInDarkMode, renderInLightMode, hasInvertedStyling} from '../../test-utils';
import {createMockDomains, render, screen} from '../../test-utils';
import {CollectionTable} from './CollectionTable';
import {createMockDomains} from '../../test-utils';
// Mock the TagsContext
jest.mock('../../Tags', () => ({
@ -32,14 +31,14 @@ jest.mock('../SortableTable', () => ({
SortableTable: ({data, rowFunc, tableHeaders}) => (
<table data-testid="sortable-table">
<thead>
<tr>
{tableHeaders.map(h => (
<th key={h.key} data-width={h.width}>{h.text}</th>
))}
</tr>
<tr>
{tableHeaders.map(h => (
<th key={h.key} data-width={h.width}>{h.text}</th>
))}
</tr>
</thead>
<tbody>
{data.map(item => rowFunc(item))}
{data.map(item => rowFunc(item))}
</tbody>
</table>
),

View file

@ -1,4 +1,4 @@
import React, {useState, useEffect, useCallback} from 'react';
import React, {useCallback, useEffect, useState} from 'react';
import {Grid, Input} from 'semantic-ui-react';
import Message from 'semantic-ui-react/dist/commonjs/collections/Message';
import {Button, Modal, ModalActions, ModalContent, ModalHeader} from '../Theme';
@ -20,15 +20,15 @@ import {APIButton, Toggle} from '../Common';
* When false, hides directory toggle and input, always passes null for directory
*/
export function CollectionTagModal({
open,
onClose,
currentTagName,
originalDirectory,
getTagInfo,
onSave,
collectionName = 'Collection',
hasDirectory = true,
}) {
open,
onClose,
currentTagName,
originalDirectory,
getTagInfo,
onSave,
collectionName = 'Collection',
hasDirectory = true,
}) {
const [newTagName, setNewTagName] = useState(currentTagName || null);
const [moveToTagDirectory, setMoveToTagDirectory] = useState(true);
const [newTagDirectory, setNewTagDirectory] = useState(originalDirectory || '');

View file

@ -1,5 +1,5 @@
import React from 'react';
import {render, screen, waitFor, act} from '../../test-utils';
import {act, render, screen, waitFor} from '../../test-utils';
import userEvent from '@testing-library/user-event';
import {CollectionTagModal} from './CollectionTagModal';
@ -75,17 +75,17 @@ describe('CollectionTagModal', () => {
});
it('does not render modal when open is false', () => {
render(<CollectionTagModal {...defaultProps} open={false} />);
render(<CollectionTagModal {...defaultProps} open={false}/>);
expect(screen.queryByTestId('modal')).not.toBeInTheDocument();
});
it('shows "Add Tag" header when no current tag', () => {
render(<CollectionTagModal {...defaultProps} currentTagName={null} />);
render(<CollectionTagModal {...defaultProps} currentTagName={null}/>);
expect(screen.getByTestId('modal-header')).toHaveTextContent('Add Tag');
});
it('shows "Modify Tag" header when there is a current tag', () => {
render(<CollectionTagModal {...defaultProps} currentTagName="existing-tag" />);
render(<CollectionTagModal {...defaultProps} currentTagName="existing-tag"/>);
expect(screen.getByTestId('modal-header')).toHaveTextContent('Modify Tag');
});
});
@ -122,7 +122,7 @@ describe('CollectionTagModal', () => {
conflict_message: null,
});
render(<CollectionTagModal {...defaultProps} getTagInfo={mockGetTagInfo} />);
render(<CollectionTagModal {...defaultProps} getTagInfo={mockGetTagInfo}/>);
const addTagButton = screen.getByTestId('add-tag');
await userEvent.click(addTagButton);
@ -143,7 +143,7 @@ describe('CollectionTagModal', () => {
conflict_message: null,
});
render(<CollectionTagModal {...defaultProps} getTagInfo={mockGetTagInfo} />);
render(<CollectionTagModal {...defaultProps} getTagInfo={mockGetTagInfo}/>);
const addTagButton = screen.getByTestId('add-tag');
await userEvent.click(addTagButton);
@ -157,7 +157,7 @@ describe('CollectionTagModal', () => {
it('handles legacy string format from tag info', async () => {
const mockGetTagInfo = jest.fn().mockResolvedValue('/legacy/directory');
render(<CollectionTagModal {...defaultProps} getTagInfo={mockGetTagInfo} />);
render(<CollectionTagModal {...defaultProps} getTagInfo={mockGetTagInfo}/>);
const addTagButton = screen.getByTestId('add-tag');
await userEvent.click(addTagButton);
@ -171,7 +171,7 @@ describe('CollectionTagModal', () => {
it('fetches tag info when tag is removed', async () => {
const mockGetTagInfo = jest.fn().mockResolvedValue(null);
render(<CollectionTagModal {...defaultProps} getTagInfo={mockGetTagInfo} currentTagName="existing-tag" />);
render(<CollectionTagModal {...defaultProps} getTagInfo={mockGetTagInfo} currentTagName="existing-tag"/>);
const removeTagButton = screen.getByTestId('remove-tag');
await userEvent.click(removeTagButton);
@ -192,7 +192,7 @@ describe('CollectionTagModal', () => {
conflict_message: null,
});
render(<CollectionTagModal {...defaultProps} getTagInfo={mockGetTagInfo} currentTagName="existing-tag" />);
render(<CollectionTagModal {...defaultProps} getTagInfo={mockGetTagInfo} currentTagName="existing-tag"/>);
const removeTagButton = screen.getByTestId('remove-tag');
await userEvent.click(removeTagButton);
@ -206,7 +206,8 @@ describe('CollectionTagModal', () => {
it('resets to original directory when tag is removed and no suggestion', async () => {
const mockGetTagInfo = jest.fn().mockResolvedValue(null);
render(<CollectionTagModal {...defaultProps} getTagInfo={mockGetTagInfo} originalDirectory="/original/path" />);
render(<CollectionTagModal {...defaultProps} getTagInfo={mockGetTagInfo}
originalDirectory="/original/path"/>);
// First add a tag - wait for async to complete including state updates
const addTagButton = screen.getByTestId('add-tag');
@ -244,7 +245,7 @@ describe('CollectionTagModal', () => {
conflict_message: 'Directory already in use',
});
render(<CollectionTagModal {...defaultProps} getTagInfo={mockGetTagInfo} />);
render(<CollectionTagModal {...defaultProps} getTagInfo={mockGetTagInfo}/>);
const addTagButton = screen.getByTestId('add-tag');
await userEvent.click(addTagButton);
@ -272,7 +273,7 @@ describe('CollectionTagModal', () => {
conflict_message: null,
});
render(<CollectionTagModal {...defaultProps} getTagInfo={mockGetTagInfo} />);
render(<CollectionTagModal {...defaultProps} getTagInfo={mockGetTagInfo}/>);
// Add first tag - shows conflict
const addTagButton = screen.getByTestId('add-tag');
@ -300,7 +301,7 @@ describe('CollectionTagModal', () => {
describe('Modal Close Behavior', () => {
it('calls onClose when cancel button is clicked', async () => {
const mockOnClose = jest.fn();
render(<CollectionTagModal {...defaultProps} onClose={mockOnClose} />);
render(<CollectionTagModal {...defaultProps} onClose={mockOnClose}/>);
const cancelButton = screen.getByTestId('button-Cancel');
await userEvent.click(cancelButton);
@ -603,7 +604,7 @@ describe('CollectionTagModal', () => {
await waitFor(() => {
const input = screen.getByRole('textbox');
expect(input).toHaveValue('/videos/wrolpi.org');
}, { timeout: 500 });
}, {timeout: 500});
// Click Move button
await act(async () => {

View file

@ -9,7 +9,6 @@ import {
filesSearch,
getArchive,
getChannel,
getChannels,
getConfigs,
getDomain,
getDownloads,

View file

@ -1,7 +1,14 @@
import React from 'react';
import {renderHook, act, waitFor} from '@testing-library/react';
import {render, screen, fireEvent} from '@testing-library/react';
import {useForm, commaSeparatedValidator, InputForm, NumberInputForm, UrlInput, ToggleForm, UrlsTextarea} from './useForm';
import {act, renderHook, screen, waitFor} from '@testing-library/react';
import {
commaSeparatedValidator,
InputForm,
NumberInputForm,
ToggleForm,
UrlInput,
UrlsTextarea,
useForm
} from './useForm';
import {renderWithProviders} from '../test-utils';
// Mock lodash debounce to control timing in tests

View file

@ -29,13 +29,21 @@ Object.defineProperty(window, 'matchMedia', {
// Mock IntersectionObserver (if needed for lazy loading)
global.IntersectionObserver = class IntersectionObserver {
constructor() {}
disconnect() {}
observe() {}
constructor() {
}
disconnect() {
}
observe() {
}
takeRecords() {
return [];
}
unobserve() {}
unobserve() {
}
};
// Suppress console errors during tests (optional - uncomment if needed)

View file

@ -131,7 +131,8 @@ export function mockFetchError(error = 'An error occurred', status = 400) {
*/
export async function waitForLoadingToFinish() {
const {waitFor} = await import('@testing-library/react');
await waitFor(() => {}, {timeout: 100});
await waitFor(() => {
}, {timeout: 100});
}
/**

View file

@ -26,9 +26,9 @@ from wrolpi.common import get_media_directory, get_relative_to_media_directory,
from wrolpi.dates import now, Seconds
from wrolpi.db import get_db_session, get_db_curs, optional_session
from wrolpi.errors import UnknownArchive, InvalidOrderBy, InvalidDatetime
from wrolpi.events import Events
from wrolpi.files.lib import handle_file_group_search_results
from wrolpi.files.models import FileGroup
from wrolpi.events import Events
from wrolpi.switches import register_switch_handler, ActivateSwitchMethod
from wrolpi.tags import tag_append_sub_select_where
from wrolpi.vars import PYTEST, DOCKERIZED

View file

@ -84,7 +84,8 @@ async def test_model_archive_sets_collection_id(async_client, test_session, test
@pytest.mark.asyncio
async def test_model_archive_extracts_url_from_singlefile(async_client, test_session, test_directory, make_files_structure):
async def test_model_archive_extracts_url_from_singlefile(async_client, test_session, test_directory,
make_files_structure):
"""
Test that model_archive() can extract URL from singlefile when file_group.url is None.

View file

@ -593,7 +593,8 @@ async def test_archive_meta(async_client, test_session, make_files_structure):
@pytest.mark.asyncio
async def test_refresh_archives_deleted_singlefile(async_client, test_session, make_files_structure, singlefile_contents_factory):
async def test_refresh_archives_deleted_singlefile(async_client, test_session, make_files_structure,
singlefile_contents_factory):
"""Removing a Singlefile file from a FileGroup makes that group no longer an Archive."""
singlefile, readability = make_files_structure({
'2022-09-04-16-20-11_The Title.html': singlefile_contents_factory(),
@ -923,7 +924,8 @@ def test_detect_domain_directory_no_archives(test_directory, test_session):
@pytest.mark.asyncio
async def test_get_or_create_domain_collection_auto_detects_directory(async_client, test_directory, test_session, archive_factory):
async def test_get_or_create_domain_collection_auto_detects_directory(async_client, test_directory, test_session,
archive_factory):
"""get_or_create_domain_collection should auto-detect directory for existing archives."""
from modules.archive.lib import get_or_create_domain_collection
@ -1075,4 +1077,4 @@ def test_link_domain_and_downloads(test_session, test_download_manager):
assert download1.collection_id == collection.id # matched by directory (exact)
assert download2.collection_id == collection.id # matched by subdirectory
assert download3.collection_id == collection.id # matched by URL domain
assert download4.collection_id is None # no frequency = no link
assert download4.collection_id is None # no frequency = no link

View file

@ -59,5 +59,3 @@ class Inventory(Base, ModelHelper):
@staticmethod
def find_by_name(session: Session, name: str) -> 'Inventory':
return session.query(Inventory).filter_by(name=name).one()

View file

@ -111,12 +111,12 @@ def claim_videos_for_channels(channel_ids: List[int]):
with get_db_curs(commit=True) as curs:
# Note: %% is escaped to % in psycopg2 when parameters are used
curs.execute('''
UPDATE video v
SET channel_id = c.id
FROM channel c
INNER JOIN collection col ON col.id = c.collection_id
LEFT JOIN file_group fg ON fg.primary_path LIKE col.directory || '/%%'::VARCHAR
WHERE v.channel_id IS NULL
AND fg.id = v.file_group_id
AND c.id = ANY(%s)
''', (list(channel_ids),))
UPDATE video v
SET channel_id = c.id
FROM channel c
INNER JOIN collection col ON col.id = c.collection_id
LEFT JOIN file_group fg ON fg.primary_path LIKE col.directory || '/%%'::VARCHAR
WHERE v.channel_id IS NULL
AND fg.id = v.file_group_id
AND c.id = ANY (%s)
''', (list(channel_ids),))

View file

@ -12,12 +12,10 @@ from wrolpi.captions import read_captions
from wrolpi.common import Base, ModelHelper, logger, get_media_directory, background_task, replace_file, \
unique_by_predicate
from wrolpi.db import get_db_curs, get_db_session, optional_session
from wrolpi.downloader import Download, download_manager, save_downloads_config
from wrolpi.errors import InvalidDownload
from wrolpi.downloader import Download, save_downloads_config
from wrolpi.events import Events
from wrolpi.files.lib import refresh_files, split_path_stem_and_suffix, move
from wrolpi.files.models import FileGroup
from wrolpi.media_path import MediaPathType
from wrolpi.tags import Tag, TagFile, save_tags_config
from wrolpi.vars import PYTEST, VIDEO_INFO_JSON_KEYS_TO_CLEAN

View file

@ -68,7 +68,7 @@ class TestChannelsConfigUpgrade:
"""Tests for upgrade scenarios where config file exists."""
async def test_upgrade_config_exists_with_data(self, test_session, test_directory, async_client,
test_channels_config, channel_factory):
test_channels_config, channel_factory):
"""
Upgrade with existing config containing channel data.
Should import and sync DB with config.
@ -94,7 +94,7 @@ class TestChannelsConfigUpgrade:
assert channels[0].name == 'Config Channel'
async def test_upgrade_config_exists_empty_list(self, test_session, test_directory, async_client,
test_channels_config, channel_factory):
test_channels_config, channel_factory):
"""
Config exists but has empty channels list.
Should NOT delete existing DB channels (never delete on empty).
@ -123,7 +123,7 @@ class TestChannelsConfigUpgrade:
assert channels[0].name == 'Should Not Delete'
async def test_upgrade_config_missing_db_has_data(self, test_session, test_directory, async_client,
test_channels_config, channel_factory):
test_channels_config, channel_factory):
"""
Config file missing but DB has channels.
Import should succeed (nothing to import), DB data preserved.
@ -157,7 +157,7 @@ class TestChannelsConfigEdgeCases:
"""Tests for edge cases in config import."""
async def test_config_deletes_removed_items(self, test_session, test_directory, async_client, test_channels_config,
channel_factory):
channel_factory):
"""
Config removes a channel that exists in DB.
Should delete the channel from DB.
@ -233,7 +233,7 @@ class TestChannelsConfigEdgeCases:
assert channels[0].url == 'https://example.com/new'
async def test_config_updates_existing_items(self, test_session, test_directory, async_client, test_channels_config,
channel_factory):
channel_factory):
"""
Config updates an existing channel's URL.
Should update the channel in DB.

View file

@ -9,7 +9,7 @@ from modules.zim.errors import UnknownZim, UnknownZimEntry
from modules.zim.models import TagZimEntry, ZimSubscription
from wrolpi import tags, flags
from wrolpi.common import DownloadFileInfo, get_wrolpi_config
from wrolpi.downloader import Download, import_downloads_config, save_downloads_config, get_download_manager_config
from wrolpi.downloader import Download, import_downloads_config, get_download_manager_config
from wrolpi.files import lib as files_lib
from wrolpi.files.models import FileGroup
from wrolpi.test.common import skip_circleci

View file

@ -10,7 +10,7 @@ from typing import List, Optional, Dict
from sqlalchemy import func
from sqlalchemy.orm import Session
from wrolpi.common import logger, get_media_directory, get_relative_to_media_directory
from wrolpi.common import logger, get_relative_to_media_directory
from wrolpi.db import get_db_session, optional_session
from wrolpi.errors import ValidationError
from wrolpi.events import Events

View file

@ -320,8 +320,10 @@ class TestCollectionDeletion:
test_session.flush()
# Create file groups and archives for this domain
fg1 = FileGroup(primary_path=test_directory / 'archive' / 'example.com' / 'page1.html', url='https://example.com/page1')
fg2 = FileGroup(primary_path=test_directory / 'archive' / 'example.com' / 'page2.html', url='https://example.com/page2')
fg1 = FileGroup(primary_path=test_directory / 'archive' / 'example.com' / 'page1.html',
url='https://example.com/page1')
fg2 = FileGroup(primary_path=test_directory / 'archive' / 'example.com' / 'page2.html',
url='https://example.com/page2')
test_session.add_all([fg1, fg2])
test_session.flush()

View file

@ -10,7 +10,8 @@ from wrolpi.common import get_media_directory
@pytest.mark.asyncio
async def test_collection_lifecycle_end_to_end(async_client, test_session: Session, test_directory: pathlib.Path, video_factory):
async def test_collection_lifecycle_end_to_end(async_client, test_session: Session, test_directory: pathlib.Path,
video_factory):
"""
Lifecycle:
- Start with no collections

View file

@ -1,5 +1,4 @@
import pathlib
import pathlib
import pytest
import yaml
@ -171,7 +170,8 @@ def test_set_tag_on_directory_less_domain_collection(test_session):
@pytest.mark.asyncio
async def test_tag_collection_removes_tag_and_updates_directory(test_session, test_directory, tag_factory, await_switches):
async def test_tag_collection_removes_tag_and_updates_directory(test_session, test_directory, tag_factory,
await_switches):
"""When removing a tag via tag_collection, the directory should be updated if provided."""
from wrolpi.collections.lib import tag_collection

View file

@ -1,3 +1,5 @@
import sanic.request
import pathlib
from http import HTTPStatus
@ -18,6 +20,7 @@ from ..vars import PYTEST
import pathlib
from http import HTTPStatus
import sanic.request
import sanic.request
from sanic import response, Request, Blueprint
from sanic_ext import validate

View file

@ -1,7 +1,5 @@
"""Tests for shared context initialization."""
import pytest
def test_domains_config_in_shared_context():
"""Verify domains_config is initialized in shared context.

View file

@ -16,7 +16,8 @@ from wrolpi.downloader import Download, get_download_manager_config
class TestDownloadManagerConfigOnboarding:
"""Tests for new install scenarios where no config file exists."""
async def test_new_install_no_db_data(self, test_session, test_directory, async_client, test_download_manager_config):
async def test_new_install_no_db_data(self, test_session, test_directory, async_client,
test_download_manager_config):
"""
New install with empty DB and no config file.
Should succeed with empty config.
@ -73,7 +74,7 @@ class TestDownloadManagerConfigUpgrade:
"""Tests for upgrade scenarios where config file exists."""
async def test_upgrade_config_exists_with_data(self, test_session, test_directory, async_client,
test_download_manager_config):
test_download_manager_config):
"""
Upgrade with existing config containing download data.
Should import and sync DB with config.
@ -123,7 +124,7 @@ class TestDownloadManagerConfigUpgrade:
assert downloads[0].url == 'https://example.com/download'
async def test_upgrade_config_exists_empty_list(self, test_session, test_directory, async_client,
test_download_manager_config):
test_download_manager_config):
"""
Config exists but has empty downloads list.
Should NOT delete existing DB downloads (never delete on empty).
@ -159,7 +160,7 @@ class TestDownloadManagerConfigUpgrade:
assert downloads[0].url == 'https://example.com/preserve'
async def test_upgrade_config_missing_db_has_data(self, test_session, test_directory, async_client,
test_download_manager_config):
test_download_manager_config):
"""
Config file missing but DB has downloads.
Import should succeed (nothing to import), DB data preserved.
@ -199,7 +200,7 @@ class TestDownloadManagerConfigEdgeCases:
"""Tests for edge cases in config import."""
async def test_config_deletes_removed_items(self, test_session, test_directory, async_client,
test_download_manager_config):
test_download_manager_config):
"""
Config removes a download that exists in DB.
Should delete the download from DB.

View file

@ -1,9 +1,10 @@
"""
Tests for the WROLPi upgrade system.
"""
import pytest
from unittest.mock import patch, MagicMock
import pytest
from wrolpi.upgrade import (
check_for_update,
get_current_branch,