mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-23 03:19:41 +00:00
Merge pull request #3342 from xinnan-tech/test-infrastructure
test: 新增三语测试基建(Python/Java/Vue)+ CI
This commit is contained in:
commit
27e780e4c1
28 changed files with 4284 additions and 52 deletions
66
.github/workflows/test.yml
vendored
Normal file
66
.github/workflows/test.yml
vendored
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
name: Tests
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
python:
|
||||
name: Python (xiaozhi-server)
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.10'
|
||||
cache: 'pip'
|
||||
cache-dependency-path: 'main/xiaozhi-server/requirements.txt'
|
||||
- name: Install dependencies
|
||||
working-directory: main/xiaozhi-server
|
||||
run: |
|
||||
pip install -r requirements.txt
|
||||
pip install pytest pytest-asyncio freezegun
|
||||
- name: Run smoke test
|
||||
working-directory: main/xiaozhi-server
|
||||
run: |
|
||||
if [ -f tests/test_smoke.py ]; then
|
||||
pytest tests/test_smoke.py -x -q
|
||||
else
|
||||
echo "::warning::Slice 2 not done yet — tests/test_smoke.py missing"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
java:
|
||||
name: Java (manager-api)
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: 'temurin'
|
||||
java-version: '21'
|
||||
cache: 'maven'
|
||||
- name: Run tests
|
||||
working-directory: main/manager-api
|
||||
run: mvn -B -q test -DfailIfNoTests=false
|
||||
|
||||
web:
|
||||
name: Vue (manager-web)
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
cache: 'npm'
|
||||
cache-dependency-path: main/manager-web/package-lock.json
|
||||
- name: Run tests
|
||||
working-directory: main/manager-web
|
||||
run: |
|
||||
npm ci --no-audit --no-fund
|
||||
npm run test:unit
|
||||
21
Makefile
Normal file
21
Makefile
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
.PHONY: test test-fast test-python test-java test-web help
|
||||
|
||||
help:
|
||||
@echo "make test-fast - run all fast unit tests (default)"
|
||||
@echo "make test - alias for test-fast"
|
||||
@echo "make test-python - pytest in main/xiaozhi-server"
|
||||
@echo "make test-java - mvn test in main/manager-api"
|
||||
@echo "make test-web - npm run test:unit in main/manager-web"
|
||||
|
||||
test: test-fast
|
||||
|
||||
test-fast: test-python test-java test-web
|
||||
|
||||
test-python:
|
||||
cd main/xiaozhi-server && python -m pytest -x -q
|
||||
|
||||
test-java:
|
||||
cd main/manager-api && mvn -B -q test -DfailIfNoTests=false
|
||||
|
||||
test-web:
|
||||
cd main/manager-web && npm ci --no-audit --no-fund && npm test
|
||||
|
|
@ -0,0 +1,83 @@
|
|||
package xiaozhi.common.utils;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import cn.hutool.json.JSONObject;
|
||||
|
||||
class SensitiveDataUtilsTest {
|
||||
|
||||
@Test
|
||||
void isSensitiveField_recognizes_known_field_names() {
|
||||
assertTrue(SensitiveDataUtils.isSensitiveField("api_key"));
|
||||
assertTrue(SensitiveDataUtils.isSensitiveField("API_KEY"));
|
||||
assertTrue(SensitiveDataUtils.isSensitiveField("personal_access_token"));
|
||||
assertTrue(SensitiveDataUtils.isSensitiveField("secret"));
|
||||
assertTrue(SensitiveDataUtils.isSensitiveField("secret_key"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void isSensitiveField_rejects_blank_and_unknown_field_names() {
|
||||
assertFalse(SensitiveDataUtils.isSensitiveField(""));
|
||||
assertFalse(SensitiveDataUtils.isSensitiveField(" "));
|
||||
assertFalse(SensitiveDataUtils.isSensitiveField(null));
|
||||
assertFalse(SensitiveDataUtils.isSensitiveField("not_a_secret"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void maskMiddle_returns_input_unchanged_for_short_or_blank_values() {
|
||||
assertNull(SensitiveDataUtils.maskMiddle(null));
|
||||
assertEquals("", SensitiveDataUtils.maskMiddle(""));
|
||||
assertEquals("a", SensitiveDataUtils.maskMiddle("a"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void maskMiddle_keeps_two_at_each_end_for_short_strings() {
|
||||
assertEquals("ab****yz", SensitiveDataUtils.maskMiddle("abcdefyz"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void maskMiddle_keeps_four_at_each_end_for_long_strings() {
|
||||
String masked = SensitiveDataUtils.maskMiddle("verylongapikeyvalue123");
|
||||
assertTrue(masked.startsWith("very"));
|
||||
assertTrue(masked.endsWith("3123"));
|
||||
assertTrue(masked.contains("****"));
|
||||
assertEquals("verylongapikeyvalue123".length(), masked.length());
|
||||
}
|
||||
|
||||
@Test
|
||||
void isMaskedValue_detects_masked_values() {
|
||||
assertTrue(SensitiveDataUtils.isMaskedValue("ab****yz"));
|
||||
assertTrue(SensitiveDataUtils.isMaskedValue("abc****def****ghi"));
|
||||
assertFalse(SensitiveDataUtils.isMaskedValue("plainstring"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void isMaskedValue_rejects_blank_values() {
|
||||
assertFalse(SensitiveDataUtils.isMaskedValue(null));
|
||||
assertFalse(SensitiveDataUtils.isMaskedValue(""));
|
||||
assertFalse(SensitiveDataUtils.isMaskedValue(" "));
|
||||
}
|
||||
|
||||
@Test
|
||||
void maskSensitiveFields_masks_known_sensitive_keys_only() {
|
||||
JSONObject source = new JSONObject();
|
||||
source.set("api_key", "sk-supersecretapikey");
|
||||
source.set("name", "alice");
|
||||
|
||||
JSONObject masked = SensitiveDataUtils.maskSensitiveFields(source);
|
||||
|
||||
String apiKey = (String) masked.get("api_key");
|
||||
assertTrue(apiKey.contains("****"));
|
||||
assertEquals("alice", masked.get("name"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void maskSensitiveFields_returns_null_when_input_is_null() {
|
||||
assertNull(SensitiveDataUtils.maskSensitiveFields(null));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,148 @@
|
|||
package xiaozhi.modules.correctword.service.impl;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
|
||||
import xiaozhi.modules.agent.dao.AgentCorrectWordMappingDao;
|
||||
import xiaozhi.modules.agent.entity.AgentCorrectWordMappingEntity;
|
||||
import xiaozhi.modules.correctword.dao.CorrectWordFileDao;
|
||||
import xiaozhi.modules.correctword.dao.CorrectWordItemDao;
|
||||
import xiaozhi.modules.correctword.entity.CorrectWordFileEntity;
|
||||
import xiaozhi.modules.correctword.entity.CorrectWordItemEntity;
|
||||
import xiaozhi.modules.correctword.vo.CorrectWordFileVO;
|
||||
import xiaozhi.modules.correctword.vo.CorrectWordSimpleVO;
|
||||
|
||||
class CorrectWordFileServiceImplTest {
|
||||
|
||||
private static final String AGENT_ID = "agent-1";
|
||||
private static final String FILE_ID = "file-1";
|
||||
|
||||
private final CorrectWordFileDao fileDao = mock(CorrectWordFileDao.class);
|
||||
private final CorrectWordItemDao itemDao = mock(CorrectWordItemDao.class);
|
||||
private final AgentCorrectWordMappingDao mappingDao = mock(AgentCorrectWordMappingDao.class);
|
||||
private final CorrectWordFileServiceImpl service =
|
||||
new CorrectWordFileServiceImpl(fileDao, itemDao, mappingDao);
|
||||
|
||||
@Test
|
||||
void getAllItemsByAgentId_returns_empty_list_when_no_mappings() {
|
||||
when(mappingDao.selectByAgentId(AGENT_ID)).thenReturn(Collections.emptyList());
|
||||
|
||||
List<CorrectWordSimpleVO> result = service.getAllItemsByAgentId(AGENT_ID);
|
||||
|
||||
assertTrue(result.isEmpty());
|
||||
verify(itemDao, never()).selectList(org.mockito.ArgumentMatchers.any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAllItemsByAgentId_returns_mapped_items_when_mappings_exist() {
|
||||
AgentCorrectWordMappingEntity mapping = new AgentCorrectWordMappingEntity();
|
||||
mapping.setFileId(FILE_ID);
|
||||
when(mappingDao.selectByAgentId(AGENT_ID)).thenReturn(List.of(mapping));
|
||||
|
||||
CorrectWordItemEntity item = new CorrectWordItemEntity();
|
||||
item.setSourceWord("hello");
|
||||
item.setTargetWord("hi");
|
||||
when(itemDao.selectList(org.mockito.ArgumentMatchers.any())).thenReturn(List.of(item));
|
||||
|
||||
List<CorrectWordSimpleVO> result = service.getAllItemsByAgentId(AGENT_ID);
|
||||
|
||||
assertEquals(1, result.size());
|
||||
assertEquals("hello", result.get(0).getSourceWord());
|
||||
assertEquals("hi", result.get(0).getTargetWord());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAllItemsByAgentId_returns_empty_list_when_mappings_are_null() {
|
||||
when(mappingDao.selectByAgentId(AGENT_ID)).thenReturn(null);
|
||||
|
||||
List<CorrectWordSimpleVO> result = service.getAllItemsByAgentId(AGENT_ID);
|
||||
|
||||
assertNotNull(result);
|
||||
assertTrue(result.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAgentCorrectWordFileIds_returns_empty_list_when_no_mappings() {
|
||||
when(mappingDao.selectByAgentId(AGENT_ID)).thenReturn(Collections.emptyList());
|
||||
|
||||
List<String> result = service.getAgentCorrectWordFileIds(AGENT_ID);
|
||||
|
||||
assertTrue(result.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAgentCorrectWordFileIds_returns_file_ids_when_mappings_exist() {
|
||||
AgentCorrectWordMappingEntity m1 = new AgentCorrectWordMappingEntity();
|
||||
m1.setFileId("f1");
|
||||
AgentCorrectWordMappingEntity m2 = new AgentCorrectWordMappingEntity();
|
||||
m2.setFileId("f2");
|
||||
when(mappingDao.selectByAgentId(AGENT_ID)).thenReturn(List.of(m1, m2));
|
||||
|
||||
List<String> result = service.getAgentCorrectWordFileIds(AGENT_ID);
|
||||
|
||||
assertEquals(List.of("f1", "f2"), result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getFileContent_returns_null_when_entity_not_found() {
|
||||
when(fileDao.selectById(FILE_ID)).thenReturn(null);
|
||||
|
||||
CorrectWordFileVO result = service.getFileContent(FILE_ID);
|
||||
|
||||
assertNull(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getFileContent_returns_vo_when_entity_found() {
|
||||
CorrectWordFileEntity entity = new CorrectWordFileEntity();
|
||||
entity.setId(FILE_ID);
|
||||
entity.setFileName("dict.txt");
|
||||
entity.setWordCount(2);
|
||||
entity.setContent("hello|hi\nbye|goodbye");
|
||||
entity.setCreatedAt(new Date());
|
||||
when(fileDao.selectById(FILE_ID)).thenReturn(entity);
|
||||
|
||||
CorrectWordFileVO result = service.getFileContent(FILE_ID);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(FILE_ID, result.getId());
|
||||
assertEquals("dict.txt", result.getFileName());
|
||||
assertEquals(2, result.getWordCount().intValue());
|
||||
assertEquals(2, result.getContent().size());
|
||||
assertEquals("hello|hi", result.getContent().get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteMappingsByAgentId_delegates_to_dao() {
|
||||
service.deleteMappingsByAgentId(AGENT_ID);
|
||||
|
||||
verify(mappingDao).deleteByAgentId(AGENT_ID);
|
||||
}
|
||||
|
||||
@Test
|
||||
void batchDeleteFiles_skips_null_and_empty_ids() {
|
||||
List<String> ids = new ArrayList<>();
|
||||
ids.add(null);
|
||||
ids.add("");
|
||||
ids.add(" ");
|
||||
ids.add(FILE_ID);
|
||||
|
||||
service.batchDeleteFiles(ids);
|
||||
|
||||
verify(fileDao).deleteById(FILE_ID);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,233 @@
|
|||
package xiaozhi.modules.knowledge.rag;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.Mockito.mockStatic;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.MockedStatic;
|
||||
|
||||
import xiaozhi.common.exception.ErrorCode;
|
||||
import xiaozhi.common.exception.RenException;
|
||||
import xiaozhi.common.page.PageData;
|
||||
import xiaozhi.common.utils.MessageUtils;
|
||||
import xiaozhi.modules.knowledge.dto.KnowledgeFilesDTO;
|
||||
import xiaozhi.modules.knowledge.dto.dataset.DatasetDTO;
|
||||
import xiaozhi.modules.knowledge.dto.document.ChunkDTO;
|
||||
import xiaozhi.modules.knowledge.dto.document.DocumentDTO;
|
||||
import xiaozhi.modules.knowledge.dto.document.RetrievalDTO;
|
||||
|
||||
class KnowledgeBaseAdapterFactoryTest {
|
||||
|
||||
private static final String REGISTERED_TYPE = "kb-test-registered";
|
||||
private static final String UNKNOWN_TYPE = "kb-test-unknown";
|
||||
|
||||
@BeforeEach
|
||||
void resetCache() {
|
||||
KnowledgeBaseAdapterFactory.clearCache();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void cleanupCache() {
|
||||
KnowledgeBaseAdapterFactory.clearCache();
|
||||
KnowledgeBaseAdapterFactory.removeCacheByType(REGISTERED_TYPE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAdapter_returns_non_null_instance_for_registered_type() {
|
||||
KnowledgeBaseAdapterFactory.registerAdapter(REGISTERED_TYPE, StubAdapter.class);
|
||||
|
||||
KnowledgeBaseAdapter adapter = KnowledgeBaseAdapterFactory.getAdapter(REGISTERED_TYPE);
|
||||
|
||||
assertNotNull(adapter);
|
||||
assertEquals(REGISTERED_TYPE, adapter.getAdapterType());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAdapter_returns_cached_instance_for_repeated_calls() {
|
||||
KnowledgeBaseAdapterFactory.registerAdapter(REGISTERED_TYPE, StubAdapter.class);
|
||||
|
||||
KnowledgeBaseAdapter first = KnowledgeBaseAdapterFactory.getAdapter(REGISTERED_TYPE);
|
||||
KnowledgeBaseAdapter second = KnowledgeBaseAdapterFactory.getAdapter(REGISTERED_TYPE);
|
||||
|
||||
assertSame(first, second);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAdapter_throws_RenException_for_unknown_type() {
|
||||
try (MockedStatic<MessageUtils> messageUtils = mockStatic(MessageUtils.class)) {
|
||||
messageUtils.when(() -> MessageUtils.getMessage(anyInt())).thenReturn("mocked message");
|
||||
messageUtils.when(() -> MessageUtils.getMessage(anyInt(), any(String[].class)))
|
||||
.thenReturn("mocked message");
|
||||
|
||||
RenException ex = assertThrows(RenException.class,
|
||||
() -> KnowledgeBaseAdapterFactory.getAdapter(UNKNOWN_TYPE));
|
||||
|
||||
assertEquals(ErrorCode.RAG_ADAPTER_TYPE_NOT_SUPPORTED, ex.getCode());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void isAdapterTypeRegistered_returns_true_for_registered_types() {
|
||||
KnowledgeBaseAdapterFactory.registerAdapter(REGISTERED_TYPE, StubAdapter.class);
|
||||
|
||||
assertTrue(KnowledgeBaseAdapterFactory.isAdapterTypeRegistered(REGISTERED_TYPE));
|
||||
assertTrue(KnowledgeBaseAdapterFactory.isAdapterTypeRegistered("ragflow"));
|
||||
assertFalse(KnowledgeBaseAdapterFactory.isAdapterTypeRegistered(UNKNOWN_TYPE));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getRegisteredAdapterTypes_contains_all_registered_types() {
|
||||
KnowledgeBaseAdapterFactory.registerAdapter(REGISTERED_TYPE, StubAdapter.class);
|
||||
|
||||
Set<String> types = KnowledgeBaseAdapterFactory.getRegisteredAdapterTypes();
|
||||
|
||||
assertTrue(types.contains(REGISTERED_TYPE));
|
||||
assertTrue(types.contains("ragflow"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void clearCache_empties_cached_instance_count() {
|
||||
KnowledgeBaseAdapterFactory.registerAdapter(REGISTERED_TYPE, StubAdapter.class);
|
||||
KnowledgeBaseAdapterFactory.getAdapter(REGISTERED_TYPE);
|
||||
|
||||
KnowledgeBaseAdapterFactory.clearCache();
|
||||
Map<String, Object> status = KnowledgeBaseAdapterFactory.getFactoryStatus();
|
||||
|
||||
assertEquals(0, status.get("cachedAdapterCount"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Test stub adapter that satisfies the abstract API surface so the factory's
|
||||
* reflection-based instantiation works in the unit test.
|
||||
*/
|
||||
public static class StubAdapter extends KnowledgeBaseAdapter {
|
||||
@Override
|
||||
public String getAdapterType() {
|
||||
return REGISTERED_TYPE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void initialize(Map<String, Object> config) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean validateConfig(Map<String, Object> config) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PageData<KnowledgeFilesDTO> getDocumentList(String datasetId,
|
||||
DocumentDTO.ListReq req) {
|
||||
return new PageData<>(java.util.Collections.emptyList(), 0);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DocumentDTO.InfoVO getDocumentById(String datasetId, String documentId) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public KnowledgeFilesDTO uploadDocument(DocumentDTO.UploadReq req) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PageData<KnowledgeFilesDTO> getDocumentListByStatus(String datasetId,
|
||||
Integer status, Integer page, Integer limit) {
|
||||
return new PageData<>(java.util.Collections.emptyList(), 0);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteDocument(String datasetId, DocumentDTO.BatchIdReq req) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean parseDocuments(String datasetId, java.util.List<String> documentIds) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ChunkDTO.ListVO listChunks(String datasetId, String documentId,
|
||||
ChunkDTO.ListReq req) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public RetrievalDTO.ResultVO retrievalTest(RetrievalDTO.TestReq req) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean testConnection() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Object> getStatus() {
|
||||
return java.util.Collections.emptyMap();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Object> getSupportedConfig() {
|
||||
return java.util.Collections.emptyMap();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Object> getDefaultConfig() {
|
||||
return java.util.Collections.emptyMap();
|
||||
}
|
||||
|
||||
@Override
|
||||
public DatasetDTO.InfoVO createDataset(DatasetDTO.CreateReq req) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DatasetDTO.InfoVO updateDataset(String datasetId, DatasetDTO.UpdateReq req) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DatasetDTO.BatchOperationVO deleteDataset(DatasetDTO.BatchIdReq req) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Integer getDocumentCount(String datasetId) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DatasetDTO.InfoVO getDatasetInfo(String datasetId) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void postStream(String endpoint, Object body, Consumer<String> onData) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object postSearchBotAsk(Map<String, Object> config, Object body,
|
||||
Consumer<String> onData) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void postAgentBotCompletion(Map<String, Object> config, String agentId,
|
||||
Object body, Consumer<String> onData) {
|
||||
}
|
||||
}
|
||||
}
|
||||
2957
main/manager-web/package-lock.json
generated
2957
main/manager-web/package-lock.json
generated
File diff suppressed because it is too large
Load diff
|
|
@ -7,7 +7,9 @@
|
|||
"check:i18n": "node scripts/check-i18n.js",
|
||||
"test:snapshot": "node --test src/components/agentSnapshotDisplayUtils.test.mjs src/apis/module/agentSnapshotApi.test.mjs",
|
||||
"build": "vue-cli-service build",
|
||||
"test:unit": "node --test tests/*.test.mjs",
|
||||
"test:contract": "node --test tests/*Contract.test.mjs",
|
||||
"test:unit": "vitest run",
|
||||
"test": "npm run test:contract && npm run test:unit",
|
||||
"analyze": "cross-env ANALYZE=true vue-cli-service build"
|
||||
},
|
||||
"dependencies": {
|
||||
|
|
@ -30,12 +32,16 @@
|
|||
"devDependencies": {
|
||||
"@babel/plugin-syntax-dynamic-import": "^7.8.3",
|
||||
"@babel/plugin-transform-runtime": "^7.26.10",
|
||||
"@vitest/coverage-v8": "^1.6.0",
|
||||
"@vue/cli-plugin-router": "~5.0.0",
|
||||
"@vue/cli-plugin-vuex": "~5.0.0",
|
||||
"@vue/cli-service": "~5.0.0",
|
||||
"@vue/test-utils": "^1.3.6",
|
||||
"compression-webpack-plugin": "^11.1.0",
|
||||
"jsdom": "^24.1.0",
|
||||
"sass": "^1.32.7",
|
||||
"sass-loader": "^12.0.0",
|
||||
"vitest": "^1.6.0",
|
||||
"vue-template-compiler": "^2.6.14",
|
||||
"webpack-bundle-analyzer": "^4.10.2",
|
||||
"workbox-webpack-plugin": "^7.3.0"
|
||||
|
|
|
|||
91
main/manager-web/tests/date.test.mjs
Normal file
91
main/manager-web/tests/date.test.mjs
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
import { describe, it, expect } from 'vitest';
|
||||
import * as date from '../src/utils/date.js';
|
||||
|
||||
describe('date utilities', () => {
|
||||
it('module loads and exports functions', () => {
|
||||
expect(date).toBeDefined();
|
||||
expect(Object.keys(date).length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
describe('isDate', () => {
|
||||
it('returns false for null and undefined', () => {
|
||||
expect(date.isDate(null)).toBe(false);
|
||||
expect(date.isDate(undefined)).toBe(false);
|
||||
});
|
||||
|
||||
it('returns false for an invalid date string', () => {
|
||||
expect(date.isDate('not-a-date')).toBe(false);
|
||||
});
|
||||
|
||||
it('returns true for valid date strings', () => {
|
||||
expect(date.isDate('2026-09-02')).toBe(true);
|
||||
expect(date.isDate('2026-09-02T10:00:00Z')).toBe(true);
|
||||
});
|
||||
|
||||
it('returns true for Date objects', () => {
|
||||
expect(date.isDate(new Date())).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isDateObject', () => {
|
||||
it('returns true only for Date instances', () => {
|
||||
expect(date.isDateObject(new Date())).toBe(true);
|
||||
expect(date.isDateObject('2026-09-02')).toBe(false);
|
||||
expect(date.isDateObject(1234567890)).toBe(false);
|
||||
expect(date.isDateObject(null)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('toDate', () => {
|
||||
it('returns null for falsy values', () => {
|
||||
expect(date.toDate(null)).toBe(null);
|
||||
expect(date.toDate(undefined)).toBe(null);
|
||||
expect(date.toDate('')).toBe(null);
|
||||
});
|
||||
|
||||
it('returns null for invalid input', () => {
|
||||
expect(date.toDate('not-a-date')).toBe(null);
|
||||
});
|
||||
|
||||
it('returns a Date for valid input', () => {
|
||||
const result = date.toDate('2026-09-02');
|
||||
expect(result).toBeInstanceOf(Date);
|
||||
expect(result.getFullYear()).toBe(2026);
|
||||
});
|
||||
});
|
||||
|
||||
describe('formatDate', () => {
|
||||
it('returns empty string for invalid input', () => {
|
||||
expect(date.formatDate(null)).toBe('');
|
||||
expect(date.formatDate('not-a-date')).toBe('');
|
||||
});
|
||||
|
||||
it('formats with the default pattern', () => {
|
||||
const result = date.formatDate('2026-09-02T10:20:30Z');
|
||||
expect(result).toMatch(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/);
|
||||
});
|
||||
|
||||
it('supports a custom format pattern', () => {
|
||||
const result = date.formatDate(new Date(2026, 8, 2, 13, 4, 5), 'yyyy/MM/dd');
|
||||
expect(result).toBe('2026/09/02');
|
||||
});
|
||||
});
|
||||
|
||||
describe('formatAddDate', () => {
|
||||
it('returns empty string when input is not a date', () => {
|
||||
expect(date.formatAddDate(null, 'yyyy-MM-dd', 5)).toBe('');
|
||||
});
|
||||
|
||||
it('returns formatted date unchanged when addDay is falsy', () => {
|
||||
// The implementation has a quirk: `if (!addDay)` adds the days (the condition is inverted),
|
||||
// so passing 0 with a date input still applies it (no-op since 0).
|
||||
const result = date.formatAddDate('2026-09-02', 'yyyy-MM-dd', 0);
|
||||
expect(result).toBe('2026-09-02');
|
||||
});
|
||||
|
||||
it('formats with the default pattern when none given', () => {
|
||||
const result = date.formatAddDate(new Date(2026, 8, 2, 13, 4, 5), '', 0);
|
||||
expect(result).toMatch(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -1,52 +1,75 @@
|
|||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import {
|
||||
compareTimestamps,
|
||||
formatCreateDate,
|
||||
formatTimestamp,
|
||||
hasTimestampValue,
|
||||
parseTimestamp,
|
||||
parseLegacyDate,
|
||||
formatTimestamp,
|
||||
formatCreateDate,
|
||||
compareTimestamps,
|
||||
} from '../src/utils/deviceTime.mjs';
|
||||
|
||||
const TIMESTAMP = 1783689702000;
|
||||
|
||||
test('accepts epoch milliseconds as a number or numeric string', () => {
|
||||
assert.equal(parseTimestamp(TIMESTAMP), TIMESTAMP);
|
||||
assert.equal(parseTimestamp(String(TIMESTAMP)), TIMESTAMP);
|
||||
assert.equal(parseTimestamp(` ${TIMESTAMP} `), TIMESTAMP);
|
||||
describe('hasTimestampValue', () => {
|
||||
it('returns false for null', () => expect(hasTimestampValue(null)).toBe(false));
|
||||
it('returns false for undefined', () => expect(hasTimestampValue(undefined)).toBe(false));
|
||||
it('returns false for empty string', () => expect(hasTimestampValue('')).toBe(false));
|
||||
it('returns false for whitespace-only string', () => expect(hasTimestampValue(' ')).toBe(false));
|
||||
it('returns true for number', () => expect(hasTimestampValue(1234567890)).toBe(true));
|
||||
it('returns true for non-empty string', () => expect(hasTimestampValue('2026-09-02')).toBe(true));
|
||||
});
|
||||
|
||||
test('rejects missing, invalid and non-scalar timestamp values', () => {
|
||||
const invalidValues = [null, undefined, '', ' ', 'invalid', true, {}, [], Infinity, Number.MAX_VALUE];
|
||||
|
||||
invalidValues.forEach(value => assert.equal(parseTimestamp(value), null));
|
||||
assert.equal(formatTimestamp('invalid'), '-');
|
||||
describe('parseTimestamp', () => {
|
||||
it('returns null for null', () => expect(parseTimestamp(null)).toBe(null));
|
||||
it('returns null for empty string', () => expect(parseTimestamp('')).toBe(null));
|
||||
it('parses numeric string', () => {
|
||||
const ts = parseTimestamp('1234567890000');
|
||||
expect(typeof ts).toBe('number');
|
||||
expect(ts).toBe(1234567890000);
|
||||
});
|
||||
it('returns null for non-numeric string', () => expect(parseTimestamp('not-a-date')).toBe(null));
|
||||
it('parses number directly', () => expect(parseTimestamp(1234567890000)).toBe(1234567890000));
|
||||
});
|
||||
|
||||
test('falls back to the legacy createDate only when the timestamp is missing', () => {
|
||||
const legacyDate = '2026-07-10 21:21:42';
|
||||
const formatter = timestamp => `local:${timestamp}`;
|
||||
|
||||
assert.equal(formatCreateDate(undefined, legacyDate, formatter), legacyDate);
|
||||
assert.equal(formatCreateDate('', legacyDate, formatter), legacyDate);
|
||||
assert.equal(formatCreateDate('invalid', legacyDate, formatter), '-');
|
||||
assert.equal(formatCreateDate(String(TIMESTAMP), legacyDate, formatter), `local:${TIMESTAMP}`);
|
||||
describe('parseLegacyDate', () => {
|
||||
it('returns null for empty', () => expect(parseLegacyDate('')).toBe(null));
|
||||
it('parses ISO date string', () => {
|
||||
const ts = parseLegacyDate('2026-09-02T10:00:00Z');
|
||||
expect(typeof ts).toBe('number');
|
||||
expect(ts).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
test('formats the same instant consistently in each browser time zone', () => {
|
||||
const formatter = timeZone => timestamp => new Date(timestamp).toLocaleString('en-US', { timeZone });
|
||||
|
||||
for (const timeZone of ['Asia/Shanghai', 'America/Sao_Paulo']) {
|
||||
assert.equal(
|
||||
formatTimestamp(TIMESTAMP, formatter(timeZone)),
|
||||
formatTimestamp(String(TIMESTAMP), formatter(timeZone)),
|
||||
);
|
||||
}
|
||||
describe('formatTimestamp', () => {
|
||||
it('returns dash for null', () => expect(formatTimestamp(null)).toBe('-'));
|
||||
it('uses default formatter', () => {
|
||||
const out = formatTimestamp(0);
|
||||
expect(typeof out).toBe('string');
|
||||
expect(out).not.toBe('-');
|
||||
});
|
||||
it('accepts custom formatter', () => {
|
||||
expect(formatTimestamp(0, () => 'CUSTOM')).toBe('CUSTOM');
|
||||
});
|
||||
});
|
||||
|
||||
test('sorts valid epoch values first and leaves invalid values at the end', () => {
|
||||
const timestamps = [null, TIMESTAMP + 1, undefined, TIMESTAMP];
|
||||
|
||||
assert.deepEqual(timestamps.sort(compareTimestamps), [TIMESTAMP, TIMESTAMP + 1, null, undefined]);
|
||||
assert.equal(compareTimestamps(null, undefined), 0);
|
||||
describe('formatCreateDate', () => {
|
||||
it('falls back to legacy date when timestamp missing', () => {
|
||||
expect(formatCreateDate(null, 'fallback')).toBe('fallback');
|
||||
});
|
||||
it('falls back to dash when both missing', () => {
|
||||
expect(formatCreateDate(null, null)).toBe('-');
|
||||
});
|
||||
});
|
||||
|
||||
describe('compareTimestamps', () => {
|
||||
it('returns negative when first < second', () => {
|
||||
expect(compareTimestamps(100, 200)).toBeLessThan(0);
|
||||
});
|
||||
it('returns positive when first > second', () => {
|
||||
expect(compareTimestamps(200, 100)).toBeGreaterThan(0);
|
||||
});
|
||||
it('returns 0 when both equal', () => {
|
||||
expect(compareTimestamps(100, 100)).toBe(0);
|
||||
});
|
||||
it('treats invalid as greater than nothing', () => {
|
||||
expect(compareTimestamps(100, NaN)).toBeLessThan(0);
|
||||
});
|
||||
});
|
||||
52
main/manager-web/tests/deviceTimeContract.test.mjs
Normal file
52
main/manager-web/tests/deviceTimeContract.test.mjs
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
|
||||
import {
|
||||
compareTimestamps,
|
||||
formatCreateDate,
|
||||
formatTimestamp,
|
||||
parseTimestamp,
|
||||
} from '../src/utils/deviceTime.mjs';
|
||||
|
||||
const TIMESTAMP = 1783689702000;
|
||||
|
||||
test('accepts epoch milliseconds as a number or numeric string', () => {
|
||||
assert.equal(parseTimestamp(TIMESTAMP), TIMESTAMP);
|
||||
assert.equal(parseTimestamp(String(TIMESTAMP)), TIMESTAMP);
|
||||
assert.equal(parseTimestamp(` ${TIMESTAMP} `), TIMESTAMP);
|
||||
});
|
||||
|
||||
test('rejects missing, invalid and non-scalar timestamp values', () => {
|
||||
const invalidValues = [null, undefined, '', ' ', 'invalid', true, {}, [], Infinity, Number.MAX_VALUE];
|
||||
|
||||
invalidValues.forEach(value => assert.equal(parseTimestamp(value), null));
|
||||
assert.equal(formatTimestamp('invalid'), '-');
|
||||
});
|
||||
|
||||
test('falls back to the legacy createDate only when the timestamp is missing', () => {
|
||||
const legacyDate = '2026-07-10 21:21:42';
|
||||
const formatter = timestamp => `local:${timestamp}`;
|
||||
|
||||
assert.equal(formatCreateDate(undefined, legacyDate, formatter), legacyDate);
|
||||
assert.equal(formatCreateDate('', legacyDate, formatter), legacyDate);
|
||||
assert.equal(formatCreateDate('invalid', legacyDate, formatter), '-');
|
||||
assert.equal(formatCreateDate(String(TIMESTAMP), legacyDate, formatter), `local:${TIMESTAMP}`);
|
||||
});
|
||||
|
||||
test('formats the same instant consistently in each browser time zone', () => {
|
||||
const formatter = timeZone => timestamp => new Date(timestamp).toLocaleString('en-US', { timeZone });
|
||||
|
||||
for (const timeZone of ['Asia/Shanghai', 'America/Sao_Paulo']) {
|
||||
assert.equal(
|
||||
formatTimestamp(TIMESTAMP, formatter(timeZone)),
|
||||
formatTimestamp(String(TIMESTAMP), formatter(timeZone)),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('sorts valid epoch values first and leaves invalid values at the end', () => {
|
||||
const timestamps = [null, TIMESTAMP + 1, undefined, TIMESTAMP];
|
||||
|
||||
assert.deepEqual(timestamps.sort(compareTimestamps), [TIMESTAMP, TIMESTAMP + 1, null, undefined]);
|
||||
assert.equal(compareTimestamps(null, undefined), 0);
|
||||
});
|
||||
99
main/manager-web/tests/featureManager.test.mjs
Normal file
99
main/manager-web/tests/featureManager.test.mjs
Normal file
|
|
@ -0,0 +1,99 @@
|
|||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
|
||||
// Mock the heavy dependencies before importing the module under test.
|
||||
vi.mock('@/apis/api', () => ({
|
||||
default: {
|
||||
user: {
|
||||
getPubConfig: vi.fn(),
|
||||
},
|
||||
admin: {
|
||||
updateParam: vi.fn(),
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('@/store', () => ({
|
||||
default: {
|
||||
commit: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
import featureManager from '../src/utils/featureManager.js';
|
||||
|
||||
describe('featureManager', () => {
|
||||
beforeEach(() => {
|
||||
// Reset to defaults so each test starts from a clean feature set.
|
||||
featureManager.resetToDefault();
|
||||
});
|
||||
|
||||
it('module loads and exports the singleton', () => {
|
||||
expect(featureManager).toBeDefined();
|
||||
expect(typeof featureManager.getCurrentConfig).toBe('function');
|
||||
});
|
||||
|
||||
it('resetToDefault populates the seven default feature flags', () => {
|
||||
const features = featureManager.getCurrentConfig();
|
||||
const keys = Object.keys(features).sort();
|
||||
expect(keys).toEqual([
|
||||
'addressBook',
|
||||
'asr',
|
||||
'knowledgeBase',
|
||||
'mcpAccessPoint',
|
||||
'vad',
|
||||
'voiceClone',
|
||||
'voiceprintRecognition',
|
||||
]);
|
||||
// Every default feature should start disabled.
|
||||
for (const key of keys) {
|
||||
expect(features[key].enabled).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it('setFeatureStatus returns false for an unknown feature key', () => {
|
||||
expect(featureManager.setFeatureStatus('notARealFeature', true)).toBe(false);
|
||||
});
|
||||
|
||||
it('setFeatureStatus enables and disables a known feature', () => {
|
||||
expect(featureManager.setFeatureStatus('asr', true)).toBe(true);
|
||||
expect(featureManager.isFeatureEnabled('asr')).toBe(true);
|
||||
|
||||
expect(featureManager.setFeatureStatus('asr', false)).toBe(true);
|
||||
expect(featureManager.isFeatureEnabled('asr')).toBe(false);
|
||||
});
|
||||
|
||||
it('enableFeature / disableFeature / toggleFeature update state', () => {
|
||||
featureManager.enableFeature('voiceprintRecognition');
|
||||
expect(featureManager.getFeatureStatus('voiceprintRecognition')).toBe(true);
|
||||
|
||||
featureManager.disableFeature('voiceprintRecognition');
|
||||
expect(featureManager.getFeatureStatus('voiceprintRecognition')).toBe(false);
|
||||
|
||||
featureManager.toggleFeature('knowledgeBase');
|
||||
expect(featureManager.getFeatureStatus('knowledgeBase')).toBe(true);
|
||||
featureManager.toggleFeature('knowledgeBase');
|
||||
expect(featureManager.getFeatureStatus('knowledgeBase')).toBe(false);
|
||||
});
|
||||
|
||||
it('getConfig returns a flat object of booleans', () => {
|
||||
const config = featureManager.getConfig();
|
||||
expect(Object.keys(config).sort()).toEqual([
|
||||
'addressBook',
|
||||
'asr',
|
||||
'knowledgeBase',
|
||||
'mcpAccessPoint',
|
||||
'vad',
|
||||
'voiceClone',
|
||||
'voiceprintRecognition',
|
||||
]);
|
||||
for (const key of Object.keys(config)) {
|
||||
expect(typeof config[key]).toBe('boolean');
|
||||
}
|
||||
});
|
||||
|
||||
it('getEnabledFeatures lists only enabled keys', () => {
|
||||
featureManager.enableFeature('asr');
|
||||
featureManager.enableFeature('vad');
|
||||
const enabled = featureManager.getEnabledFeatures().sort();
|
||||
expect(enabled).toEqual(['asr', 'vad']);
|
||||
});
|
||||
});
|
||||
56
main/manager-web/tests/format.test.mjs
Normal file
56
main/manager-web/tests/format.test.mjs
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
import { describe, it, expect } from 'vitest';
|
||||
import * as format from '../src/utils/format.js';
|
||||
|
||||
describe('format utilities', () => {
|
||||
it('module loads and exports functions', () => {
|
||||
expect(format).toBeDefined();
|
||||
expect(Object.keys(format).length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
describe('formatDate', () => {
|
||||
it('returns empty string for falsy values', () => {
|
||||
expect(format.formatDate(null)).toBe('');
|
||||
expect(format.formatDate(undefined)).toBe('');
|
||||
expect(format.formatDate('')).toBe('');
|
||||
expect(format.formatDate(0)).toBe('');
|
||||
});
|
||||
|
||||
it('formats a Date object as YYYY-MM-DD HH:mm:ss', () => {
|
||||
const date = new Date(2026, 8, 2, 13, 4, 5); // Sep 2, 2026 13:04:05 (local)
|
||||
expect(format.formatDate(date)).toBe('2026-09-02 13:04:05');
|
||||
});
|
||||
|
||||
it('accepts ISO date strings', () => {
|
||||
expect(format.formatDate('2026-01-15T08:30:00Z')).toMatch(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/);
|
||||
});
|
||||
|
||||
it('zero-pads single digit components', () => {
|
||||
const date = new Date(2026, 0, 5, 7, 8, 9); // Jan 5, 2026 07:08:09
|
||||
expect(format.formatDate(date)).toBe('2026-01-05 07:08:09');
|
||||
});
|
||||
});
|
||||
|
||||
describe('formatFileSize', () => {
|
||||
it('returns 0 B for falsy values', () => {
|
||||
expect(format.formatFileSize(0)).toBe('0 B');
|
||||
expect(format.formatFileSize(null)).toBe('0 B');
|
||||
expect(format.formatFileSize(undefined)).toBe('0 B');
|
||||
});
|
||||
|
||||
it('formats bytes in B', () => {
|
||||
expect(format.formatFileSize(512)).toBe('512 B');
|
||||
});
|
||||
|
||||
it('formats kilobytes', () => {
|
||||
expect(format.formatFileSize(1024)).toBe('1 KB');
|
||||
expect(format.formatFileSize(1536)).toBe('1.5 KB');
|
||||
});
|
||||
|
||||
it('formats megabytes and above', () => {
|
||||
expect(format.formatFileSize(1024 * 1024)).toBe('1 MB');
|
||||
expect(format.formatFileSize(2.5 * 1024 * 1024)).toBe('2.5 MB');
|
||||
expect(format.formatFileSize(1024 ** 3)).toBe('1 GB');
|
||||
expect(format.formatFileSize(1024 ** 4)).toBe('1 TB');
|
||||
});
|
||||
});
|
||||
});
|
||||
22
main/manager-web/vitest.config.js
Normal file
22
main/manager-web/vitest.config.js
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
import { defineConfig } from 'vitest/config';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
export default defineConfig({
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': fileURLToPath(new URL('./src', import.meta.url)),
|
||||
},
|
||||
},
|
||||
test: {
|
||||
environment: 'jsdom',
|
||||
globals: false,
|
||||
include: ['tests/**/*.test.{js,mjs}'],
|
||||
exclude: ['tests/*Contract.test.mjs', 'node_modules/**'],
|
||||
passWithNoTests: true,
|
||||
coverage: {
|
||||
provider: 'v8',
|
||||
reporter: ['text', 'html'],
|
||||
include: ['src/utils/**', 'src/store/**'],
|
||||
},
|
||||
},
|
||||
});
|
||||
10
main/xiaozhi-server/pyproject.toml
Normal file
10
main/xiaozhi-server/pyproject.toml
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
[tool.pytest.ini_options]
|
||||
asyncio_mode = "auto"
|
||||
testpaths = ["tests"]
|
||||
python_files = ["test_*.py"]
|
||||
python_classes = ["Test*"]
|
||||
python_functions = ["test_*"]
|
||||
addopts = "-ra"
|
||||
filterwarnings = [
|
||||
"ignore::DeprecationWarning",
|
||||
]
|
||||
0
main/xiaozhi-server/tests/__init__.py
Normal file
0
main/xiaozhi-server/tests/__init__.py
Normal file
0
main/xiaozhi-server/tests/config/__init__.py
Normal file
0
main/xiaozhi-server/tests/config/__init__.py
Normal file
45
main/xiaozhi-server/tests/config/test_config_loader.py
Normal file
45
main/xiaozhi-server/tests/config/test_config_loader.py
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
"""Tests for the recursive config merge in config/config_loader.py."""
|
||||
from config.config_loader import merge_configs
|
||||
|
||||
|
||||
def test_merge_simple_override():
|
||||
default = {"a": 1, "b": 2}
|
||||
custom = {"b": 99}
|
||||
assert merge_configs(default, custom) == {"a": 1, "b": 99}
|
||||
|
||||
|
||||
def test_merge_adds_new_key():
|
||||
default = {"a": 1}
|
||||
custom = {"b": 2}
|
||||
assert merge_configs(default, custom) == {"a": 1, "b": 2}
|
||||
|
||||
|
||||
def test_merge_recursive_dict():
|
||||
default = {"x": {"a": 1, "b": 2}}
|
||||
custom = {"x": {"b": 99}}
|
||||
assert merge_configs(default, custom) == {"x": {"a": 1, "b": 99}}
|
||||
|
||||
|
||||
def test_merge_deep_recursive():
|
||||
default = {"a": {"b": {"c": 1, "d": 2}}}
|
||||
custom = {"a": {"b": {"c": 99}}}
|
||||
assert merge_configs(default, custom) == {"a": {"b": {"c": 99, "d": 2}}}
|
||||
|
||||
|
||||
def test_merge_replaces_non_dict_with_dict():
|
||||
default = {"a": 1}
|
||||
custom = {"a": {"nested": True}}
|
||||
assert merge_configs(default, custom) == {"a": {"nested": True}}
|
||||
|
||||
|
||||
def test_merge_replaces_dict_with_non_dict():
|
||||
default = {"a": {"nested": True}}
|
||||
custom = {"a": 1}
|
||||
assert merge_configs(default, custom) == {"a": 1}
|
||||
|
||||
|
||||
def test_merge_does_not_mutate_defaults():
|
||||
default = {"a": {"b": 1}}
|
||||
custom = {"a": {"c": 2}}
|
||||
merge_configs(default, custom)
|
||||
assert default == {"a": {"b": 1}} # unchanged
|
||||
11
main/xiaozhi-server/tests/conftest.py
Normal file
11
main/xiaozhi-server/tests/conftest.py
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
"""Pytest configuration — must run BEFORE any test imports project modules.
|
||||
|
||||
Adds the xiaozhi-server directory to sys.path so the existing implicit
|
||||
relative imports (`from core.utils.textUtils import ...`) resolve.
|
||||
"""
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
_PROJECT_ROOT = Path(__file__).resolve().parent.parent
|
||||
if str(_PROJECT_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(_PROJECT_ROOT))
|
||||
0
main/xiaozhi-server/tests/core/__init__.py
Normal file
0
main/xiaozhi-server/tests/core/__init__.py
Normal file
0
main/xiaozhi-server/tests/core/utils/__init__.py
Normal file
0
main/xiaozhi-server/tests/core/utils/__init__.py
Normal file
57
main/xiaozhi-server/tests/core/utils/test_current_time.py
Normal file
57
main/xiaozhi-server/tests/core/utils/test_current_time.py
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
"""Tests for core/utils/current_time.py.
|
||||
|
||||
Uses freezegun to control `datetime.now()` so the tests don't flake
|
||||
around midnight, and to verify the weekday/lunar mapping logic.
|
||||
"""
|
||||
from datetime import datetime
|
||||
|
||||
import pytest
|
||||
from freezegun import freeze_time
|
||||
|
||||
from core.utils import current_time
|
||||
|
||||
|
||||
@freeze_time("2026-09-02 10:30:00")
|
||||
def test_get_current_time_format_is_hh_mm():
|
||||
assert current_time.get_current_time() == "10:30"
|
||||
|
||||
|
||||
@freeze_time("2026-09-02 23:59:59")
|
||||
def test_get_current_time_at_late_hour():
|
||||
assert current_time.get_current_time() == "23:59"
|
||||
|
||||
|
||||
@freeze_time("2026-09-02 10:30:00")
|
||||
def test_get_current_date_format_is_iso():
|
||||
assert current_time.get_current_date() == "2026-09-02"
|
||||
|
||||
|
||||
@freeze_time("2026-09-02 10:30:00") # 2026-09-02 is a Wednesday
|
||||
def test_get_current_weekday_returns_chinese_label():
|
||||
assert current_time.get_current_weekday() == "星期三"
|
||||
|
||||
|
||||
def test_weekday_map_has_all_seven_days():
|
||||
assert set(current_time.WEEKDAY_MAP.keys()) == {
|
||||
"Monday", "Tuesday", "Wednesday", "Thursday",
|
||||
"Friday", "Saturday", "Sunday",
|
||||
}
|
||||
|
||||
|
||||
@freeze_time("2026-09-02 10:30:00")
|
||||
def test_get_current_time_info_returns_four_tuple():
|
||||
info = current_time.get_current_time_info()
|
||||
assert isinstance(info, tuple)
|
||||
assert len(info) == 4
|
||||
time_str, date_str, weekday, lunar = info
|
||||
assert time_str == "10:30"
|
||||
assert date_str == "2026-09-02"
|
||||
assert weekday == "星期三"
|
||||
assert "年" in lunar # lunar output contains "年"
|
||||
|
||||
|
||||
@freeze_time("2026-09-02 10:30:00")
|
||||
def test_get_current_lunar_date_contains_year():
|
||||
"""cnlunar should produce a string containing 年 character."""
|
||||
lunar = current_time.get_current_lunar_date()
|
||||
assert "年" in lunar
|
||||
83
main/xiaozhi-server/tests/core/utils/test_dialogue.py
Normal file
83
main/xiaozhi-server/tests/core/utils/test_dialogue.py
Normal file
|
|
@ -0,0 +1,83 @@
|
|||
"""Tests for the Message/Dialogue classes used to build LLM context."""
|
||||
import pytest
|
||||
|
||||
from core.utils.dialogue import Dialogue, Message
|
||||
|
||||
|
||||
def test_message_assigns_default_uniq_id():
|
||||
m = Message(role="user", content="hi")
|
||||
assert m.uniq_id is not None
|
||||
assert len(m.uniq_id) > 0
|
||||
|
||||
|
||||
def test_message_preserves_explicit_uniq_id():
|
||||
m = Message(role="user", content="hi", uniq_id="abc")
|
||||
assert m.uniq_id == "abc"
|
||||
|
||||
|
||||
def test_message_default_is_not_temporary():
|
||||
m = Message(role="user", content="hi")
|
||||
assert m.is_temporary is False
|
||||
|
||||
|
||||
def test_message_tool_call_id_default_is_none():
|
||||
m = Message(role="user", content="hi")
|
||||
assert m.tool_call_id is None
|
||||
|
||||
|
||||
def test_dialogue_starts_empty():
|
||||
d = Dialogue()
|
||||
assert d.dialogue == []
|
||||
|
||||
|
||||
def test_dialogue_put_appends_message():
|
||||
d = Dialogue()
|
||||
d.put(Message(role="user", content="hi"))
|
||||
d.put(Message(role="assistant", content="hello"))
|
||||
assert len(d.dialogue) == 2
|
||||
|
||||
|
||||
def test_dialogue_get_llm_dialogue_includes_user_and_assistant():
|
||||
d = Dialogue()
|
||||
d.put(Message(role="user", content="hi"))
|
||||
d.put(Message(role="assistant", content="hello"))
|
||||
msgs = d.get_llm_dialogue()
|
||||
assert {"role": "user", "content": "hi"} in msgs
|
||||
assert {"role": "assistant", "content": "hello"} in msgs
|
||||
|
||||
|
||||
def test_dialogue_update_system_message_replaces_existing():
|
||||
d = Dialogue()
|
||||
d.update_system_message("you are a helper")
|
||||
d.update_system_message("you are a coder")
|
||||
system_msgs = [m for m in d.dialogue if m.role == "system"]
|
||||
assert len(system_msgs) == 1
|
||||
assert system_msgs[0].content == "you are a coder"
|
||||
|
||||
|
||||
def test_dialogue_update_system_message_creates_when_missing():
|
||||
d = Dialogue()
|
||||
d.update_system_message("you are a coder")
|
||||
assert len(d.dialogue) == 1
|
||||
assert d.dialogue[0].role == "system"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_llm_dialogue_with_memory_substitutes_into_system_message():
|
||||
d = Dialogue()
|
||||
d.update_system_message("Memory so far: <memory></memory>")
|
||||
msgs = d.get_llm_dialogue_with_memory(memory_str="user likes cats")
|
||||
system = next(m for m in msgs if m["role"] == "system")
|
||||
assert "user likes cats" in system["content"]
|
||||
assert "<memory></memory>" not in system["content"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_llm_dialogue_separates_temporary_few_shot_from_actual_history():
|
||||
d = Dialogue()
|
||||
d.put(Message(role="user", content="real user msg", is_temporary=False))
|
||||
d.put(Message(role="user", content="fewshot example", is_temporary=True))
|
||||
msgs = d.get_llm_dialogue()
|
||||
contents = [m["content"] for m in msgs if m["role"] == "user"]
|
||||
assert "real user msg" in contents
|
||||
assert "fewshot example" in contents
|
||||
|
|
@ -0,0 +1,49 @@
|
|||
"""Tests for the create_instance factories in intent/llm/memory utils.
|
||||
|
||||
Each `create_instance(name, ...)` looks up `core/providers/<type>/<name>/<name>.py`
|
||||
on disk. We only test:
|
||||
- the ValueError path for unknown names (no providers need to exist)
|
||||
- that the signature accepts *args / **kwargs (so all three modules work)
|
||||
|
||||
NOTE: This test file is currently skipped at module level because importing
|
||||
`core.utils.intent` triggers `setup_logging()` at module load time, which
|
||||
requires `data/.config.yaml` to exist. That file is .gitignore'd and not
|
||||
present in CI. To enable this test suite, either:
|
||||
1. Make `setup_logging()` lazy (move the call out of module-level scope).
|
||||
2. Provide a stub `data/.config.yaml` in the test environment.
|
||||
Tracked as deferred-minor in progress.md.
|
||||
"""
|
||||
import pytest
|
||||
|
||||
pytest.skip(
|
||||
"setup_logging() at module import requires data/.config.yaml; skipped",
|
||||
allow_module_level=True,
|
||||
)
|
||||
|
||||
from core.utils import intent, llm, memory # noqa: E402 (unreachable when skipped)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("factory,module_type", [
|
||||
(intent.create_instance, "intent"),
|
||||
(llm.create_instance, "llm"),
|
||||
(memory.create_instance, "memory"),
|
||||
])
|
||||
def test_create_instance_raises_for_unknown_class(factory, module_type):
|
||||
with pytest.raises(ValueError) as exc_info:
|
||||
factory("definitely-not-a-real-provider-name-xyz")
|
||||
assert "不支持" in str(exc_info.value) or "不支持的" in str(exc_info.value)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("factory,module_type", [
|
||||
(intent.create_instance, "intent"),
|
||||
(llm.create_instance, "llm"),
|
||||
(memory.create_instance, "memory"),
|
||||
])
|
||||
def test_create_instance_accepts_args_and_kwargs(factory, module_type):
|
||||
"""Even when the provider exists, the call must accept *args and **kwargs.
|
||||
|
||||
We don't need to assert successful creation — just that the signature
|
||||
is variadic. We use a sentinel that will fail the path check.
|
||||
"""
|
||||
with pytest.raises(ValueError):
|
||||
factory("__missing__", "positional-arg", kwarg="value")
|
||||
53
main/xiaozhi-server/tests/core/utils/test_output_counter.py
Normal file
53
main/xiaozhi-server/tests/core/utils/test_output_counter.py
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
"""Tests for the per-device daily output character counter."""
|
||||
import pytest
|
||||
|
||||
from core.utils import output_counter
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _reset_counter():
|
||||
"""Each test starts with a clean counter."""
|
||||
output_counter.reset_device_output()
|
||||
yield
|
||||
output_counter.reset_device_output()
|
||||
|
||||
|
||||
def test_get_device_output_returns_zero_when_never_added():
|
||||
assert output_counter.get_device_output("dev-1") == 0
|
||||
|
||||
|
||||
def test_add_device_output_increments_count():
|
||||
output_counter.add_device_output("dev-1", 100)
|
||||
output_counter.add_device_output("dev-1", 50)
|
||||
assert output_counter.get_device_output("dev-1") == 150
|
||||
|
||||
|
||||
def test_add_device_output_is_per_device():
|
||||
output_counter.add_device_output("dev-1", 100)
|
||||
output_counter.add_device_output("dev-2", 200)
|
||||
assert output_counter.get_device_output("dev-1") == 100
|
||||
assert output_counter.get_device_output("dev-2") == 200
|
||||
|
||||
|
||||
def test_check_device_output_limit_returns_true_when_exceeded():
|
||||
output_counter.add_device_output("dev-1", 100)
|
||||
assert output_counter.check_device_output_limit("dev-1", 100) is True
|
||||
assert output_counter.check_device_output_limit("dev-1", 50) is True
|
||||
|
||||
|
||||
def test_check_device_output_limit_returns_false_when_under():
|
||||
output_counter.add_device_output("dev-1", 50)
|
||||
assert output_counter.check_device_output_limit("dev-1", 100) is False
|
||||
|
||||
|
||||
def test_check_device_output_limit_with_empty_device_id_returns_false():
|
||||
assert output_counter.check_device_output_limit("", 1) is False
|
||||
assert output_counter.check_device_output_limit(None, 1) is False
|
||||
|
||||
|
||||
def test_reset_clears_all_counts():
|
||||
output_counter.add_device_output("dev-1", 100)
|
||||
output_counter.add_device_output("dev-2", 200)
|
||||
output_counter.reset_device_output()
|
||||
assert output_counter.get_device_output("dev-1") == 0
|
||||
assert output_counter.get_device_output("dev-2") == 0
|
||||
51
main/xiaozhi-server/tests/core/utils/test_textUtils.py
Normal file
51
main/xiaozhi-server/tests/core/utils/test_textUtils.py
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
"""Characterization tests for core/utils/textUtils.py."""
|
||||
from core.utils.textUtils import (
|
||||
is_emoji,
|
||||
is_punctuation_or_emoji,
|
||||
get_string_no_punctuation_or_emoji,
|
||||
check_emoji,
|
||||
)
|
||||
|
||||
|
||||
def test_is_emoji_returns_true_for_smile():
|
||||
assert is_emoji("🙂") is True
|
||||
|
||||
|
||||
def test_is_emoji_returns_false_for_ascii_letter():
|
||||
assert is_emoji("a") is False
|
||||
|
||||
|
||||
def test_is_emoji_returns_false_for_chinese_char():
|
||||
assert is_emoji("你") is False
|
||||
|
||||
|
||||
def test_is_punctuation_or_emoji_for_chinese_comma():
|
||||
assert is_punctuation_or_emoji(",") is True
|
||||
|
||||
|
||||
def test_is_punctuation_or_emoji_for_space():
|
||||
assert is_punctuation_or_emoji(" ") is True
|
||||
|
||||
|
||||
def test_is_punctuation_or_emoji_for_letter_is_false():
|
||||
assert is_punctuation_or_emoji("a") is False
|
||||
|
||||
|
||||
def test_get_string_no_punctuation_or_emoji_strips_both_sides():
|
||||
assert get_string_no_punctuation_or_emoji(", 你好 。") == "你好"
|
||||
|
||||
|
||||
def test_get_string_no_punctuation_or_emoji_no_punctuation():
|
||||
assert get_string_no_punctuation_or_emoji("你好") == "你好"
|
||||
|
||||
|
||||
def test_get_string_no_punctuation_or_emoji_empty_string():
|
||||
assert get_string_no_punctuation_or_emoji("") == ""
|
||||
|
||||
|
||||
def test_check_emoji_removes_emoji_keeps_text():
|
||||
assert check_emoji("hi 😀 there") == "hi there"
|
||||
|
||||
|
||||
def test_check_emoji_removes_newlines():
|
||||
assert check_emoji("a\nb") == "ab"
|
||||
0
main/xiaozhi-server/tests/plugins_func/__init__.py
Normal file
0
main/xiaozhi-server/tests/plugins_func/__init__.py
Normal file
26
main/xiaozhi-server/tests/plugins_func/test_loadplugins.py
Normal file
26
main/xiaozhi-server/tests/plugins_func/test_loadplugins.py
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
"""Test for the auto-import mechanism in plugins_func/loadplugins.py.
|
||||
|
||||
We import a real subpackage (`plugins_func.functions`) and verify the
|
||||
import side-effect runs. This protects against accidentally deleting
|
||||
`auto_import_modules` from `app.py` startup code.
|
||||
|
||||
NOTE: This test is currently skipped because importing
|
||||
`plugins_func.functions` triggers heavy module imports (cache_manager,
|
||||
etc.) that may not initialise in the test environment. To enable this
|
||||
test, ensure `data/.config.yaml` exists in the test environment or refactor
|
||||
plugin discovery to be lazy.
|
||||
"""
|
||||
import pytest
|
||||
|
||||
pytest.skip(
|
||||
"plugins_func.functions import has side effects that need data/.config.yaml; skipped",
|
||||
allow_module_level=True,
|
||||
)
|
||||
|
||||
from plugins_func.functions import get_time # noqa: F401 (unreachable when skipped)
|
||||
|
||||
|
||||
def test_functions_package_importable():
|
||||
"""If this test runs, plugins_func.functions.__init__.py has been imported."""
|
||||
import plugins_func.functions as fns
|
||||
assert hasattr(fns, "get_time")
|
||||
14
main/xiaozhi-server/tests/test_smoke.py
Normal file
14
main/xiaozhi-server/tests/test_smoke.py
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
"""Smoke test — confirms pytest can collect from this directory.
|
||||
|
||||
Real tests land in Slice 2 (see docs/superpowers/specs/2026-09-02-test-infrastructure-design.md).
|
||||
"""
|
||||
|
||||
|
||||
def test_pytest_works():
|
||||
assert 1 + 1 == 2
|
||||
|
||||
|
||||
def test_repo_path_is_writable(tmp_path):
|
||||
p = tmp_path / "scratch.txt"
|
||||
p.write_text("ok", encoding="utf-8")
|
||||
assert p.read_text(encoding="utf-8") == "ok"
|
||||
Loading…
Reference in a new issue