Skip to content

Commit 3dc978d

Browse files
committed
test: Добавлены тесты для исключения путей и команд форматирования/анализа
- Добавлены тесты для AnalyzeCommand и FormatCommand, проверяющие корректность обработки исключенных путей. - Обновлены тесты ServerContext для проверки исключения путей из конфигурации. - Добавлен новый класс PathExclusionUtilsTest для тестирования логики исключения путей. - Создан файл конфигурации .bsl-language-server-exclude-paths.json для тестирования. Эти изменения обеспечивают более надежное тестирование функциональности исключения путей в языковом сервере BSL.
1 parent c109039 commit 3dc978d

File tree

6 files changed

+496
-52
lines changed

6 files changed

+496
-52
lines changed

src/test/java/com/github/_1c_syntax/bsl/languageserver/BSLWorkspaceServiceTest.java

Lines changed: 74 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
*/
2222
package com.github._1c_syntax.bsl.languageserver;
2323

24+
import com.github._1c_syntax.bsl.languageserver.configuration.LanguageServerConfiguration;
2425
import com.github._1c_syntax.bsl.languageserver.context.ServerContext;
2526
import com.github._1c_syntax.bsl.languageserver.util.CleanupContextBeforeClassAndAfterEachTestMethod;
2627
import com.github._1c_syntax.utils.Absolute;
@@ -33,12 +34,14 @@
3334
import org.junit.jupiter.api.io.TempDir;
3435
import org.springframework.beans.factory.annotation.Autowired;
3536
import org.springframework.boot.test.context.SpringBootTest;
37+
import org.springframework.test.annotation.DirtiesContext;
3638

3739
import java.io.File;
3840
import java.io.IOException;
3941
import java.net.URI;
4042
import java.nio.charset.StandardCharsets;
4143
import java.nio.file.Path;
44+
import java.nio.file.Paths;
4245
import java.time.Duration;
4346
import java.util.List;
4447

@@ -53,6 +56,7 @@
5356
*/
5457
@SpringBootTest
5558
@CleanupContextBeforeClassAndAfterEachTestMethod
59+
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
5660
class BSLWorkspaceServiceTest {
5761

5862
@Autowired
@@ -61,31 +65,30 @@ class BSLWorkspaceServiceTest {
6165
@Autowired
6266
private ServerContext serverContext;
6367

68+
@Autowired
69+
private LanguageServerConfiguration configuration;
70+
6471
@TempDir
6572
Path tempDir;
6673

6774
@Test
6875
void testDidChangeWatchedFiles_Created_NotOpened() throws IOException {
69-
// given
7076
var testFile = createTestFile("test_created.bsl");
7177
var uri = Absolute.uri(testFile.toURI());
7278

7379
var fileEvent = new FileEvent(uri.toString(), FileChangeType.Created);
7480
var params = new DidChangeWatchedFilesParams(List.of(fileEvent));
7581

76-
// when
7782
workspaceService.didChangeWatchedFiles(params);
7883
await().until(() -> serverContext.getDocument(uri) != null);
7984

80-
// then
8185
var documentContext = serverContext.getDocument(uri);
8286
assertThat(documentContext).isNotNull();
8387
assertThat(serverContext.isDocumentOpened(documentContext)).isFalse();
8488
}
8589

8690
@Test
8791
void testDidChangeWatchedFiles_Created_AlreadyOpened() throws IOException {
88-
// given
8992
var testFile = createTestFile("test_created_opened.bsl");
9093
var uri = Absolute.uri(testFile.toURI());
9194
var content = FileUtils.readFileToString(testFile, StandardCharsets.UTF_8);
@@ -96,71 +99,55 @@ void testDidChangeWatchedFiles_Created_AlreadyOpened() throws IOException {
9699
var fileEvent = new FileEvent(uri.toString(), FileChangeType.Created);
97100
var params = new DidChangeWatchedFilesParams(List.of(fileEvent));
98101

99-
// when
100102
workspaceService.didChangeWatchedFiles(params);
101103
await().pollDelay(Duration.ofMillis(200)).until(() -> true);
102104

103-
// then
104-
// Для открытого файла событие Created должно быть проигнорировано
105-
// Документ должен остаться в контексте
106105
assertThat(serverContext.getDocument(uri)).isNotNull();
107106
}
108107

109108
@Test
110109
void testDidChangeWatchedFiles_Changed_NotOpened() throws IOException {
111-
// given
112110
var testFile = createTestFile("test_changed.bsl");
113111
var uri = Absolute.uri(testFile.toURI());
114112

115113
var documentContext = serverContext.addDocument(uri);
116114
serverContext.rebuildDocument(documentContext);
117115
serverContext.tryClearDocument(documentContext);
118116

119-
// Изменяем содержимое файла
120-
FileUtils.writeStringToFile(testFile, "// Новое содержимое\nПроцедура Тест()\nКонецПроцедуры\n", StandardCharsets.UTF_8);
117+
FileUtils.copyFile(getFixtureFile("providers/format.bsl"), testFile);
121118

122119
var fileEvent = new FileEvent(uri.toString(), FileChangeType.Changed);
123120
var params = new DidChangeWatchedFilesParams(List.of(fileEvent));
124121

125-
// when
126122
workspaceService.didChangeWatchedFiles(params);
127123
await().pollDelay(Duration.ofMillis(100)).until(() -> true);
128124

129-
// then
130125
assertThat(serverContext.getDocument(uri)).isNotNull();
131126
assertThat(serverContext.isDocumentOpened(documentContext)).isFalse();
132127
}
133128

134129
@Test
135130
void testDidChangeWatchedFiles_Changed_Opened() throws IOException {
136-
// given
137131
var testFile = createTestFile("test_changed_opened.bsl");
138132
var uri = Absolute.uri(testFile.toURI());
139133
var content = FileUtils.readFileToString(testFile, StandardCharsets.UTF_8);
140134

141135
var documentContext = serverContext.addDocument(uri);
142136
serverContext.openDocument(documentContext, content, 1);
143137

144-
// Изменяем содержимое файла на диске
145-
var newContentOnDisk = "// Измененное содержимое\n";
146-
FileUtils.writeStringToFile(testFile, newContentOnDisk, StandardCharsets.UTF_8);
138+
FileUtils.copyFile(getFixtureFile("providers/format.bsl"), testFile);
147139

148140
var fileEvent = new FileEvent(uri.toString(), FileChangeType.Changed);
149141
var params = new DidChangeWatchedFilesParams(List.of(fileEvent));
150142

151-
// when
152143
workspaceService.didChangeWatchedFiles(params);
153144
await().pollDelay(Duration.ofMillis(200)).until(() -> true);
154145

155-
// then
156-
// Для открытого файла событие Changed должно быть проигнорировано
157-
// Документ должен остаться в контексте
158146
assertThat(serverContext.getDocument(uri)).isNotNull();
159147
}
160148

161149
@Test
162150
void testDidChangeWatchedFiles_Changed_UnknownFile() throws IOException {
163-
// given
164151
var testFile = createTestFile("test_changed_unknown.bsl");
165152
var uri = Absolute.uri(testFile.toURI());
166153

@@ -169,18 +156,15 @@ void testDidChangeWatchedFiles_Changed_UnknownFile() throws IOException {
169156
var fileEvent = new FileEvent(uri.toString(), FileChangeType.Changed);
170157
var params = new DidChangeWatchedFilesParams(List.of(fileEvent));
171158

172-
// when
173159
workspaceService.didChangeWatchedFiles(params);
174160
await().until(() -> serverContext.getDocument(uri) != null);
175161

176-
// then
177162
var documentContext = serverContext.getDocument(uri);
178163
assertThat(documentContext).isNotNull();
179164
}
180165

181166
@Test
182167
void testDidChangeWatchedFiles_Deleted_NotOpened() throws IOException {
183-
// given
184168
var testFile = createTestFile("test_deleted.bsl");
185169
var uri = Absolute.uri(testFile.toURI());
186170

@@ -193,17 +177,14 @@ void testDidChangeWatchedFiles_Deleted_NotOpened() throws IOException {
193177
var fileEvent = new FileEvent(uri.toString(), FileChangeType.Deleted);
194178
var params = new DidChangeWatchedFilesParams(List.of(fileEvent));
195179

196-
// when
197180
workspaceService.didChangeWatchedFiles(params);
198181
await().until(() -> serverContext.getDocument(uri) == null);
199182

200-
// then
201183
assertThat(serverContext.getDocument(uri)).isNull();
202184
}
203185

204186
@Test
205187
void testDidChangeWatchedFiles_Deleted_Opened() throws IOException {
206-
// given
207188
var testFile = createTestFile("test_deleted_opened.bsl");
208189
var uri = Absolute.uri(testFile.toURI());
209190
var content = FileUtils.readFileToString(testFile, StandardCharsets.UTF_8);
@@ -216,34 +197,27 @@ void testDidChangeWatchedFiles_Deleted_Opened() throws IOException {
216197
var fileEvent = new FileEvent(uri.toString(), FileChangeType.Deleted);
217198
var params = new DidChangeWatchedFilesParams(List.of(fileEvent));
218199

219-
// when
220200
workspaceService.didChangeWatchedFiles(params);
221201
await().until(() -> serverContext.getDocument(uri) == null);
222202

223-
// then
224203
assertThat(serverContext.getDocument(uri)).isNull();
225204
}
226205

227206
@Test
228207
void testDidChangeWatchedFiles_Deleted_UnknownFile() {
229-
// given
230208
var uri = URI.create("file:///nonexistent.bsl");
231209

232210
var fileEvent = new FileEvent(uri.toString(), FileChangeType.Deleted);
233211
var params = new DidChangeWatchedFilesParams(List.of(fileEvent));
234212

235-
// when
236213
workspaceService.didChangeWatchedFiles(params);
237214
await().pollDelay(Duration.ofMillis(100)).until(() -> true);
238215

239-
// then
240-
// Не должно быть исключений
241216
assertThat(serverContext.getDocument(uri)).isNull();
242217
}
243218

244219
@Test
245220
void testDidChangeWatchedFiles_MultipleEvents() throws IOException {
246-
// given
247221
var file1 = createTestFile("test_multiple_1.bsl");
248222
var file2 = createTestFile("test_multiple_2.bsl");
249223
var file3 = createTestFile("test_multiple_3.bsl");
@@ -255,7 +229,6 @@ void testDidChangeWatchedFiles_MultipleEvents() throws IOException {
255229
var documentContext2 = serverContext.addDocument(uri2);
256230
serverContext.rebuildDocument(documentContext2);
257231

258-
// file3 добавляем в контекст, чтобы проверить его удаление
259232
var documentContext3 = serverContext.addDocument(uri3);
260233
serverContext.rebuildDocument(documentContext3);
261234

@@ -266,48 +239,97 @@ void testDidChangeWatchedFiles_MultipleEvents() throws IOException {
266239
);
267240
var params = new DidChangeWatchedFilesParams(events);
268241

269-
// when
270242
workspaceService.didChangeWatchedFiles(params);
271243
await().until(() ->
272244
serverContext.getDocument(uri1) != null &&
273245
serverContext.getDocument(uri2) != null &&
274246
serverContext.getDocument(uri3) == null
275247
);
276248

277-
// then
278249
assertThat(serverContext.getDocument(uri1)).isNotNull();
279250
assertThat(serverContext.getDocument(uri2)).isNotNull();
280251
assertThat(serverContext.getDocument(uri3)).isNull();
281252
}
282253

254+
@Test
255+
void testDidChangeWatchedFiles_Created_ExcludedPath() throws IOException {
256+
serverContext.setConfigurationRoot(tempDir);
257+
configuration.setExcludePaths(List.of(".git"));
258+
259+
var excludedDir = tempDir.resolve(".git").toFile();
260+
excludedDir.mkdirs();
261+
var testFile = new File(excludedDir, "excluded.bsl");
262+
FileUtils.copyFile(getFixtureFile("cli/test.bsl"), testFile);
263+
var uri = Absolute.uri(testFile.toURI());
264+
265+
var fileEvent = new FileEvent(uri.toString(), FileChangeType.Created);
266+
workspaceService.didChangeWatchedFiles(new DidChangeWatchedFilesParams(List.of(fileEvent)));
267+
268+
await().pollDelay(Duration.ofMillis(150)).until(() -> true);
269+
assertThat(serverContext.getDocument(uri)).isNull();
270+
271+
configuration.setExcludePaths(List.of());
272+
}
273+
274+
@Test
275+
void testDidChangeWatchedFiles_Changed_ExcludedPathNotAdded() throws IOException {
276+
serverContext.setConfigurationRoot(tempDir);
277+
configuration.setExcludePaths(List.of(".git"));
278+
279+
var excludedDir = tempDir.resolve(".git").toFile();
280+
excludedDir.mkdirs();
281+
var testFile = new File(excludedDir, "excluded_changed.bsl");
282+
FileUtils.copyFile(getFixtureFile("cli/test.bsl"), testFile);
283+
var uri = Absolute.uri(testFile.toURI());
284+
285+
assertThat(serverContext.getDocument(uri)).isNull();
286+
287+
var fileEvent = new FileEvent(uri.toString(), FileChangeType.Changed);
288+
workspaceService.didChangeWatchedFiles(new DidChangeWatchedFilesParams(List.of(fileEvent)));
289+
290+
await().pollDelay(Duration.ofMillis(150)).until(() -> true);
291+
assertThat(serverContext.getDocument(uri)).isNull();
292+
293+
configuration.setExcludePaths(List.of());
294+
}
295+
283296
@Test
284297
void testDidChangeConfiguration_WithNullSettings() {
285-
// given
286-
// Мокируем params с getSettings(), возвращающим null
287-
// Это соответствует реальному сценарию, когда некоторые LSP клиенты
288-
// отправляют workspace/didChangeConfiguration без настроек
289298
var params = mock(DidChangeConfigurationParams.class);
290299
when(params.getSettings()).thenReturn(null);
291300

292-
// when/then
293-
// Не должно быть исключений при вызове с null settings
294301
assertThatCode(() -> workspaceService.didChangeConfiguration(params))
295302
.doesNotThrowAnyException();
296303
}
297304

298305
/**
299-
* Создает временный тестовый файл с базовым содержимым.
306+
* Создаёт временный BSL-файл из фикстуры {@code cli/test.bsl}.
307+
*
308+
* @param fileName имя файла во временном каталоге
309+
* @return созданный файл
300310
*/
301311
private File createTestFile(String fileName) throws IOException {
302312
var file = tempDir.resolve(fileName).toFile();
303-
var content = """
304-
// Тестовый файл
305-
Процедура ТестоваяПроцедура()
306-
Сообщить("Тест");
307-
КонецПроцедуры
308-
""";
309-
FileUtils.writeStringToFile(file, content, StandardCharsets.UTF_8);
313+
FileUtils.copyFile(getFixtureFile("cli/test.bsl"), file);
310314
return file;
311315
}
316+
317+
/**
318+
* Возвращает файл фикстуры по пути относительно {@code src/test/resources}.
319+
*
320+
* @param resourcePath путь к ресурсу (например, {@code cli/test.bsl})
321+
* @return файл фикстуры
322+
*/
323+
private static File getFixtureFile(String resourcePath) throws IOException {
324+
var url = BSLWorkspaceServiceTest.class.getResource("/" + resourcePath);
325+
if (url == null) {
326+
return Path.of("src/test/resources", resourcePath).toAbsolutePath().toFile();
327+
}
328+
try {
329+
return Paths.get(url.toURI()).toFile();
330+
} catch (java.net.URISyntaxException e) {
331+
throw new IOException(e);
332+
}
333+
}
312334
}
313335

0 commit comments

Comments
 (0)