From 6cd39ffd8582a847c3499d3bc033a956d5105a6d Mon Sep 17 00:00:00 2001 From: labkey-jeckels Date: Thu, 19 Nov 2026 07:59:09 -0800 Subject: [PATCH 01/10] Add shared server test helpers and condense recent tests Moves recently added tests onto new shared helpers (JunitUtil, RequestTestUtil, QueryUpdateServiceTestUtil, SampleTypeTestHelper, AbstractContainerScopingTest) and folds near-duplicate tests into table-driven ones with the same coverage. --- .../AnnouncementsController.java | 209 ++++------ .../labkey/api/action/ApiQueryResponse.java | 39 +- .../assay/transform/PreparedTransform.java | 3 +- .../org/labkey/api/cache/CacheManager.java | 3 +- .../labkey/api/data/AsyncQueryRequest.java | 14 +- .../org/labkey/api/data/ConnectionUsage.java | 26 +- .../api/data/RepeatedCommitTaskMonitor.java | 59 +-- .../labkey/api/data/RequestCancellation.java | 101 +---- .../org/labkey/api/data/RequestTestUtil.java | 91 +++++ api/src/org/labkey/api/data/SQLFragment.java | 12 +- api/src/org/labkey/api/data/Table.java | 19 +- .../labkey/api/data/TransactionFilter.java | 67 ++-- .../api/data/dialect/PostgresSnapshot.java | 4 +- .../labkey/api/data/queryprofiler/Query.java | 11 +- .../api/data/queryprofiler/QueryProfiler.java | 17 +- .../QueryDataIteratorBuilder.java | 26 +- .../api/dataiterator/SimpleTranslator.java | 3 +- .../org/labkey/api/exp/OntologyManager.java | 23 +- .../api/exp/api/SampleTypeTestHelper.java | 70 ++++ .../labkey/api/exp/property/DomainUtil.java | 67 +--- .../labkey/api/mcp/AbstractAgentAction.java | 366 +++++------------- .../org/labkey/api/module/ModuleLoader.java | 66 +--- .../api/query/QueryUpdateServiceTestUtil.java | 80 ++++ .../FilterSuggestionTestContext.java | 28 ++ .../api/reports/ExternalScriptEngine.java | 23 +- .../AbstractContainerScopingTest.java | 39 +- .../org/labkey/api/util/ExceptionUtil.java | 7 +- api/src/org/labkey/api/util/JunitUtil.java | 70 ++++ .../org/labkey/api/util/TracedOperation.java | 16 +- .../dsmiley/httpproxy/LabKeyProxyServlet.java | 96 ++--- assay/src/org/labkey/assay/AssayManager.java | 2 +- .../org/labkey/audit/model/LogManager.java | 18 +- .../org/labkey/core/ChatHistoryManager.java | 38 +- .../core/LabKeyAssistantAgentAction.java | 28 +- core/src/org/labkey/core/QuartzShutdown.java | 5 +- .../core/security/SecurityController.java | 9 +- .../test/tests/RequestCancellationTest.java | 76 +--- ...llegalFieldNameMetricsMaintenanceTask.java | 63 +-- ...pecialCharacterMetricsMaintenanceTask.java | 7 +- .../api/DataMapDiffColumnTestCase.java | 2 +- .../experiment/api/ExpMaterialTableImpl.java | 38 +- .../experiment/api/ExperimentServiceImpl.java | 27 +- .../SampleProvidedAmountAuditTestCase.java | 44 +-- .../SampleTypeFilterSuggestionProvider.java | 53 +-- .../experiment/api/SampleTypeServiceImpl.java | 16 +- .../list/model/ListQueryUpdateService.java | 136 ++----- .../labkey/pipeline/PipelineController.java | 32 +- .../org/labkey/query/QueryServiceImpl.java | 58 ++- query/src/org/labkey/query/sql/Method.java | 3 +- .../query/suggestions/ColumnFactsCache.java | 45 +-- .../labkey/search/model/SecurityQuery.java | 57 +-- .../reports/ReportsController.java | 33 +- wiki/src/org/labkey/wiki/WikiController.java | 2 +- wiki/src/org/labkey/wiki/WikiTOC.java | 10 +- 54 files changed, 997 insertions(+), 1460 deletions(-) create mode 100644 api/src/org/labkey/api/data/RequestTestUtil.java create mode 100644 api/src/org/labkey/api/exp/api/SampleTypeTestHelper.java create mode 100644 api/src/org/labkey/api/query/QueryUpdateServiceTestUtil.java create mode 100644 api/src/org/labkey/api/query/suggestions/FilterSuggestionTestContext.java diff --git a/announcements/src/org/labkey/announcements/AnnouncementsController.java b/announcements/src/org/labkey/announcements/AnnouncementsController.java index 0ce6173167c..e1632935b0c 100644 --- a/announcements/src/org/labkey/announcements/AnnouncementsController.java +++ b/announcements/src/org/labkey/announcements/AnnouncementsController.java @@ -27,6 +27,7 @@ import org.json.JSONObject; import org.junit.Before; import org.junit.Test; +import org.labkey.announcements.config.AnnouncementEmailConfig; import org.labkey.announcements.model.AnnouncementDigestProvider; import org.labkey.announcements.model.AnnouncementFullModel; import org.labkey.announcements.model.AnnouncementManager; @@ -77,6 +78,7 @@ import org.labkey.api.data.RenderContext; import org.labkey.api.data.SimpleFilter; import org.labkey.api.data.SqlExecutor; +import org.labkey.api.data.Table; import org.labkey.api.data.TableInfo; import org.labkey.api.data.TableSelector; import org.labkey.api.message.digest.DailyMessageDigest; @@ -2941,6 +2943,19 @@ public Object execute(ThreadForm form, BindException errors) } } + private static AnnouncementModel insertTestPost(Container c, User user, String title, @Nullable AnnouncementModel parent, User... members) throws Exception + { + AnnouncementModel post = new AnnouncementModel(); + post.setTitle(title); + post.setBody("body"); + if (parent != null) + post.setParent(parent.getEntityId()); + // insertAnnouncement rebuilds memberListIds from memberListInput, so set the input, not the ids directly. + if (members.length > 0) + post.setMemberListInput(Arrays.stream(members).map(member -> String.valueOf(member.getUserId())).collect(Collectors.joining("\n"))); + return AnnouncementManager.insertAnnouncement(c, user, post, null, false); + } + public static class ContainerScopingTestCase extends AbstractContainerScopingTest { private Container _folderA; @@ -2954,10 +2969,7 @@ public void createThread() throws Exception // (cross-container by design), so each test addresses B's thread through a folder-A request. _folderA = getSharedContainer("A"); _folderB = getSharedContainer("B"); - AnnouncementModel insert = new AnnouncementModel(); - insert.setTitle("Container scoping test thread"); - insert.setBody("body"); - _thread = AnnouncementManager.insertAnnouncement(_folderB, getAdmin(), insert, null, false); + _thread = insertTestPost(_folderB, getAdmin(), "Container scoping test thread", null); } @Test @@ -2993,12 +3005,7 @@ public void testSubscribeThreadEnforcesSecureBoardMemberList() throws Exception User member = createUserInRole(secure, ReaderRole.class); User nonMember = createUserInRole(secure, ReaderRole.class); - AnnouncementModel insert = new AnnouncementModel(); - insert.setTitle("Secure member-list test thread"); - insert.setBody("body"); - // insertAnnouncement rebuilds memberListIds from memberListInput, so set the input, not the ids directly. - insert.setMemberListInput(String.valueOf(member.getUserId())); - AnnouncementModel secureThread = AnnouncementManager.insertAnnouncement(secure, getAdmin(), insert, null, false); + AnnouncementModel secureThread = insertTestPost(secure, getAdmin(), "Secure member-list test thread", null, member); ActionURL url = new ActionURL(SubscribeThreadAction.class, secure) .addParameter("threadId", secureThread.getEntityId()); @@ -3024,23 +3031,9 @@ public void testQueryEnforcesSecureBoardMemberList() throws Exception for (User user : List.of(member, nonMember, editor)) grantRole(user, _folderA, ReaderRole.class); - AnnouncementModel memberThread = new AnnouncementModel(); - memberThread.setTitle("Member thread"); - memberThread.setBody("body"); - memberThread.setMemberListInput(String.valueOf(member.getUserId())); - memberThread = AnnouncementManager.insertAnnouncement(secure, getAdmin(), memberThread, null, false); - - AnnouncementModel response = new AnnouncementModel(); - response.setTitle("Member thread response"); - response.setBody("body"); - response.setParent(memberThread.getEntityId()); - response.setMemberListInput(String.valueOf(member.getUserId())); - response = AnnouncementManager.insertAnnouncement(secure, getAdmin(), response, null, false); - - AnnouncementModel otherThread = new AnnouncementModel(); - otherThread.setTitle("Other thread"); - otherThread.setBody("body"); - otherThread = AnnouncementManager.insertAnnouncement(secure, getAdmin(), otherThread, null, false); + AnnouncementModel memberThread = insertTestPost(secure, getAdmin(), "Member thread", null, member); + AnnouncementModel response = insertTestPost(secure, getAdmin(), "Member thread response", memberThread, member); + AnnouncementModel otherThread = insertTestPost(secure, getAdmin(), "Other thread", null); Set all = Set.of(memberThread.getRowId(), response.getRowId(), otherThread.getRowId()); assertEquals(Set.of(), queryRowIds(nonMember, secure, AnnouncementSchema.ANNOUNCEMENT_TABLE_NAME)); @@ -3075,19 +3068,9 @@ public void testSubscriptionTableEnforcesSecureBoardMemberList() throws Exceptio User editor = createUserInRole(secure, EditorRole.class); grantRole(nonMember, _folderA, ReaderRole.class); - AnnouncementModel thread = new AnnouncementModel(); - thread.setTitle("Member thread"); - thread.setBody("body"); - thread.setMemberListInput(String.valueOf(member.getUserId())); - thread = AnnouncementManager.insertAnnouncement(secure, getAdmin(), thread, null, false); - + AnnouncementModel thread = insertTestPost(secure, getAdmin(), "Member thread", null, member); // The thread's effective member list lives on its latest post - AnnouncementModel response = new AnnouncementModel(); - response.setTitle("Member thread response"); - response.setBody("body"); - response.setParent(thread.getEntityId()); - response.setMemberListInput(String.valueOf(member.getUserId())); - response = AnnouncementManager.insertAnnouncement(secure, getAdmin(), response, null, false); + AnnouncementModel response = insertTestPost(secure, getAdmin(), "Member thread response", thread, member); for (Container from : List.of(secure, _folderA)) { @@ -3148,7 +3131,7 @@ public void testSubscriptionTablesRequireAdminOfRowFolder() throws Exception Map row = new HashMap<>(Map.of("User", victim.getUserId(), "Folder", _folderB.getId(), "EmailOption", EmailOption.MESSAGES_ALL.getValue())); forumSubscriptionService(adminOfB).insertRows(adminOfB, _folderB, List.of(row), new BatchValidationException(), null, null); - new SqlExecutor(CommSchema.getInstance().getSchema()).execute("INSERT INTO comm.userlist (UserId, MessageId) VALUES (?, ?)", victim.getUserId(), _thread.getRowId()); + Table.insert(null, CommSchema.getInstance().getTableInfoUserList(), new HashMap<>(Map.of("UserId", victim.getUserId(), "MessageId", _thread.getRowId()))); // Both query from A across all folders; only B's admin sees B's rows for another user assertEquals(Map.of(AnnouncementSchema.FORUM_SUBSCRIPTION_TABLE_NAME, 0L, AnnouncementSchema.ANNOUNCEMENT_SUBSCRIPTION_TABLE_NAME, 0L), subscriptionCounts(adminOfA, victim)); @@ -3161,16 +3144,13 @@ public void testSubscriptionTablesRequireAdminOfRowFolder() throws Exception forumSubscriptionService(adminOfB).updateRows(adminOfB, _folderB, List.of(update), List.of(key), errors, null, null); assertFalse(errors.getMessage(), errors.hasErrors()); TableInfo emailPrefs = CoreSchema.getInstance().getTableInfoEmailPrefs(); - assertEquals(Integer.valueOf(mine), new TableSelector(emailPrefs, List.of(emailPrefs.getColumn("EmailOptionId")), new SimpleFilter(FieldKey.fromParts("UserId"), victim.getUserId()).addCondition(FieldKey.fromParts("Type"), "messages"), null).getObject(Integer.class)); + assertEquals(Integer.valueOf(mine), new TableSelector(emailPrefs, List.of(emailPrefs.getColumn("EmailOptionId")), new SimpleFilter(FieldKey.fromParts("UserId"), victim.getUserId()).addCondition(FieldKey.fromParts("Type"), AnnouncementEmailConfig.TYPE), null).getObject(Integer.class)); Map noSuchUser = new HashMap<>(Map.of("User", Integer.MAX_VALUE, "Folder", _folderB.getId(), "EmailOption", mine)); assertThrows(QueryUpdateServiceException.class, () -> forumSubscriptionService(adminOfB).insertRows(adminOfB, _folderB, List.of(noSuchUser), new BatchValidationException(), null, null)); // Admin moves the other user's subscription to another thread, then removes it - AnnouncementModel otherThread = new AnnouncementModel(); - otherThread.setTitle("Other thread"); - otherThread.setBody("body"); - otherThread = AnnouncementManager.insertAnnouncement(_folderB, getAdmin(), otherThread, null, false); + AnnouncementModel otherThread = insertTestPost(_folderB, getAdmin(), "Other thread", null); QueryUpdateService qus = new AnnouncementSchema(adminOfB, _folderB).getTable(AnnouncementSchema.ANNOUNCEMENT_SUBSCRIPTION_TABLE_NAME).getUpdateService(); Map oldKey = new HashMap<>(Map.of("Announcement", _thread.getRowId(), "User", victim.getUserId())); Map moved = new HashMap<>(Map.of("Announcement", otherThread.getRowId(), "User", victim.getUserId())); @@ -3208,7 +3188,7 @@ private QueryUpdateService forumSubscriptionService(User user) private long forumSubscriptionCount(User user) { - return new TableSelector(CoreSchema.getInstance().getTableInfoEmailPrefs(), new SimpleFilter(FieldKey.fromParts("UserId"), user.getUserId()).addCondition(FieldKey.fromParts("Type"), "messages"), null).getRowCount(); + return new TableSelector(CoreSchema.getInstance().getTableInfoEmailPrefs(), new SimpleFilter(FieldKey.fromParts("UserId"), user.getUserId()).addCondition(FieldKey.fromParts("Type"), AnnouncementEmailConfig.TYPE), null).getRowCount(); } private void insertSubscription(User user, Container from, AnnouncementModel target) throws Exception @@ -3236,14 +3216,8 @@ private boolean canRead(User user, Container c, AnnouncementModel thread) public void testModerationTablesRequireAdmin() throws Exception { TableInfo announcements = CommSchema.getInstance().getTableInfoAnnouncements(); - AnnouncementModel pending = new AnnouncementModel(); - pending.setTitle("Pending review"); - pending.setBody("body"); - pending = AnnouncementManager.insertAnnouncement(_folderB, getAdmin(), pending, null, false); - AnnouncementModel spam = new AnnouncementModel(); - spam.setTitle("Spam"); - spam.setBody("body"); - spam = AnnouncementManager.insertAnnouncement(_folderB, getAdmin(), spam, null, false); + AnnouncementModel pending = insertTestPost(_folderB, getAdmin(), "Pending review", null); + AnnouncementModel spam = insertTestPost(_folderB, getAdmin(), "Spam", null); new SqlExecutor(announcements.getSchema()).execute("UPDATE " + announcements.getSelectName() + " SET Approved = NULL WHERE RowId IN (?, ?)", pending.getRowId(), spam.getRowId()); AnnouncementManager.markAsSpam(_folderB, spam); Set mine = Set.of(pending.getRowId(), spam.getRowId()); @@ -3315,9 +3289,10 @@ private Set queryCurrentFolderRowIds(User user, Container folder) // GH Issue 1444 public static class MemberListTestCase extends AbstractContainerScopingTest { - private Container createBoard(String name, String secure) + // Shared across tests, which reset the settings and assert only on their own threads + private Container getBoard(String secure) { - Container c = createContainer(name); + Container c = getSharedContainer(secure); Settings settings = AnnouncementManager.getMessageBoardSettings(c); settings.setSecure(secure); settings.setMemberList(true); @@ -3327,11 +3302,36 @@ private Container createBoard(String name, String secure) private AnnouncementModel insertThread(Container c, User... members) throws Exception { - AnnouncementModel insert = new AnnouncementModel(); - insert.setTitle("Member list test thread"); - insert.setBody("body"); - insert.setMemberListInput(Arrays.stream(members).map(member -> String.valueOf(member.getUserId())).collect(Collectors.joining("\n"))); - return AnnouncementManager.insertAnnouncement(c, getAdmin(), insert, null, false); + return insertTestPost(c, getAdmin(), "Member list test thread", null, members); + } + + private AnnouncementModel insertResponse(Container c, AnnouncementModel thread, User... members) throws Exception + { + return insertTestPost(c, getAdmin(), "Response", thread, members); + } + + private static ActionURL apiReplyUrl(Container c, AnnouncementModel parent) + { + return new ActionURL(CreateThreadAction.class, c) + .addParameter("reply", true) + .addParameter("thread.parent", parent.getEntityId()) + .addParameter("thread.title", "Reply") + .addParameter("thread.body", "reply body"); + } + + private static ActionURL uiReplyUrl(Container c, AnnouncementModel parent) + { + return new ActionURL(RespondAction.class, c) + .addParameter("parentId", parent.getEntityId()) + .addParameter("title", "Reply") + .addParameter("body", "reply body"); + } + + private static ActionURL updateUrl(Container c, AnnouncementModel thread) + { + return new ActionURL(UpdateThreadAction.class, c) + .addParameter("thread.rowId", thread.getRowId()) + .addParameter("thread.body", "updated body"); } private List currentMemberList(Container c, AnnouncementModel thread) @@ -3342,20 +3342,13 @@ private List currentMemberList(Container c, AnnouncementModel thread) @Test public void testSecureReplyRequiresMembership() throws Exception { - Container secure = createBoard("Secure", Settings.SECURE_WITHOUT_EMAIL); + Container secure = getBoard(Settings.SECURE_WITHOUT_EMAIL); User member = createUserInRole(secure, MessageBoardContributorRole.class); User nonMember = createUserInRole(secure, MessageBoardContributorRole.class); AnnouncementModel thread = insertThread(secure, member); - ActionURL apiReply = new ActionURL(CreateThreadAction.class, secure) - .addParameter("reply", true) - .addParameter("thread.parent", thread.getEntityId()) - .addParameter("thread.title", "Reply") - .addParameter("thread.body", "reply body"); - ActionURL uiReply = new ActionURL(RespondAction.class, secure) - .addParameter("parentId", thread.getEntityId()) - .addParameter("title", "Reply") - .addParameter("body", "reply body"); + ActionURL apiReply = apiReplyUrl(secure, thread); + ActionURL uiReply = uiReplyUrl(secure, thread); assertStatus(HttpServletResponse.SC_FORBIDDEN, post(apiReply, nonMember)); assertStatus(HttpServletResponse.SC_FORBIDDEN, post(uiReply, nonMember)); @@ -3369,86 +3362,53 @@ public void testSecureReplyRequiresMembership() throws Exception @Test public void testRemovedMemberCannotReplyViaOldResponse() throws Exception { - Container secure = createBoard("SecureRemoved", Settings.SECURE_WITHOUT_EMAIL); + Container secure = getBoard(Settings.SECURE_WITHOUT_EMAIL); User formerMember = createUserInRole(secure, MessageBoardContributorRole.class); AnnouncementModel thread = insertThread(secure, formerMember); // The first response still records formerMember on its member list; the second removes them from the thread - AnnouncementModel oldResponse = insertResponse(secure, thread, String.valueOf(formerMember.getUserId())); - insertResponse(secure, thread, null); + AnnouncementModel oldResponse = insertResponse(secure, thread, formerMember); + insertResponse(secure, thread); assertEquals(List.of(), currentMemberList(secure, thread)); - ActionURL viaOldResponse = new ActionURL(RespondAction.class, secure) - .addParameter("parentId", oldResponse.getEntityId()) - .addParameter("title", "Reply") - .addParameter("body", "reply body"); - ActionURL viaThread = new ActionURL(RespondAction.class, secure) - .addParameter("parentId", thread.getEntityId()) - .addParameter("title", "Reply") - .addParameter("body", "reply body"); - - assertStatus(HttpServletResponse.SC_NOT_FOUND, post(viaOldResponse, formerMember)); - assertStatus(HttpServletResponse.SC_FORBIDDEN, post(viaThread, formerMember)); + assertStatus(HttpServletResponse.SC_NOT_FOUND, post(uiReplyUrl(secure, oldResponse), formerMember)); + assertStatus(HttpServletResponse.SC_FORBIDDEN, post(uiReplyUrl(secure, thread), formerMember)); } @Test public void testApiReplyToResponseRejected() throws Exception { - Container secure = createBoard("SecureApiResponse", Settings.SECURE_WITHOUT_EMAIL); + Container secure = getBoard(Settings.SECURE_WITHOUT_EMAIL); User member = createUserInRole(secure, MessageBoardContributorRole.class); AnnouncementModel thread = insertThread(secure, member); - AnnouncementModel response = insertResponse(secure, thread, String.valueOf(member.getUserId())); + AnnouncementModel response = insertResponse(secure, thread, member); - ActionURL viaResponse = new ActionURL(CreateThreadAction.class, secure) - .addParameter("reply", true) - .addParameter("thread.parent", response.getEntityId()) - .addParameter("thread.title", "Reply") - .addParameter("thread.body", "reply body"); - - assertStatus(HttpServletResponse.SC_BAD_REQUEST, post(viaResponse, member)); + assertStatus(HttpServletResponse.SC_BAD_REQUEST, post(apiReplyUrl(secure, response), member)); assertEquals(1, AnnouncementManager.getAnnouncement(secure, thread.getEntityId()).getResponses().size()); } - private AnnouncementModel insertResponse(Container c, AnnouncementModel thread, String memberListInput) throws Exception - { - AnnouncementModel response = new AnnouncementModel(); - response.setParent(thread.getEntityId()); - response.setTitle("Response"); - response.setBody("response body"); - response.setMemberListInput(memberListInput); - return AnnouncementManager.insertAnnouncement(c, getAdmin(), response, null, false); - } - @Test public void testApiUpdateRetainsMemberList() throws Exception { - Container board = createBoard("Normal", Settings.SECURE_OFF); + Container board = getBoard(Settings.SECURE_OFF); User member = createUserInRole(board, MessageBoardContributorRole.class); AnnouncementModel thread = insertThread(board, member); - ActionURL update = new ActionURL(UpdateThreadAction.class, board) - .addParameter("thread.rowId", thread.getRowId()) - .addParameter("thread.body", "updated body"); - - assertStatus(HttpServletResponse.SC_OK, post(update, getAdmin())); + assertStatus(HttpServletResponse.SC_OK, post(updateUrl(board, thread), getAdmin())); assertEquals(List.of(member.getUserId()), currentMemberList(board, thread)); } @Test public void testApiUpdateRetainsPostMemberList() throws Exception { - Container board = createBoard("NormalResponded", Settings.SECURE_OFF); + Container board = getBoard(Settings.SECURE_OFF); User member = createUserInRole(board, MessageBoardContributorRole.class); User other = createUserInRole(board, MessageBoardContributorRole.class); AnnouncementModel thread = insertThread(board, member, other); - insertResponse(board, thread, String.valueOf(member.getUserId())); - - ActionURL update = new ActionURL(UpdateThreadAction.class, board) - .addParameter("thread.rowId", thread.getRowId()) - .addParameter("thread.body", "updated body"); + insertResponse(board, thread, member); // Editing the original must keep its own list, not copy the latest response's list onto it - assertStatus(HttpServletResponse.SC_OK, post(update, getAdmin())); + assertStatus(HttpServletResponse.SC_OK, post(updateUrl(board, thread), getAdmin())); assertEquals(Set.of(member.getUserId(), other.getUserId()), new HashSet<>(AnnouncementManager.getPostMemberList(thread.getRowId()))); assertEquals(List.of(member.getUserId()), currentMemberList(board, thread)); } @@ -3456,26 +3416,17 @@ public void testApiUpdateRetainsPostMemberList() throws Exception @Test public void testApiWritesDropMembersWhoCannotRead() throws Exception { - Container board = createBoard("NormalInactive", Settings.SECURE_OFF); + Container board = getBoard(Settings.SECURE_OFF); User member = createUserInRole(board, MessageBoardContributorRole.class); User inactive = createUserInRole(board, MessageBoardContributorRole.class); AnnouncementModel updated = insertThread(board, member, inactive); AnnouncementModel repliedTo = insertThread(board, member, inactive); UserManager.setUserActive(getAdmin(), inactive, false); - ActionURL update = new ActionURL(UpdateThreadAction.class, board) - .addParameter("thread.rowId", updated.getRowId()) - .addParameter("thread.body", "updated body"); - ActionURL apiReply = new ActionURL(CreateThreadAction.class, board) - .addParameter("reply", true) - .addParameter("thread.parent", repliedTo.getEntityId()) - .addParameter("thread.title", "Reply") - .addParameter("thread.body", "reply body"); - // Without the filter, validation rejects these writes because a listed member can't read the thread - assertStatus(HttpServletResponse.SC_OK, post(update, getAdmin())); + assertStatus(HttpServletResponse.SC_OK, post(updateUrl(board, updated), getAdmin())); assertEquals(List.of(member.getUserId()), currentMemberList(board, updated)); - assertStatus(HttpServletResponse.SC_OK, post(apiReply, member)); + assertStatus(HttpServletResponse.SC_OK, post(apiReplyUrl(board, repliedTo), member)); assertEquals(List.of(member.getUserId()), currentMemberList(board, repliedTo)); } } diff --git a/api/src/org/labkey/api/action/ApiQueryResponse.java b/api/src/org/labkey/api/action/ApiQueryResponse.java index 1bede61ca9b..24db9311516 100644 --- a/api/src/org/labkey/api/action/ApiQueryResponse.java +++ b/api/src/org/labkey/api/action/ApiQueryResponse.java @@ -19,13 +19,14 @@ import org.apache.commons.lang3.StringUtils; import org.json.JSONArray; import org.json.JSONObject; -import org.junit.After; +import org.junit.AfterClass; import org.junit.Assert; -import org.junit.Before; +import org.junit.BeforeClass; import org.junit.Test; import org.labkey.api.collections.ResultSetRowMapFactory; import org.labkey.api.data.ColumnInfo; import org.labkey.api.data.Container; +import org.labkey.api.data.ContainerFilter; import org.labkey.api.data.ContainerManager; import org.labkey.api.data.DataRegion; import org.labkey.api.data.DetailsColumn; @@ -40,6 +41,7 @@ import org.labkey.api.data.UpdateColumn; import org.labkey.api.exp.PropertyColumn; import org.labkey.api.query.FieldKey; +import org.labkey.api.query.QueryParam; import org.labkey.api.query.QueryService; import org.labkey.api.query.QuerySettings; import org.labkey.api.query.QueryView; @@ -801,11 +803,12 @@ public static class TestCase extends Assert { private static final String FOLDER_NAME = "ApiQueryResponseTest"; - private User _user; - private Container _folder; + private static User _user; + private static Container _folder; - @Before - public void setUp() throws Exception + // The tests only read, so one fixture serves the class + @BeforeClass + public static void setUp() { _user = TestContext.get().getUser(); Container testContainer = JunitUtil.getTestContainer(); @@ -817,17 +820,18 @@ public void setUp() throws Exception ContainerManager.createContainer(_folder, "child2", _user); } - @After - public void tearDown() throws Exception + @AfterClass + public static void tearDown() { if (null != _folder) ContainerManager.deleteAll(_folder, _user); } + /** Each pair renders the same rows streamed and through the map-based writeRow */ @Test public void testStreamedRowsMatchMap() throws Exception { - assertRowsMatch(view -> new ApiQueryResponse(view, false, true, "core", "Containers", 0, null, false, true, true, true), + assertRowsMatch("ApiQueryResponse", view -> new ApiQueryResponse(view, false, true, "core", "Containers", 0, null, false, true, true, true), view -> new ApiQueryResponse(view, false, true, "core", "Containers", 0, null, false, true, true, true) { @Override @@ -836,12 +840,7 @@ protected void writeRow(ApiResponseWriter writer) throws IOException writer.writeListEntry(getRow()); } }); - } - - @Test - public void testStreamedExtendedRowsMatchMap() throws Exception - { - assertRowsMatch(view -> configure(new ExtendedApiQueryResponse(view, false, true, "core", "Containers", 0, null, false, true, true)), + assertRowsMatch("ExtendedApiQueryResponse", view -> configure(new ExtendedApiQueryResponse(view, false, true, "core", "Containers", 0, null, false, true, true)), view -> configure(new ExtendedApiQueryResponse(view, false, true, "core", "Containers", 0, null, false, true, true) { @Override @@ -859,19 +858,19 @@ private static ApiQueryResponse configure(ExtendedApiQueryResponse response) return response; } - private void assertRowsMatch(Function streamed, Function mapped) throws Exception + private void assertRowsMatch(String name, Function streamed, Function mapped) throws Exception { JSONArray expected = render(mapped); - assertEquals("Expected the folder and its two children", 3, expected.length()); - assertEquals(expected.toList(), render(streamed).toList()); + assertEquals(name + ": expected the folder and its two children", 3, expected.length()); + assertEquals(name, expected.toList(), render(streamed).toList()); } private JSONArray render(Function factory) throws Exception { UserSchema schema = QueryService.get().getUserSchema(_user, _folder, "core"); MutablePropertyValues mpv = new MutablePropertyValues(); - mpv.addPropertyValue("query.queryName", "Containers"); - mpv.addPropertyValue("query" + DataRegion.CONTAINER_FILTER_NAME, "CurrentAndSubfolders"); + mpv.addPropertyValue("query." + QueryParam.queryName, "Containers"); + mpv.addPropertyValue("query" + DataRegion.CONTAINER_FILTER_NAME, ContainerFilter.Type.CurrentAndSubfolders.name()); mpv.addPropertyValue("query.sort", "RowId"); QuerySettings settings = schema.getSettings(mpv, "query"); diff --git a/api/src/org/labkey/api/assay/transform/PreparedTransform.java b/api/src/org/labkey/api/assay/transform/PreparedTransform.java index 9848cf76883..a9e8d53fdc4 100644 --- a/api/src/org/labkey/api/assay/transform/PreparedTransform.java +++ b/api/src/org/labkey/api/assay/transform/PreparedTransform.java @@ -19,6 +19,7 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.json.JSONObject; +import org.labkey.api.audit.AbstractAuditTypeProvider; import org.labkey.api.audit.AuditLogService; import org.labkey.api.audit.TransactionAuditProvider; import org.junit.After; @@ -335,7 +336,7 @@ private static PendingFileAudit audit(String comment, FileLike file) private static List selectEvents(String comment) { - SimpleFilter filter = new SimpleFilter(FieldKey.fromParts("Comment"), comment); + SimpleFilter filter = new SimpleFilter(FieldKey.fromParts(AbstractAuditTypeProvider.COLUMN_NAME_COMMENT), comment); return AuditLogService.get().getAuditEvents(JunitUtil.getTestContainer(), TestContext.get().getUser(), FileSystemAuditProvider.EVENT_TYPE, filter, null); } } diff --git a/api/src/org/labkey/api/cache/CacheManager.java b/api/src/org/labkey/api/cache/CacheManager.java index 59a631f26fa..c30df5762a5 100644 --- a/api/src/org/labkey/api/cache/CacheManager.java +++ b/api/src/org/labkey/api/cache/CacheManager.java @@ -24,6 +24,7 @@ import org.labkey.api.cache.ehcache.EhCacheProvider; import org.labkey.api.collections.CollectionUtils; import org.labkey.api.data.Container; +import org.labkey.api.data.ContainerManager; import org.labkey.api.data.Project; import org.labkey.api.mbean.LabKeyManagement; import org.labkey.api.security.User; @@ -296,7 +297,7 @@ public void testContainerKeyRejected() { try (Cache cache = getTemporaryCache(Object.class, 10, MINUTE, "Container key test", null)) { - Container c = new Container(null, "", GUID.makeGUID(), 1, 1, null, 0, false); + Container c = ContainerManager.createFakeContainer("CacheKeyTest", null); assertThrows(IllegalArgumentException.class, () -> cache.put(c, "value")); assertThrows(IllegalArgumentException.class, () -> cache.put(c, "value", MINUTE)); assertThrows(IllegalArgumentException.class, () -> cache.get(c, null, (key, argument) -> "loaded")); diff --git a/api/src/org/labkey/api/data/AsyncQueryRequest.java b/api/src/org/labkey/api/data/AsyncQueryRequest.java index 0804b59b511..681dcc01d57 100644 --- a/api/src/org/labkey/api/data/AsyncQueryRequest.java +++ b/api/src/org/labkey/api/data/AsyncQueryRequest.java @@ -559,16 +559,8 @@ public void testInterruptReleasesConnection() throws Exception } }, "AsyncQueryRequest interrupt test " + i); - long start = System.currentTimeMillis(); requestThread.start(); - while (ConnectionWrapper.getConnectionsByScopeForEffectiveThread(requestThread).isEmpty() && System.currentTimeMillis() - start < 10_000) - { - //noinspection BusyWait - Thread.sleep(50); - } - // Let the statement reach the server - Thread.sleep(300); - ConnectionWrapper.getConnectionsByScopeForEffectiveThread(requestThread).values().forEach(c -> c.forEach(w -> spids.add(w.getSPID()))); + RequestTestUtil.awaitStatementStarted(requestThread).values().forEach(c -> c.forEach(w -> spids.add(w.getSPID()))); requestThread.interrupt(); requestThread.join(30_000); @@ -578,7 +570,7 @@ public void testInterruptReleasesConnection() throws Exception assertTrue("Request thread's connection holder is still referenced", holderReleased.get()); assertNull("Next query on the request thread failed", nextQueryFailure.get()); assertFalse("Interrupted query had no connections", spids.isEmpty()); - assertEquals("Cancelled session went back to the pool", 0, RequestCancellation.TestCase.countLiveBackends(scope, spids)); + assertEquals("Cancelled session went back to the pool", 0, RequestTestUtil.countLiveBackends(scope, spids)); } } @@ -663,7 +655,7 @@ public void testStuckWorkerDetached() throws Exception assertTrue("Worker didn't finish", workerDone.await(10, TimeUnit.SECONDS)); assertNull("Worker's connection release failed", workerFailure.get()); - assertEquals("Stuck worker's session went back to the pool", 0, RequestCancellation.TestCase.countLiveBackends(scope, Set.of(workerSpid.get()))); + assertEquals("Stuck worker's session went back to the pool", 0, RequestTestUtil.countLiveBackends(scope, Set.of(workerSpid.get()))); } /** A query that reaches the database only after its request stopped waiting, where Statement.cancel() can't stop it, must still be cancelled */ diff --git a/api/src/org/labkey/api/data/ConnectionUsage.java b/api/src/org/labkey/api/data/ConnectionUsage.java index f05ab6aa8ad..adf17a8e047 100644 --- a/api/src/org/labkey/api/data/ConnectionUsage.java +++ b/api/src/org/labkey/api/data/ConnectionUsage.java @@ -21,6 +21,7 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import org.labkey.api.util.JunitUtil; import java.sql.Connection; import java.util.ArrayList; @@ -240,34 +241,17 @@ public void restore() _enabled = _wasEnabled; } - private static Snapshot measureOnNewThread(ThrowingRunnable block) throws Exception + private static Snapshot measureOnNewThread(JunitUtil.ThrowingRunnable block) throws Exception { AtomicReference result = new AtomicReference<>(); - AtomicReference failure = new AtomicReference<>(); - Thread thread = new Thread(() -> { + JunitUtil.runOnNewThread("ConnectionUsage test", () -> { Mark mark = mark(); - try - { - block.run(); - } - catch (Throwable t) - { - failure.set(t); - } + block.run(); result.set(measure(mark)); - }, "ConnectionUsage test"); - thread.start(); - thread.join(); - if (null != failure.get()) - throw new AssertionError("Failure on test thread", failure.get()); + }); return result.get(); } - private interface ThrowingRunnable - { - void run() throws Exception; - } - @Test public void testConcurrentPooledBorrows() throws Exception { diff --git a/api/src/org/labkey/api/data/RepeatedCommitTaskMonitor.java b/api/src/org/labkey/api/data/RepeatedCommitTaskMonitor.java index 56c6535044a..4d1e836b62a 100644 --- a/api/src/org/labkey/api/data/RepeatedCommitTaskMonitor.java +++ b/api/src/org/labkey/api/data/RepeatedCommitTaskMonitor.java @@ -368,14 +368,6 @@ public void tallyIsPerQueue() public static class IntegrationTestCase extends Assert { - private record ValueTask(int i) implements Runnable - { - @Override - public void run() - { - } - } - private static class NoOpAccumulatingTask extends AccumulatingCommitTask { NoOpAccumulatingTask() @@ -417,44 +409,23 @@ private static int tallyTransactions(RepeatedTaskWarning key) return tally != null ? tally.transactions() : 0; } - @Test - public void warnsAtTheThreshold() - { - assertEquals(1, warningsFor(true, THRESHOLD, i -> scope().addCommitTask(TestCase.task(i), CommitTaskOption.POSTCOMMIT))); - } - - @Test - public void silentBelowTheThreshold() - { - assertEquals(0, warningsFor(true, THRESHOLD - 1, i -> scope().addCommitTask(TestCase.task(i), CommitTaskOption.POSTCOMMIT))); - } + private record Case(String name, int expectedWarnings, boolean commit, int count, IntConsumer register) {} @Test - public void silentForDedupedTasks() - { - assertEquals(0, warningsFor(true, THRESHOLD, i -> scope().addCommitTask(new ValueTask(0), CommitTaskOption.POSTCOMMIT))); - } - - @Test - public void silentForAccumulatingTask() - { - assertEquals(0, warningsFor(true, THRESHOLD, i -> new NoOpAccumulatingTask().register(scope(), List.of(i), CommitTaskOption.POSTCOMMIT))); - } - - @Test - public void warnsForEachQueue() - { - assertEquals(2, warningsFor(true, THRESHOLD, i -> { - scope().addCommitTask(TestCase.task(i), CommitTaskOption.PRECOMMIT); - scope().addCommitTask(TestCase.task(i), CommitTaskOption.POSTCOMMIT); - })); - } - - @Test - public void warnsOnlyForTheQueueThatRuns() - { - assertEquals(0, warningsFor(false, THRESHOLD, i -> scope().addCommitTask(TestCase.task(i), CommitTaskOption.POSTCOMMIT))); - assertEquals(1, warningsFor(false, THRESHOLD, i -> scope().addCommitTask(TestCase.task(i), CommitTaskOption.POSTROLLBACK))); + public void testWarnings() + { + IntConsumer postCommit = i -> scope().addCommitTask(TestCase.task(i), CommitTaskOption.POSTCOMMIT); + for (Case c : List.of( + new Case("at the threshold", 1, true, THRESHOLD, postCommit), + new Case("below the threshold", 0, true, THRESHOLD - 1, postCommit), + new Case("deduped tasks", 0, true, THRESHOLD, _ -> scope().addCommitTask(new TestCase.KeyedTask(0), CommitTaskOption.POSTCOMMIT)), + new Case("accumulating task", 0, true, THRESHOLD, i -> new NoOpAccumulatingTask().register(scope(), List.of(i), CommitTaskOption.POSTCOMMIT)), + new Case("each queue", 2, true, THRESHOLD, i -> { + scope().addCommitTask(TestCase.task(i), CommitTaskOption.PRECOMMIT); + postCommit.accept(i); + }), + new Case("only the queue that runs", 0, false, THRESHOLD, postCommit))) + assertEquals(c.name(), c.expectedWarnings(), warningsFor(c.commit(), c.count(), c.register())); } @Test diff --git a/api/src/org/labkey/api/data/RequestCancellation.java b/api/src/org/labkey/api/data/RequestCancellation.java index 39ac4824b0d..bef760caa61 100644 --- a/api/src/org/labkey/api/data/RequestCancellation.java +++ b/api/src/org/labkey/api/data/RequestCancellation.java @@ -17,8 +17,6 @@ import io.opentracing.Span; import io.opentracing.util.GlobalTracer; -import jakarta.servlet.ServletException; -import jakarta.servlet.http.HttpServletRequest; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.Logger; import org.jetbrains.annotations.NotNull; @@ -26,16 +24,11 @@ import org.junit.Assert; import org.junit.Test; import org.labkey.api.data.dialect.SqlDialect; -import org.labkey.api.security.User; import org.labkey.api.settings.OptionalFeatureService; import org.labkey.api.usageMetrics.CoreMetricArea; import org.labkey.api.usageMetrics.SimpleMetricsService; -import org.labkey.api.util.TestContext; import org.labkey.api.util.logging.LogHelper; -import org.springframework.mock.web.MockHttpServletRequest; -import org.springframework.mock.web.MockHttpServletResponse; -import java.io.IOException; import java.security.Principal; import java.util.Collection; import java.util.HashMap; @@ -367,78 +360,10 @@ private static void increment(String metricName) public static class TestCase extends Assert { - /** Runs body on a new thread that carries this test's TestContext, rethrowing whatever it throws */ - public static void runOnRequestThread(Runnable body) throws Exception - { - HttpServletRequest testRequest = TestContext.get().getRequest(); - User user = TestContext.get().getUser(); - AtomicReference failure = new AtomicReference<>(); - Thread thread = new Thread(() -> { - try - { - TestContext.setTestContext(testRequest, user); - body.run(); - } - catch (Throwable t) - { - failure.set(t); - } - }, "RequestCancellation test request"); - - thread.start(); - thread.join(60_000); - assertFalse("Request thread didn't exit", thread.isAlive()); - - switch (failure.get()) - { - case null -> {} - case Error e -> throw e; - case Exception e -> throw e; - default -> throw new RuntimeException(failure.get()); - } - } - - /** Runs body inside a TransactionFilter request on the current thread, cancelled first if cancelledBy is set */ - public static void doRequest(@NotNull MockHttpServletRequest request, @Nullable Source cancelledBy, @NotNull Runnable body) - { - try - { - new TransactionFilter().doFilter(request, new MockHttpServletResponse(), (_, _) -> { - if (cancelledBy != null) - { - Thread thread = Thread.currentThread(); - assertTrue(requestCancelled(thread, TransactionFilter.getRequestSummary(thread), cancelledBy)); - } - body.run(); - }); - } - catch (IOException | ServletException e) - { - throw new RuntimeException(e); - } - } - - public static void doRequest(@Nullable Source cancelledBy, @NotNull Runnable body) - { - doRequest(new MockHttpServletRequest("GET", "/test"), cancelledBy, body); - } - - /** Polls briefly, since a discarded session's backend exits only after the pool closes its connection */ - static long countLiveBackends(DbScope scope, Set spids) throws InterruptedException - { - SQLFragment live = SQLFragment.unsafe("SELECT COUNT(*) FROM pg_stat_activity WHERE pid ").appendInClause(spids, scope.getSqlDialect()); - long start = System.currentTimeMillis(); - long count; - while ((count = new SqlSelector(scope, live).getObject(Long.class)) > 0 && System.currentTimeMillis() - start < 5_000) - //noinspection BusyWait - Thread.sleep(100); - return count; - } - @Test public void testCancelledOnce() throws Exception { - runOnRequestThread(() -> doRequest(null, () -> { + RequestTestUtil.runOnRequestThread(() -> RequestTestUtil.doRequest(null, () -> { Thread thread = Thread.currentThread(); TransactionFilter.RequestTracker tracker = TransactionFilter.getRequestSummary(thread); assertNull(getSource(thread)); @@ -454,7 +379,7 @@ public void testCancelledOnce() throws Exception @Test public void testStatementRecorded() throws Exception { - runOnRequestThread(() -> doRequest(Source.TIMEOUT, () -> { + RequestTestUtil.runOnRequestThread(() -> RequestTestUtil.doRequest(Source.TIMEOUT, () -> { Cancelled cancelled = getCancelled(Thread.currentThread()); assertNotNull(cancelled); @@ -468,7 +393,7 @@ public void testStatementRecorded() throws Exception @Test public void testStuckReportedAfterGracePeriod() throws Exception { - runOnRequestThread(() -> doRequest(null, () -> { + RequestTestUtil.runOnRequestThread(() -> RequestTestUtil.doRequest(null, () -> { Thread thread = Thread.currentThread(); TransactionFilter.RequestTracker tracker = TransactionFilter.getRequestSummary(thread); @@ -488,13 +413,13 @@ public void testStuckReportedAfterGracePeriod() throws Exception @Test public void testFinishedRequest() throws Exception { - runOnRequestThread(() -> { + RequestTestUtil.runOnRequestThread(() -> { Thread thread = Thread.currentThread(); AtomicReference finished = new AtomicReference<>(); - doRequest(null, () -> finished.set(TransactionFilter.getRequestSummary(thread))); + RequestTestUtil.doRequest(null, () -> finished.set(TransactionFilter.getRequestSummary(thread))); requestCancelled(thread, finished.get(), Source.TIMEOUT); - doRequest(null, () -> assertNull("Cancel applied to the next request", getSource(thread))); + RequestTestUtil.doRequest(null, () -> assertNull("Cancel applied to the next request", getSource(thread))); }); } @@ -502,9 +427,9 @@ public void testFinishedRequest() throws Exception @Test public void testNestedRequest() throws Exception { - runOnRequestThread(() -> doRequest(Source.TIMEOUT, () -> { + RequestTestUtil.runOnRequestThread(() -> RequestTestUtil.doRequest(Source.TIMEOUT, () -> { Thread thread = Thread.currentThread(); - doRequest(null, () -> {}); + RequestTestUtil.doRequest(null, () -> {}); assertEquals(Source.TIMEOUT, getSource(thread)); })); } @@ -535,16 +460,8 @@ private static BlockedQuery startBlockedQuery() throws InterruptedException long start = System.currentTimeMillis(); queryThread.start(); - Map> connections = Map.of(); - while (connections.isEmpty() && System.currentTimeMillis() - start < 10_000) - { - //noinspection BusyWait - Thread.sleep(100); - connections = ConnectionWrapper.getConnectionsByScopeForEffectiveThread(queryThread); - } + Map> connections = RequestTestUtil.awaitStatementStarted(queryThread); assertFalse("Query thread never got a connection", connections.isEmpty()); - // Let the statement reach the server - Thread.sleep(500); return new BlockedQuery(scope, queryThread, failure, connections.get(scope), start); } diff --git a/api/src/org/labkey/api/data/RequestTestUtil.java b/api/src/org/labkey/api/data/RequestTestUtil.java new file mode 100644 index 00000000000..73f1768ecf2 --- /dev/null +++ b/api/src/org/labkey/api/data/RequestTestUtil.java @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2026 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.labkey.api.data; + +import jakarta.servlet.ServletException; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.junit.Assert; +import org.labkey.api.util.JunitUtil; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; + +import java.io.IOException; +import java.util.Map; +import java.util.Set; + +/** Test helpers for driving in-JVM requests through TransactionFilter and observing their database sessions */ +public class RequestTestUtil +{ + /** Runs body on a new thread that carries this test's TestContext, rethrowing whatever it throws */ + public static void runOnRequestThread(JunitUtil.ThrowingRunnable body) throws Exception + { + JunitUtil.runOnNewThread("Test request", body); + } + + /** Runs body inside a TransactionFilter request on the current thread, cancelled first if cancelledBy is set */ + public static void doRequest(@NotNull MockHttpServletRequest request, @Nullable RequestCancellation.Source cancelledBy, @NotNull Runnable body) + { + try + { + new TransactionFilter().doFilter(request, new MockHttpServletResponse(), (_, _) -> { + if (cancelledBy != null) + { + Thread thread = Thread.currentThread(); + Assert.assertTrue(RequestCancellation.requestCancelled(thread, TransactionFilter.getRequestSummary(thread), cancelledBy)); + } + body.run(); + }); + } + catch (IOException | ServletException e) + { + throw new RuntimeException(e); + } + } + + public static void doRequest(@Nullable RequestCancellation.Source cancelledBy, @NotNull Runnable body) + { + doRequest(new MockHttpServletRequest("GET", "/test"), cancelledBy, body); + } + + /** + * Waits up to 10 seconds for thread to hold a connection, then briefly for its statement to reach the server. + * Returns the thread's connections, which are empty if it never got one. + */ + public static Map> awaitStatementStarted(Thread thread) throws InterruptedException + { + long start = System.currentTimeMillis(); + Map> connections; + while ((connections = ConnectionWrapper.getConnectionsByScopeForEffectiveThread(thread)).isEmpty() && System.currentTimeMillis() - start < 10_000) + //noinspection BusyWait + Thread.sleep(50); + if (!connections.isEmpty()) + Thread.sleep(500); + return ConnectionWrapper.getConnectionsByScopeForEffectiveThread(thread); + } + + /** Polls briefly, since a discarded session's backend exits only after the pool closes its connection */ + public static long countLiveBackends(DbScope scope, Set spids) throws InterruptedException + { + SQLFragment live = SQLFragment.unsafe("SELECT COUNT(*) FROM pg_stat_activity WHERE pid ").appendInClause(spids, scope.getSqlDialect()); + long start = System.currentTimeMillis(); + long count; + while ((count = new SqlSelector(scope, live).getObject(Long.class)) > 0 && System.currentTimeMillis() - start < 5_000) + //noinspection BusyWait + Thread.sleep(100); + return count; + } +} diff --git a/api/src/org/labkey/api/data/SQLFragment.java b/api/src/org/labkey/api/data/SQLFragment.java index c2268691101..29f3f45ecbe 100644 --- a/api/src/org/labkey/api/data/SQLFragment.java +++ b/api/src/org/labkey/api/data/SQLFragment.java @@ -29,6 +29,7 @@ import org.labkey.api.query.AliasManager; import org.labkey.api.query.FieldKey; import org.labkey.api.util.GUID; +import org.labkey.api.util.JunitUtil; import org.labkey.api.util.Pair; import org.labkey.api.util.StringUtilsLabKey; import org.labkey.api.util.logging.LogHelper; @@ -1963,7 +1964,7 @@ public void testInClause() verify(Arrays.asList(2, null), new HashSet<>(Arrays.asList(2, null))); verify(Collections.singletonList(null), Collections.singleton(null)); // Large enough for the temp table generator - verify(IntStream.concat(IntStream.of(2), IntStream.rangeClosed(4, 2000)).boxed().toList(), Set.of(2)); + verify(IntStream.concat(IntStream.of(2), IntStream.range(4, 4 + SqlDialect.TEMP_TABLE_GENERATOR_MIN_SIZE)).boxed().toList(), Set.of(2)); } @Test @@ -1979,20 +1980,13 @@ public void testExpressionParameters() @Test public void testNotBeforeInClause() { - assumeAssertionsEnabled(); + JunitUtil.assumeAssertionsEnabled(); SqlDialect dialect = CoreSchema.getInstance().getSqlDialect(); assertThrows(AssertionError.class, () -> dialect.appendInClauseSql(new SQLFragment("x NOT"), List.of(1, 2))); assertThrows(AssertionError.class, () -> dialect.appendInClauseSql(new SQLFragment("x not "), List.of())); assertThrows(AssertionError.class, () -> new SQLFragment("x NOT").appendInClause(List.of(1), dialect)); } - private static void assumeAssertionsEnabled() - { - boolean enabled = false; - assert enabled = true; - org.junit.Assume.assumeTrue(enabled); - } - private void verify(List values, Set expected) { assertEquals("IN " + values.size(), expected, select(values, false)); diff --git a/api/src/org/labkey/api/data/Table.java b/api/src/org/labkey/api/data/Table.java index 6027633e3a9..89036f3d716 100644 --- a/api/src/org/labkey/api/data/Table.java +++ b/api/src/org/labkey/api/data/Table.java @@ -70,6 +70,7 @@ import java.time.LocalDate; import java.time.LocalDateTime; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; @@ -1917,7 +1918,6 @@ private static SQLException backendTerminated() @Test public void testBackendTerminated() { - assertTrue(SqlDialect.isConnectionLostException(backendTerminated())); assertEquals(Level.ERROR, getExceptionLogLevel(SELECT, backendTerminated(), Level.WARN)); assertEquals(Level.ERROR, getExceptionLogLevel(null, backendTerminated(), Level.WARN)); } @@ -1944,18 +1944,13 @@ public void testSkipped() } @Test - public void testShutdown() + public void testConnectionLost() { - assertTrue(SqlDialect.isConnectionLostException(new SQLException("terminating connection due to administrator command", "57P01"))); - assertTrue(SqlDialect.isConnectionLostException(new SQLException("terminating connection because of crash of another server process", "57P02"))); - } - - @Test - public void testOtherErrors() - { - assertFalse(SqlDialect.isConnectionLostException(new SQLException("canceling statement due to user request", "57014"))); - assertFalse(SqlDialect.isConnectionLostException(new SQLException("relation does not exist", "42P01"))); - assertFalse(SqlDialect.isConnectionLostException(new SQLException("no state"))); + // Backend killed mid-query, then shutdown and crash of another server process + for (String state : List.of("08006", "57P01", "57P02")) + assertTrue(state, SqlDialect.isConnectionLostException(new SQLException("lost", state))); + for (String state : Arrays.asList("57014", "42P01", null)) + assertFalse(state, SqlDialect.isConnectionLostException(new SQLException("other", state))); } } } diff --git a/api/src/org/labkey/api/data/TransactionFilter.java b/api/src/org/labkey/api/data/TransactionFilter.java index 45e5b295e09..2eecbddeffd 100644 --- a/api/src/org/labkey/api/data/TransactionFilter.java +++ b/api/src/org/labkey/api/data/TransactionFilter.java @@ -41,6 +41,7 @@ import org.labkey.api.util.FileUtil; import org.labkey.api.util.GUID; import org.labkey.api.util.HeartBeat; +import org.labkey.api.util.JunitUtil; import org.labkey.api.util.QuietCloser; import org.labkey.api.util.StartupListener; import org.labkey.api.util.TestContext; @@ -448,11 +449,11 @@ public static class TestCase extends Assert @Test public void testIsTimedOut() throws Exception { - RequestCancellation.TestCase.runOnRequestThread(() -> { + RequestTestUtil.runOnRequestThread(() -> { Thread thread = Thread.currentThread(); AtomicReference finished = new AtomicReference<>(); - RequestCancellation.TestCase.doRequest(new MockHttpServletRequest("GET", "/test"), null, () -> { + RequestTestUtil.doRequest(new MockHttpServletRequest("GET", "/test"), null, () -> { RequestTracker tracker = getRequestSummary(thread); finished.set(tracker); assertTrue("Read-only request past the cutoff", isTimedOut(thread, tracker, tracker.startTime() + 1)); @@ -460,17 +461,17 @@ public void testIsTimedOut() throws Exception }); assertFalse("Finished request", isTimedOut(thread, finished.get(), Long.MAX_VALUE)); - RequestCancellation.TestCase.doRequest(new MockHttpServletRequest("GET", "/test"), null, () -> { + RequestTestUtil.doRequest(new MockHttpServletRequest("GET", "/test"), null, () -> { RequestTracker tracker = getRequestSummary(thread); tracker.request().setAttribute(EXPORT_ATTRIBUTE_NAME, true); assertFalse("Export", isTimedOut(thread, tracker, Long.MAX_VALUE)); }); - RequestCancellation.TestCase.doRequest(new MockHttpServletRequest("POST", "/test"), null, () -> + RequestTestUtil.doRequest(new MockHttpServletRequest("POST", "/test"), null, () -> assertFalse("Mutating request", isTimedOut(thread, getRequestSummary(thread), Long.MAX_VALUE))); MockHttpServletRequest recycled = new MockHttpServletRequest("GET", "/test"); - RequestCancellation.TestCase.doRequest(recycled, null, () -> { + RequestTestUtil.doRequest(recycled, null, () -> { // A closed mock request throws on getAttribute(), like a request Tomcat has recycled recycled.close(); assertFalse("Recycled request", isTimedOut(thread, getRequestSummary(thread), Long.MAX_VALUE)); @@ -488,10 +489,10 @@ public void testSweep() throws Exception setReadOnlyTimeout(2); try { - RequestCancellation.TestCase.runOnRequestThread(() -> { + RequestTestUtil.runOnRequestThread(() -> { Thread thread = Thread.currentThread(); - RequestCancellation.TestCase.doRequest(null, () -> { + RequestTestUtil.doRequest(null, () -> { long start = System.currentTimeMillis(); try { @@ -505,7 +506,7 @@ public void testSweep() throws Exception }); assertTrue("Connection wasn't released", ConnectionWrapper.getConnectionsByScopeForThread(thread).isEmpty()); - RequestCancellation.TestCase.doRequest(null, () -> { + RequestTestUtil.doRequest(null, () -> { getRequestSummary(thread).request().setAttribute(EXPORT_ATTRIBUTE_NAME, true); // Long enough for a sweep after the timeout despite HeartBeat's lag new SqlSelector(scope, "SELECT pg_sleep(12)").getObject(Object.class); @@ -530,25 +531,19 @@ public void testCancelFallback() throws Exception RequestCancellation._skipDriverCancel = true; try { - RequestCancellation.TestCase.runOnRequestThread(() -> { + RequestTestUtil.runOnRequestThread(() -> { Thread requestThread = Thread.currentThread(); Thread canceller = new Thread(() -> { try { - long start = System.currentTimeMillis(); - while (ConnectionWrapper.getConnectionsByScopeForEffectiveThread(requestThread).isEmpty() && System.currentTimeMillis() - start < 10_000) - //noinspection BusyWait - Thread.sleep(100); - // Let the statement reach the server - Thread.sleep(500); - ConnectionWrapper.getConnectionsByScopeForEffectiveThread(requestThread).values().forEach(c -> c.forEach(w -> spids.add(w.getSPID()))); + RequestTestUtil.awaitStatementStarted(requestThread).values().forEach(c -> c.forEach(w -> spids.add(w.getSPID()))); cancelRequest(requestThread, getRequestSummary(requestThread), RequestCancellation.Source.TIMEOUT); } catch (InterruptedException ignored) {} }, "TransactionFilter test canceller"); canceller.start(); - RequestCancellation.TestCase.doRequest(null, () -> { + RequestTestUtil.doRequest(null, () -> { long start = System.currentTimeMillis(); try { @@ -569,13 +564,11 @@ public void testCancelFallback() throws Exception } assertNotNull("Query wasn't cancelled", queryFailure.get()); - boolean cancelled = false; - for (Throwable t = queryFailure.get(); t != null && !cancelled; t = ExceptionUtil.getCause(t)) - cancelled = t instanceof SQLException e && SqlDialect.isCancelException(e); - assertTrue("Query failed with something other than a cancel: " + queryFailure.get(), cancelled); + assertTrue("Query failed with something other than a cancel: " + queryFailure.get(), + JunitUtil.hasCause(queryFailure.get(), t -> t instanceof SQLException e && SqlDialect.isCancelException(e))); assertFalse("Request had no connections", spids.isEmpty()); - assertEquals("Cancelled session went back to the pool", 0, RequestCancellation.TestCase.countLiveBackends(scope, spids)); + assertEquals("Cancelled session went back to the pool", 0, RequestTestUtil.countLiveBackends(scope, spids)); } /** Even with no request timeout, the sweep must resend a cancel that reached the request's connection while it was idle */ @@ -588,10 +581,10 @@ public void testSweepResendsLostCancel() throws Exception setReadOnlyTimeout(0); try { - RequestCancellation.TestCase.runOnRequestThread(() -> { + RequestTestUtil.runOnRequestThread(() -> { Thread thread = Thread.currentThread(); - RequestCancellation.TestCase.doRequest(null, () -> { + RequestTestUtil.doRequest(null, () -> { // Holds a connection, so the cancel signals it rather than banning new ones try (TableResultSet rs = new SqlSelector(scope, "SELECT 1").getResultSet(false)) { @@ -633,10 +626,10 @@ public void testCancelRequestsRefused() throws Exception String tabId = GUID.makeGUID(); List ids = List.of("r1"); - RequestCancellation.TestCase.runOnRequestThread(() -> { + RequestTestUtil.runOnRequestThread(() -> { Thread thread = Thread.currentThread(); - RequestCancellation.TestCase.doRequest(cancellableRequest("GET", tabId, "r1"), null, () -> { + RequestTestUtil.doRequest(cancellableRequest("GET", tabId, "r1"), null, () -> { assertEquals(Outcome.WRONG_USER, cancelRequests(userId + 1, SESSION_ID, tabId, ids, RequestCancellation.Source.WS_MESSAGE).get("r1")); assertEquals("Other tab", Outcome.NOT_FOUND, cancelRequests(userId, SESSION_ID, GUID.makeGUID(), ids, RequestCancellation.Source.WS_MESSAGE).get("r1")); assertEquals("Other session", Outcome.NOT_FOUND, cancelRequests(userId, "OtherSession", tabId, ids, RequestCancellation.Source.WS_MESSAGE).get("r1")); @@ -645,7 +638,7 @@ public void testCancelRequestsRefused() throws Exception assertNull("Refused cancel was applied", RequestCancellation.getSource(thread)); }); - RequestCancellation.TestCase.doRequest(cancellableRequest("POST", tabId, "r1"), null, () -> + RequestTestUtil.doRequest(cancellableRequest("POST", tabId, "r1"), null, () -> assertEquals(Outcome.NOT_READ_ONLY, cancelRequests(userId, SESSION_ID, tabId, ids, RequestCancellation.Source.WS_MESSAGE).get("r1"))); }); @@ -674,10 +667,10 @@ public void testCancelDeferred() throws Exception { DbScope scope = DbScope.getLabKeyScope(); - RequestCancellation.TestCase.runOnRequestThread(() -> { + RequestTestUtil.runOnRequestThread(() -> { Thread thread = Thread.currentThread(); - RequestCancellation.TestCase.doRequest(null, () -> { + RequestTestUtil.doRequest(null, () -> { try (TableResultSet rs = new SqlSelector(scope, "SELECT 1").getResultSet(false)) { assertTrue(rs.next()); @@ -710,10 +703,7 @@ public void testCancelDeferred() throws Exception } catch (RuntimeException e) { - boolean aborted = false; - for (Throwable t = e; t != null && !aborted; t = ExceptionUtil.getCause(t)) - aborted = t instanceof AbortedRequestException; - assertTrue("Query failed with something other than the ban: " + e, aborted); + assertTrue("Query failed with something other than the ban: " + e, JunitUtil.hasCause(e, t -> t instanceof AbortedRequestException)); } }); assertTrue("Connection wasn't released", ConnectionWrapper.getConnectionsByScopeForThread(thread).isEmpty()); @@ -736,23 +726,18 @@ private static void assertCancelledWhileQuerying(MockHttpServletRequest request, DbScope scope = DbScope.getLabKeyScope(); AtomicReference> outcomes = new AtomicReference<>(); - RequestCancellation.TestCase.runOnRequestThread(() -> { + RequestTestUtil.runOnRequestThread(() -> { Thread thread = Thread.currentThread(); Thread canceller = new Thread(() -> { try { - long start = System.currentTimeMillis(); - while (ConnectionWrapper.getConnectionsByScopeForEffectiveThread(thread).isEmpty() && System.currentTimeMillis() - start < 10_000) - //noinspection BusyWait - Thread.sleep(100); - // Let the statement reach the server - Thread.sleep(500); + RequestTestUtil.awaitStatementStarted(thread); outcomes.set(cancel.get()); } catch (InterruptedException ignored) {} }, "TransactionFilter test canceller"); - RequestCancellation.TestCase.doRequest(request, null, () -> { + RequestTestUtil.doRequest(request, null, () -> { canceller.start(); long start = System.currentTimeMillis(); try diff --git a/api/src/org/labkey/api/data/dialect/PostgresSnapshot.java b/api/src/org/labkey/api/data/dialect/PostgresSnapshot.java index 3202db467fe..6175e3a8be4 100644 --- a/api/src/org/labkey/api/data/dialect/PostgresSnapshot.java +++ b/api/src/org/labkey/api/data/dialect/PostgresSnapshot.java @@ -20,11 +20,11 @@ import org.jetbrains.annotations.Nullable; import org.json.JSONObject; import org.junit.Assert; -import org.junit.Assume; import org.junit.Test; import org.labkey.api.data.CoreSchema; import org.labkey.api.data.DbSchema; import org.labkey.api.data.SqlSelector; +import org.labkey.api.util.JunitUtil; import org.springframework.dao.DataAccessException; import java.util.Set; @@ -156,7 +156,7 @@ public static class TestCase extends Assert @Test public void testCapture() { - Assume.assumeTrue("Requires Postgres", CoreSchema.getInstance().getSqlDialect().isPostgreSQL()); + JunitUtil.assumePostgres(); // JSONObject rejects duplicate keys, so parsing also verifies statement keys are unique JSONObject snapshot = new JSONObject(capture()); diff --git a/api/src/org/labkey/api/data/queryprofiler/Query.java b/api/src/org/labkey/api/data/queryprofiler/Query.java index 058a87940fb..2b818867ea9 100644 --- a/api/src/org/labkey/api/data/queryprofiler/Query.java +++ b/api/src/org/labkey/api/data/queryprofiler/Query.java @@ -295,9 +295,14 @@ public static class TestCase extends Assert { private static final String HASH = "0123456789abcdef0123456789abcdef"; + static Query query(String sql, long elapsed) + { + return new Query(null, sql, null, elapsed, null, false); + } + private static String transform(String sql) { - return new Query(null, sql, null, 0, null, false).getSql(); + return query(sql, 0).getSql(); } @Test @@ -330,7 +335,7 @@ public void testOtherHexUnchanged() "SELECT 1.123456789012345678901234567890123456e10", "SELECT x FROM study.c108d1468_demographics")) { - Query query = new Query(null, sql, null, 0, null, false); + Query query = query(sql, 0); assertEquals(sql, query.getSql()); assertTrue(query.isValidSql()); assertNull(query.getNormalizationReason()); @@ -346,7 +351,7 @@ public void testNormalizationReason() private static void assertNormalizedName(String expectedName, String sql) { - Query query = new Query(null, sql, null, 0, null, false); + Query query = query(sql, 0); query.getSql(); assertFalse(query.isValidSql()); String reason = query.getNormalizationReason(); diff --git a/api/src/org/labkey/api/data/queryprofiler/QueryProfiler.java b/api/src/org/labkey/api/data/queryprofiler/QueryProfiler.java index e14d37f0c62..667c326c130 100644 --- a/api/src/org/labkey/api/data/queryprofiler/QueryProfiler.java +++ b/api/src/org/labkey/api/data/queryprofiler/QueryProfiler.java @@ -745,24 +745,19 @@ public interface ActionURLFactory public static class TestCase extends Assert { - private static Query query(String sql, long elapsed) - { - return new Query(null, sql, null, elapsed, null, false); - } - @Test public void testSlowestStatementTagsSpan() { Map tags = new HashMap<>(); MutableSpan span = TagRecordingSpan.create(tags); - Query slow = query("SELECT * FROM core.containers", 2000); + Query slow = Query.TestCase.query("SELECT * FROM core.containers", 2000); tagActiveSpan(span, slow); - tagActiveSpan(span, query("SELECT 1", 1500)); - tagActiveSpan(span, query("SELECT 2", 2000)); + tagActiveSpan(span, Query.TestCase.query("SELECT 1", 1500)); + tagActiveSpan(span, Query.TestCase.query("SELECT 2", 2000)); assertEquals(Map.of(SLOW_SQL_HASH_TAG, HashHelpers.hash(slow.getSql()), SLOW_SQL_MS_TAG, 2000L), tags); - Query slower = query("SELECT 3", 2500); + Query slower = Query.TestCase.query("SELECT 3", 2500); tagActiveSpan(span, slower); assertEquals(Map.of(SLOW_SQL_HASH_TAG, HashHelpers.hash(slower.getSql()), SLOW_SQL_MS_TAG, 2500L), tags); } @@ -772,8 +767,8 @@ public void testHashIgnoresGeneratedNames() { Map first = new HashMap<>(); Map second = new HashMap<>(); - tagActiveSpan(TagRecordingSpan.create(first), query("SELECT * FROM temp.tt_lsids$0123456789abcdef0123456789abcdef", 2000)); - tagActiveSpan(TagRecordingSpan.create(second), query("SELECT * FROM temp.tt_lsids$fedcba9876543210fedcba9876543210", 2000)); + tagActiveSpan(TagRecordingSpan.create(first), Query.TestCase.query("SELECT * FROM temp.tt_lsids$0123456789abcdef0123456789abcdef", 2000)); + tagActiveSpan(TagRecordingSpan.create(second), Query.TestCase.query("SELECT * FROM temp.tt_lsids$fedcba9876543210fedcba9876543210", 2000)); assertEquals(first.get(SLOW_SQL_HASH_TAG), second.get(SLOW_SQL_HASH_TAG)); } } diff --git a/api/src/org/labkey/api/dataiterator/QueryDataIteratorBuilder.java b/api/src/org/labkey/api/dataiterator/QueryDataIteratorBuilder.java index 08c786473b2..33e34f7aded 100644 --- a/api/src/org/labkey/api/dataiterator/QueryDataIteratorBuilder.java +++ b/api/src/org/labkey/api/dataiterator/QueryDataIteratorBuilder.java @@ -203,27 +203,17 @@ public void existingQuery() throws IOException } @Test - public void bogusQueryName() + public void missingQueryName() { - DataIteratorContext context = new DataIteratorContext(); - assertNull(run("NoSuchQuery", context)); - assertTrue(context.getErrors().hasErrors()); - String message = context.getErrors().getRowErrors().getFirst().getMessage(); - assertTrue(message, message.contains("NoSuchQuery")); - } - - @Test - public void quoteCharactersInQueryName() - { - // the name is quoted as LabKey SQL, so characters other dialects quote with are just part of the name - for (String name : List.of("No`Such`Query", "No\"Such\"Query", "No[Such]Query")) - { + // name -> expected message fragment; the name is quoted as LabKey SQL, so characters other dialects quote with are just part of the name + Map cases = Map.of("NoSuchQuery", "NoSuchQuery", "No`Such`Query", "not found", "No\"Such\"Query", "not found", "No[Such]Query", "not found"); + cases.forEach((name, expected) -> { DataIteratorContext context = new DataIteratorContext(); - assertNull(run(name, context)); - assertTrue(context.getErrors().hasErrors()); + assertNull(name, run(name, context)); + assertTrue(name, context.getErrors().hasErrors()); String message = context.getErrors().getRowErrors().getFirst().getMessage(); - assertTrue(message, message.contains("not found")); - } + assertTrue(message, message.contains(expected)); + }); } } } diff --git a/api/src/org/labkey/api/dataiterator/SimpleTranslator.java b/api/src/org/labkey/api/dataiterator/SimpleTranslator.java index a279be215c3..3f290226ac1 100644 --- a/api/src/org/labkey/api/dataiterator/SimpleTranslator.java +++ b/api/src/org/labkey/api/dataiterator/SimpleTranslator.java @@ -2272,8 +2272,7 @@ public void convertTest() throws Exception public void convertRemapTest() throws Exception { // fake-o lookup table - var core = QueryService.get().getUserSchema(TestContext.get().getUser(), JunitUtil.getTestContainer(), "core"); - var lookupTable = new EnumTableInfo<>(LookupValues.class, core, "fake enum", true); + var lookupTable = remapLookupTable(); var fk = new AbstractForeignKey(null, null) { @Override diff --git a/api/src/org/labkey/api/exp/OntologyManager.java b/api/src/org/labkey/api/exp/OntologyManager.java index 33b9f5d533a..f33cf51ed26 100644 --- a/api/src/org/labkey/api/exp/OntologyManager.java +++ b/api/src/org/labkey/api/exp/OntologyManager.java @@ -3214,6 +3214,13 @@ public static void updateDomainPropertyFromDescriptor(DomainProperty p, Property @TestTimeout(120) public static class TestCase extends Assert { + private static void deletePropertyDescriptorIfExists(String propertyURI, Container c) + { + PropertyDescriptor pd = getPropertyDescriptor(propertyURI, c); + if (pd != null) + deletePropertyDescriptor(pd); + } + @Test public void testSchema() { @@ -3414,9 +3421,7 @@ public void testDeleteByUriSqlClearsObjectCaches() throws Exception finally { deleteOntologyObjects(c, parentObjectLsid); - PropertyDescriptor pd = getPropertyDescriptor(intProp, c); - if (pd != null) - deletePropertyDescriptor(pd); + deletePropertyDescriptorIfExists(intProp, c); } } @@ -3469,9 +3474,7 @@ public void testDeleteByObjectIdSqlAcrossContainers() throws Exception { deleteOntologyObjects(c1, lsid1); ContainerManager.delete(c2, user); - PropertyDescriptor pd = getPropertyDescriptor(intProp, c1); - if (pd != null) - deletePropertyDescriptor(pd); + deletePropertyDescriptorIfExists(intProp, c1); } } @@ -3519,9 +3522,7 @@ public void testDeleteByObjectIdSqlOverLimitClearsContainer() throws Exception { deleteOntologyObjectsByObjectIdSql(getExpSchema(), bulkIdSql); ContainerManager.delete(c2, user); - PropertyDescriptor pd = getPropertyDescriptor(intProp, c1); - if (pd != null) - deletePropertyDescriptor(pd); + deletePropertyDescriptorIfExists(intProp, c1); } } @@ -3577,9 +3578,7 @@ public void testDeleteByObjectIdSqlOverLimitAcrossContainers() throws Exception deleteOntologyObjectsByObjectIdSql(getExpSchema(), bulkIdSql); ContainerManager.delete(c2, user); ContainerManager.delete(c3, user); - PropertyDescriptor pd = getPropertyDescriptor(intProp, c1); - if (pd != null) - deletePropertyDescriptor(pd); + deletePropertyDescriptorIfExists(intProp, c1); } } diff --git a/api/src/org/labkey/api/exp/api/SampleTypeTestHelper.java b/api/src/org/labkey/api/exp/api/SampleTypeTestHelper.java new file mode 100644 index 00000000000..ec1f753bf4e --- /dev/null +++ b/api/src/org/labkey/api/exp/api/SampleTypeTestHelper.java @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2026 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.labkey.api.exp.api; + +import org.jetbrains.annotations.NotNull; +import org.labkey.api.data.Container; +import org.labkey.api.data.TableInfo; +import org.labkey.api.exp.ExperimentException; +import org.labkey.api.exp.query.SamplesSchema; +import org.labkey.api.gwt.client.model.GWTPropertyDescriptor; +import org.labkey.api.query.QueryUpdateServiceTestUtil; +import org.labkey.api.security.User; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +/** Test helpers for creating a sample type and writing to its samples.* table */ +public class SampleTypeTestHelper +{ + public static GWTPropertyDescriptor nameProperty() + { + return new GWTPropertyDescriptor("Name", "string"); + } + + /** Creates a sample type with a Name property followed by extraProperties */ + public static @NotNull ExpSampleType create(Container c, User user, String name, GWTPropertyDescriptor... extraProperties) throws ExperimentException + { + List props = new ArrayList<>(); + props.add(nameProperty()); + props.addAll(Arrays.asList(extraProperties)); + return create(c, user, name, props); + } + + /** Creates a sample type with exactly these properties; include {@link #nameProperty()} unless naming by expression */ + public static @NotNull ExpSampleType create(Container c, User user, String name, List properties) throws ExperimentException + { + return SampleTypeService.get().createSampleType(c, user, name, null, properties, Collections.emptyList(), -1, -1, -1, -1, null); + } + + public static @NotNull TableInfo getTable(Container c, User user, ExpSampleType st) + { + return QueryUpdateServiceTestUtil.getTable(user, c, SamplesSchema.SCHEMA_SAMPLES, st.getName()); + } + + public static List> insert(Container c, User user, ExpSampleType st, List> rows) throws Exception + { + return QueryUpdateServiceTestUtil.insert(getTable(c, user, st), user, c, rows); + } + + public static List> update(Container c, User user, ExpSampleType st, List> rows) throws Exception + { + return QueryUpdateServiceTestUtil.update(getTable(c, user, st), user, c, rows); + } +} diff --git a/api/src/org/labkey/api/exp/property/DomainUtil.java b/api/src/org/labkey/api/exp/property/DomainUtil.java index 8c78ff49b60..7d8f1e00346 100644 --- a/api/src/org/labkey/api/exp/property/DomainUtil.java +++ b/api/src/org/labkey/api/exp/property/DomainUtil.java @@ -2136,61 +2136,36 @@ private static GWTPropertyDescriptor lookup(int propertyId, @Nullable String sch return pd; } - private static GWTDomain domain(GWTPropertyDescriptor field) - { - GWTDomain domain = new GWTDomain<>(); - domain.setFields(List.of(field)); - return domain; - } - private static List validate(GWTPropertyDescriptor field, @Nullable GWTPropertyDescriptor origField, DbScope domainScope) { ValidationException errors = new ValidationException(); - validateLookupScopes(domain(field), null == origField ? null : domain(origField), domainScope, JunitUtil.getTestContainer(), TestContext.get().getUser(), errors); + validateLookupScopes(SystemFieldLabelTestCase.domain(field), null == origField ? null : SystemFieldLabelTestCase.domain(origField), domainScope, JunitUtil.getTestContainer(), TestContext.get().getUser(), errors); return errors.getFieldErrors(FIELD_NAME); } - @Test - public void sameDataSourceIsAllowed() - { - assertEquals(List.of(), validate(lookup(0, "core", "Users"), null, DbScope.getLabKeyScope())); - } - - @Test - public void newLookupToOtherDataSourceIsRejected() - { - assertEquals(List.of("Field '" + FIELD_NAME + "' can't look up 'core.Users' because it is in a different data source."), - validate(lookup(0, "core", "Users"), null, OTHER_SCOPE)); - } - - @Test - public void unchangedLookupToOtherDataSourceIsAllowed() - { - // Case-only differences don't count as a change - assertEquals(List.of(), validate(lookup(PROPERTY_ID, "core", "Users"), lookup(PROPERTY_ID, "Core", "users"), OTHER_SCOPE)); - } + private record Case(String description, GWTPropertyDescriptor field, @Nullable GWTPropertyDescriptor origField, DbScope scope, int expectedErrors) {} @Test - public void changedLookupToOtherDataSourceIsRejected() - { - assertEquals(1, validate(lookup(PROPERTY_ID, "core", "Users"), lookup(PROPERTY_ID, "core", "Containers"), OTHER_SCOPE).size()); - assertEquals(1, validate(lookup(PROPERTY_ID, "core", "Users"), lookup(PROPERTY_ID, null, null), OTHER_SCOPE).size()); - } + public void testLookupScopes() + { + GWTPropertyDescriptor newUsers = lookup(0, "core", "Users"); + GWTPropertyDescriptor storedUsers = lookup(PROPERTY_ID, "core", "Users"); + for (Case c : List.of( + new Case("same data source", newUsers, null, DbScope.getLabKeyScope(), 0), + // Case-only differences don't count as a change + new Case("unchanged lookup", storedUsers, lookup(PROPERTY_ID, "Core", "users"), OTHER_SCOPE, 0), + new Case("changed lookup", storedUsers, lookup(PROPERTY_ID, "core", "Containers"), OTHER_SCOPE, 1), + new Case("lookup added", storedUsers, lookup(PROPERTY_ID, null, null), OTHER_SCOPE, 1), + // New fields arrive with propertyId 0, so they never match an original field and are always validated + new Case("new field", newUsers, storedUsers, OTHER_SCOPE, 1), + new Case("no query", lookup(0, "core", null), null, OTHER_SCOPE, 0), + // Some UIs (e.g. SND's package editor) send "" for fields without a lookup + new Case("empty lookup", lookup(0, "", ""), null, OTHER_SCOPE, 0), + new Case("unresolvable schema", lookup(0, "noSuchSchema", "Users"), null, OTHER_SCOPE, 0))) + assertEquals(c.description(), c.expectedErrors(), validate(c.field(), c.origField(), c.scope()).size()); - @Test - public void newFieldIsNotMatchedToAnExistingField() - { - // New fields arrive with propertyId 0, so they never match an original field and are always validated - assertEquals(1, validate(lookup(0, "core", "Users"), lookup(PROPERTY_ID, "core", "Users"), OTHER_SCOPE).size()); - } - - @Test - public void incompleteOrUnresolvableLookupIsSkipped() - { - assertEquals(List.of(), validate(lookup(0, "core", null), null, OTHER_SCOPE)); - // Some UIs (e.g. SND's package editor) send "" for fields without a lookup - assertEquals(List.of(), validate(lookup(0, "", ""), null, OTHER_SCOPE)); - assertEquals(List.of(), validate(lookup(0, "noSuchSchema", "Users"), null, OTHER_SCOPE)); + assertEquals(List.of("Field '" + FIELD_NAME + "' can't look up 'core.Users' because it is in a different data source."), + validate(newUsers, null, OTHER_SCOPE)); } } } diff --git a/api/src/org/labkey/api/mcp/AbstractAgentAction.java b/api/src/org/labkey/api/mcp/AbstractAgentAction.java index 726fe97e4df..f3615073f0a 100644 --- a/api/src/org/labkey/api/mcp/AbstractAgentAction.java +++ b/api/src/org/labkey/api/mcp/AbstractAgentAction.java @@ -469,13 +469,6 @@ private static String expressionPayload(String sql, String jdbcType) return json.toString(); } - private static void assertExpressionSegment(JSONArray segments, int i, String sql, String jdbcType) - { - assertEquals("expression", segment(segments, i).getString("type")); - assertEquals(sql, segment(segments, i).getString("sql")); - assertEquals(jdbcType, segment(segments, i).getString("jdbcType")); - } - /** The validator payload is transport between the tool and this action; it must never reach the user as text. */ private static void assertNoPayloadInProse(JSONArray segments) { @@ -513,113 +506,6 @@ public void testToHistorySnippet() assertSnippet(ChatHistoryService.Role.error, DEFAULT_ERROR_MESSAGE, Map.of("success", false, "text", "Boom")); } - @Test - public void emptyResponseList() - { - JSONArray segments = buildSegments(List.of(), LOG); - assertEquals(0, segments.length()); - } - - @Test - public void blankMessageProducesNoSegments() - { - JSONArray segments = buildSegments(List.of(markdownResponse(""), markdownResponse(" ")), LOG); - assertEquals(0, segments.length()); - } - - @Test - public void proseOnlyProducesSingleHtmlSegment() - { - JSONArray segments = buildSegments(List.of(markdownResponse("Hello, here is some advice.")), LOG); - assertEquals(1, segments.length()); - assertEquals("html", segment(segments, 0).getString("type")); - assertTrue(segment(segments, 0).getString("html").contains("Hello, here is some advice.")); - } - - @Test - public void expressionFenceProducesExpressionSegment() - { - String md = "```expression\n" + expressionPayload("SELECT 1", "INTEGER") + "\n```"; - JSONArray segments = buildSegments(List.of(markdownResponse(md)), LOG); - assertEquals(1, segments.length()); - assertEquals("expression", segment(segments, 0).getString("type")); - assertEquals("SELECT 1", segment(segments, 0).getString("sql")); - assertEquals("INTEGER", segment(segments, 0).getString("jdbcType")); - } - - @Test - public void expressionFenceWithRawSqlBodyFallsBackToSqlOnly() - { - // Legacy / model-misbehavior fallback: if the body isn't JSON, treat it as raw SQL and omit jdbcType. - String md = "```expression\nSELECT 1\n```"; - JSONArray segments = buildSegments(List.of(markdownResponse(md)), LOG); - assertEquals(1, segments.length()); - assertEquals("expression", segment(segments, 0).getString("type")); - assertEquals("SELECT 1", segment(segments, 0).getString("sql")); - assertFalse("jdbcType should be absent when body isn't JSON", - segment(segments, 0).has("jdbcType")); - } - - @Test - public void sqlFenceProducesSqlSegment() - { - String md = "```sql\nSELECT 1\n```"; - JSONArray segments = buildSegments(List.of(markdownResponse(md)), LOG); - assertEquals(1, segments.length()); - assertEquals("sql", segment(segments, 0).getString("type")); - assertEquals("SELECT 1", segment(segments, 0).getString("sql")); - } - - @Test - public void interleavedProseAndFencesProduceOrderedSegments() - { - String md = String.join("\n", - "Here are two options.", - "", - "Option A (illustrative):", - "```sql", - "SELECT a FROM t", - "```", - "", - "Option B (ready to apply):", - "```expression", - expressionPayload("SELECT b FROM t", "VARCHAR"), - "```", - "Pick whichever fits." - ); - JSONArray segments = buildSegments(List.of(markdownResponse(md)), LOG); - assertEquals(5, segments.length()); - assertEquals("html", segment(segments, 0).getString("type")); - assertEquals("sql", segment(segments, 1).getString("type")); - assertEquals("SELECT a FROM t", segment(segments, 1).getString("sql")); - assertEquals("html", segment(segments, 2).getString("type")); - assertEquals("expression", segment(segments, 3).getString("type")); - assertEquals("SELECT b FROM t", segment(segments, 3).getString("sql")); - assertEquals("VARCHAR", segment(segments, 3).getString("jdbcType")); - assertEquals("html", segment(segments, 4).getString("type")); - } - - @Test - public void multipleExpressionFencesEachBecomeOwnSegment() - { - String md = String.join("\n", - "```expression", - expressionPayload("SELECT 1", "INTEGER"), - "```", - "```expression", - expressionPayload("SELECT 2", "BIGINT"), - "```" - ); - JSONArray segments = buildSegments(List.of(markdownResponse(md)), LOG); - assertEquals(2, segments.length()); - assertEquals("expression", segment(segments, 0).getString("type")); - assertEquals("SELECT 1", segment(segments, 0).getString("sql")); - assertEquals("INTEGER", segment(segments, 0).getString("jdbcType")); - assertEquals("expression", segment(segments, 1).getString("type")); - assertEquals("SELECT 2", segment(segments, 1).getString("sql")); - assertEquals("BIGINT", segment(segments, 1).getString("jdbcType")); - } - @Test public void unterminatedFenceFallsBackToHtml() { @@ -634,182 +520,110 @@ public void unterminatedFenceFallsBackToHtml() assertFalse("opening fence must be stripped: " + html, html.contains("```")); } - @Test - public void unterminatedFenceDoesNotDiscardLaterResponses() - { - // An unterminated fence must cost only its own block — the four-backtick opener below is never - // closed (its closer is shorter), and the well-formed block after it still has to parse. - var r1 = markdownResponse("````expression\n" + expressionPayload("SELECT 1", "INTEGER") + "\n```"); - var r2 = markdownResponse("Corrected:\n```expression\n" + expressionPayload("SELECT 2", "BIGINT") + "\n```"); - JSONArray segments = buildSegments(List.of(r1, r2), LOG); - assertEquals(2, segments.length()); - assertEquals("html", segment(segments, 0).getString("type")); - assertExpressionSegment(segments, 1, "SELECT 2", "BIGINT"); - } + /** + * One parse case. Each expected entry is a segment type, optionally with content: "html~text" (html contains + * text), "sql=SQL", "expression=SQL|JDBCTYPE", "expression=SQL|" (no jdbcType), "expression=SQL" (jdbcType + * unchecked). leak, when non-null, is the expected hasLeakedPayload(). + */ + private record Case(String name, List responses, Boolean leak, boolean noPayloadInProse, String... expected) {} - @Test - public void unknownFenceLanguageIsTreatedAsProse() + private static String fence(String tag, String body, String closer) { - String md = "```python\nprint('hi')\n```"; - JSONArray segments = buildSegments(List.of(markdownResponse(md)), LOG); - // Only sql/expression are split out; other fenced blocks stay in the html segment. - assertEquals(1, segments.length()); - assertEquals("html", segment(segments, 0).getString("type")); - } - - @Test - public void fenceTagIsCaseInsensitive() - { - String md = "```EXPRESSION\n" + expressionPayload("SELECT 1", "INTEGER") + "\n```"; - JSONArray segments = buildSegments(List.of(markdownResponse(md)), LOG); - assertEquals(1, segments.length()); - assertEquals("expression", segment(segments, 0).getString("type")); - assertEquals("SELECT 1", segment(segments, 0).getString("sql")); - assertEquals("INTEGER", segment(segments, 0).getString("jdbcType")); + return tag + "\n" + body + "\n" + closer; } @Test - public void expressionFenceIsRecognizedAtAnyBacktickLength() + public void testBuildSegments() { + String payload = expressionPayload("Int7 + Int6", "INTEGER"); + String narrated = "Here is the payload: " + payload; + String noExpressionKey = "{\"jdbcType\":\"INTEGER\",\"sql\":\"Int7 + Int6\"}"; + String multiline = "SELECT a,\n b\nFROM t"; + List cases = new ArrayList<>(List.of( + new Case("empty response list", List.of(), null, false), + new Case("blank messages", List.of("", " "), null, false), + new Case("prose only", List.of("Hello, here is some advice."), null, false, "html~Hello, here is some advice."), + new Case("expression fence", List.of(fence("```expression", expressionPayload("SELECT 1", "INTEGER"), "```")), null, false, "expression=SELECT 1|INTEGER"), + // Legacy / model-misbehavior fallback: a non-JSON body is raw SQL with no jdbcType + new Case("raw sql expression body", List.of(fence("```expression", "SELECT 1", "```")), null, false, "expression=SELECT 1|"), + new Case("sql fence", List.of(fence("```sql", "SELECT 1", "```")), null, false, "sql=SELECT 1"), + new Case("interleaved prose and fences", List.of(String.join("\n", + "Here are two options.", "", "Option A (illustrative):", "```sql", "SELECT a FROM t", "```", "", + "Option B (ready to apply):", "```expression", expressionPayload("SELECT b FROM t", "VARCHAR"), "```", "Pick whichever fits.")), + null, false, "html", "sql=SELECT a FROM t", "html", "expression=SELECT b FROM t|VARCHAR", "html"), + new Case("multiple expression fences", List.of(fence("```expression", expressionPayload("SELECT 1", "INTEGER"), "```") + "\n" + fence("```expression", expressionPayload("SELECT 2", "BIGINT"), "```")), + null, false, "expression=SELECT 1|INTEGER", "expression=SELECT 2|BIGINT"), + // An unterminated fence costs only its own block: the four-backtick opener is never closed by the shorter closer + new Case("unterminated fence keeps later responses", List.of(fence("````expression", expressionPayload("SELECT 1", "INTEGER"), "```"), "Corrected:\n" + fence("```expression", expressionPayload("SELECT 2", "BIGINT"), "```")), + null, false, "html", "expression=SELECT 2|BIGINT"), + // Only sql/expression are split out; other fenced blocks stay in the html segment + new Case("unknown fence language", List.of(fence("```python", "print('hi')", "```")), null, false, "html"), + new Case("case-insensitive tag", List.of(fence("```EXPRESSION", expressionPayload("SELECT 1", "INTEGER"), "```")), null, false, "expression=SELECT 1|INTEGER"), + new Case("longer closer ends shorter opener", List.of(fence("```expression", payload, "````")), null, false, "expression=Int7 + Int6|INTEGER"), + // Per CommonMark the short line is fence content, not a closer, so the block never terminates + new Case("shorter closer doesn't end longer opener", List.of(fence("````expression", payload, "```")), null, false, "html"), + // No opening fence, so the payload lands in prose and the user gets no Apply affordance + new Case("leak: missing fence", List.of("Adding Int7 and Int6.\n\n" + payload + "\n```"), true, false, "html"), + // The illustrative sql tag renders the payload as a read-only code block + new Case("leak: sql fence", List.of(fence("```sql", payload, "```")), true, false, "sql"), + // Narration inside the fence means the body doesn't parse and Apply would write JSON to the field + new Case("leak: non-JSON expression body", List.of(fence("```expression", narrated, "```")), true, false, "expression=" + narrated), + // Parses, but with nothing to unpack buildSqlSegment falls back to the raw body + new Case("leak: no expression key", List.of(fence("```expression", noExpressionKey, "```")), true, false, "expression=" + noExpressionKey), + // "jdbcType" is a key on the expression segment itself, not part of the SQL the user sees + new Case("well-formed expression", List.of(fence("```expression", payload, "```")), false, false, "expression=Int7 + Int6|INTEGER"), + new Case("prose without payload", List.of("Which date field should be used?"), false, false, "html"), + // Only the info string's first word is the tag + new Case("extra info string token", List.of(fence("```expression json", payload, "```")), null, true, "expression=Int7 + Int6|INTEGER"), + // Tool calling can split one assistant turn mid-fence; the scan joins the turns so the block still closes + new Case("fence split across responses", List.of("Adding Int7 and Int6.\n\n```expression\n" + payload, "```"), null, true, "html", "expression=Int7 + Int6|INTEGER"), + new Case("multiline sql body", List.of(fence("```expression", expressionPayload(multiline, "VARCHAR"), "```")), null, false, "expression=" + multiline + "|VARCHAR"), + new Case("responses concatenated in order", List.of("First response prose.", fence("```expression", expressionPayload("SELECT 1", "INTEGER"), "```")), + null, false, "html", "expression=SELECT 1|INTEGER") + )); for (int n = 3; n <= 6; n++) { String delim = "`".repeat(n); - String md = delim + "expression\n" + expressionPayload("Int7 + Int6", "INTEGER") + "\n" + delim; - JSONArray segments = buildSegments(List.of(markdownResponse(md)), LOG); - assertEquals("fence length " + n, 1, segments.length()); - assertExpressionSegment(segments, 0, "Int7 + Int6", "INTEGER"); - assertNoPayloadInProse(segments); + cases.add(new Case("fence length " + n, List.of(fence(delim + "expression", payload, delim)), null, true, "expression=Int7 + Int6|INTEGER")); } - } - - @Test - public void longerClosingFenceTerminatesShorterOpener() - { - String md = "```expression\n" + expressionPayload("Int7 + Int6", "INTEGER") + "\n````"; - JSONArray segments = buildSegments(List.of(markdownResponse(md)), LOG); - assertEquals(1, segments.length()); - assertExpressionSegment(segments, 0, "Int7 + Int6", "INTEGER"); - } - - @Test - public void shorterClosingFenceDoesNotTerminateLongerOpener() - { - // Per CommonMark the short line is fence content, not a closer, so the block never terminates. - String md = "````expression\n" + expressionPayload("Int7 + Int6", "INTEGER") + "\n```"; - JSONArray segments = buildSegments(List.of(markdownResponse(md)), LOG); - assertEquals(1, segments.length()); - assertEquals("html", segment(segments, 0).getString("type")); - } - - @Test - public void leakedPayloadDetectedWhenFenceIsMissing() - { - // No opening fence, so the payload lands in prose and the user gets no Apply affordance. - String md = "Adding Int7 and Int6.\n\n" + expressionPayload("Int7 + Int6", "INTEGER") + "\n```"; - JSONArray segments = buildSegments(List.of(markdownResponse(md)), LOG); - assertEquals(1, segments.length()); - assertEquals("html", segment(segments, 0).getString("type")); - assertTrue("prose payload should be reported as a leak", hasLeakedPayload(segments)); - } - - @Test - public void leakedPayloadDetectedInSqlFence() - { - // The model reached for the illustrative `sql` tag, so the payload renders as a read-only code block. - String md = "```sql\n" + expressionPayload("Int7 + Int6", "INTEGER") + "\n```"; - JSONArray segments = buildSegments(List.of(markdownResponse(md)), LOG); - assertEquals(1, segments.length()); - assertEquals("sql", segment(segments, 0).getString("type")); - assertTrue("payload in a sql block should be reported as a leak", hasLeakedPayload(segments)); - } - @Test - public void leakedPayloadDetectedWhenExpressionBodyIsNotJson() - { - // The model narrated inside the fence, so the body doesn't parse and Apply would write JSON to the field. - String body = "Here is the payload: " + expressionPayload("Int7 + Int6", "INTEGER"); - JSONArray segments = buildSegments(List.of(markdownResponse("```expression\n" + body + "\n```")), LOG); - assertEquals(1, segments.length()); - assertEquals("expression", segment(segments, 0).getString("type")); - assertEquals(body, segment(segments, 0).getString("sql")); - assertTrue("unparsable payload should be reported as a leak", hasLeakedPayload(segments)); - } - - @Test - public void leakedPayloadDetectedWhenExpressionKeyIsMissing() - { - // Parses, but nothing to unpack, so buildSqlSegment falls back to the raw body. - String body = "{\"jdbcType\":\"INTEGER\",\"sql\":\"Int7 + Int6\"}"; - JSONArray segments = buildSegments(List.of(markdownResponse("```expression\n" + body + "\n```")), LOG); - assertEquals(body, segment(segments, 0).getString("sql")); - assertTrue("payload without an expression key should be reported as a leak", hasLeakedPayload(segments)); - } - - @Test - public void wellFormedExpressionSegmentIsNotALeak() - { - // "jdbcType" is a key on the expression segment itself, not part of the SQL the user sees. - String md = "```expression\n" + expressionPayload("Int7 + Int6", "INTEGER") + "\n```"; - JSONArray segments = buildSegments(List.of(markdownResponse(md)), LOG); - assertExpressionSegment(segments, 0, "Int7 + Int6", "INTEGER"); - assertFalse("a parsed expression segment is not a leak", hasLeakedPayload(segments)); - } - - @Test - public void proseWithoutPayloadIsNotALeak() - { - JSONArray segments = buildSegments(List.of(markdownResponse("Which date field should be used?")), LOG); - assertEquals("html", segment(segments, 0).getString("type")); - assertFalse(hasLeakedPayload(segments)); - } - - @Test - public void expressionFenceWithExtraInfoStringTokenIsRecognized() - { - // Only the info string's first word is the tag, so "expression json" still resolves to "expression". - String md = "```expression json\n" + expressionPayload("Int7 + Int6", "INTEGER") + "\n```"; - JSONArray segments = buildSegments(List.of(markdownResponse(md)), LOG); - assertEquals(1, segments.length()); - assertExpressionSegment(segments, 0, "Int7 + Int6", "INTEGER"); - assertNoPayloadInProse(segments); - } - - @Test - public void expressionFenceSplitAcrossResponsesIsRecognized() - { - // Tool calling can split one assistant turn mid-fence; the scan joins the turns so the block still closes. - String payload = expressionPayload("Int7 + Int6", "INTEGER"); - var r1 = markdownResponse("Adding Int7 and Int6.\n\n```expression\n" + payload); - var r2 = markdownResponse("```"); - JSONArray segments = buildSegments(List.of(r1, r2), LOG); - assertEquals(2, segments.length()); - assertEquals("html", segment(segments, 0).getString("type")); - assertExpressionSegment(segments, 1, "Int7 + Int6", "INTEGER"); - assertNoPayloadInProse(segments); - } - - @Test - public void preservesMultilineSqlBody() - { - String multiline = "SELECT a,\n b\nFROM t"; - String md = "```expression\n" + expressionPayload(multiline, "VARCHAR") + "\n```"; - JSONArray segments = buildSegments(List.of(markdownResponse(md)), LOG); - assertEquals(1, segments.length()); - assertEquals(multiline, segment(segments, 0).getString("sql")); - assertEquals("VARCHAR", segment(segments, 0).getString("jdbcType")); + for (Case c : cases) + { + JSONArray segments = buildSegments(c.responses().stream().map(TestCase::markdownResponse).toList(), LOG); + assertEquals(c.name() + ": " + segments, c.expected().length, segments.length()); + for (int i = 0; i < c.expected().length; i++) + assertSegment(c.name(), segment(segments, i), c.expected()[i]); + if (c.leak() != null) + assertEquals(c.name() + ": leak", c.leak(), hasLeakedPayload(segments)); + if (c.noPayloadInProse()) + assertNoPayloadInProse(segments); + } } - @Test - public void multipleMessageResponsesAreConcatenatedInOrder() + private static void assertSegment(String name, JSONObject seg, String expected) { - McpService.MessageResponse r1 = markdownResponse("First response prose."); - McpService.MessageResponse r2 = markdownResponse("```expression\n" + expressionPayload("SELECT 1", "INTEGER") + "\n```"); - JSONArray segments = buildSegments(List.of(r1, r2), LOG); - assertEquals(2, segments.length()); - assertEquals("html", segment(segments, 0).getString("type")); - assertEquals("expression", segment(segments, 1).getString("type")); - assertEquals("SELECT 1", segment(segments, 1).getString("sql")); - assertEquals("INTEGER", segment(segments, 1).getString("jdbcType")); + String[] html = expected.split("~", 2); + if (html.length == 2 && html[0].equals("html")) + { + assertEquals(name, "html", seg.getString("type")); + assertTrue(name + ": " + seg, seg.getString("html").contains(html[1])); + return; + } + String[] typeAndSql = expected.split("=", 2); + assertEquals(name, typeAndSql[0], seg.getString("type")); + if (typeAndSql.length == 1) + return; + int bar = typeAndSql[1].lastIndexOf('|'); + String sql = bar < 0 || typeAndSql[0].equals("sql") ? typeAndSql[1] : typeAndSql[1].substring(0, bar); + assertEquals(name, sql, seg.getString("sql")); + if (bar >= 0 && typeAndSql[0].equals("expression")) + { + String jdbcType = typeAndSql[1].substring(bar + 1); + if (jdbcType.isEmpty()) + assertFalse(name + ": jdbcType should be absent when body isn't JSON", seg.has("jdbcType")); + else + assertEquals(name, jdbcType, seg.getString("jdbcType")); + } } } } diff --git a/api/src/org/labkey/api/module/ModuleLoader.java b/api/src/org/labkey/api/module/ModuleLoader.java index 32d48e67157..7cadccf563b 100644 --- a/api/src/org/labkey/api/module/ModuleLoader.java +++ b/api/src/org/labkey/api/module/ModuleLoader.java @@ -2838,59 +2838,33 @@ private static Set requiredPlus(String... names) return expected; } - private Set allModuleNames() + private Set allModuleNamesExcept(String... names) { - return _modules.stream() + Set expected = _modules.stream() .map(Module::getName) .collect(Collectors.toCollection(TreeSet::new)); + List.of(names).forEach(expected::remove); + return expected; } - @Test - public void testNoIncludeOrExclude() - { - assertEquals(allModuleNames(), filter(Set.of(), Set.of(), _externalModulesDir)); - } - - @Test - public void testExcludeOnly() - { - // Without "include" there's no dependency walk, so B stays even though only A needs it - Set expected = allModuleNames(); - expected.remove("A"); - assertEquals(expected, filter(Set.of(), Set.of("a"), _externalModulesDir)); - } - - @Test - public void testIncludeAddsRequiredAndTransitiveDependencies() - { - // Lowercase "a" also verifies case-insensitive matching - assertEquals(requiredPlus("A", "B", "C"), filter(Set.of("a"), Set.of(), null)); - } - - @Test - public void testIncludeMissingModule() - { - assertEquals(requiredPlus("A", "B", "C"), filter(Set.of("a", "nonexistent"), Set.of(), null)); - } - - @Test - public void testExcludeDependency() - { - // Y is reachable only through excluded X - assertEquals(requiredPlus("E"), filter(Set.of("e"), Set.of("X"), null)); - } - - @Test - public void testExternalModulesIncluded() - { - // DeveloperTools matches by location despite its "devtools" directory; ExtTwo brings in its dependency, C - assertEquals(requiredPlus("D", "DeveloperTools", "ExtTwo", "C"), filter(Set.of("d"), Set.of(), _externalModulesDir)); - } + private record Case(String name, Set include, Set exclude, boolean withExternalDir, Set expected) {} @Test - public void testExternalModuleExcluded() - { - assertEquals(requiredPlus("D", "ExtTwo", "C"), filter(Set.of("d"), Set.of("developertools"), _externalModulesDir)); + public void testFilterModules() + { + for (Case c : List.of( + new Case("no include or exclude", Set.of(), Set.of(), true, allModuleNamesExcept()), + // Without "include" there's no dependency walk, so B stays even though only A needs it + new Case("exclude only", Set.of(), Set.of("a"), true, allModuleNamesExcept("A")), + // Lowercase "a" also verifies case-insensitive matching + new Case("include adds required and transitive dependencies", Set.of("a"), Set.of(), false, requiredPlus("A", "B", "C")), + new Case("include missing module", Set.of("a", "nonexistent"), Set.of(), false, requiredPlus("A", "B", "C")), + // Y is reachable only through excluded X + new Case("exclude dependency", Set.of("e"), Set.of("X"), false, requiredPlus("E")), + // DeveloperTools matches by location despite its "devtools" directory; ExtTwo brings in its dependency, C + new Case("external modules included", Set.of("d"), Set.of(), true, requiredPlus("D", "DeveloperTools", "ExtTwo", "C")), + new Case("external module excluded", Set.of("d"), Set.of("developertools"), true, requiredPlus("D", "ExtTwo", "C")))) + assertEquals(c.name(), c.expected(), filter(c.include(), c.exclude(), c.withExternalDir() ? _externalModulesDir : null)); } @Test diff --git a/api/src/org/labkey/api/query/QueryUpdateServiceTestUtil.java b/api/src/org/labkey/api/query/QueryUpdateServiceTestUtil.java new file mode 100644 index 00000000000..4f84358d8ae --- /dev/null +++ b/api/src/org/labkey/api/query/QueryUpdateServiceTestUtil.java @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2026 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.labkey.api.query; + +import org.jetbrains.annotations.NotNull; +import org.labkey.api.data.Container; +import org.labkey.api.data.TableInfo; +import org.labkey.api.dataiterator.MapDataIterator; +import org.labkey.api.security.User; + +import java.util.List; +import java.util.Map; + +/** Test helpers that call a QueryUpdateService and throw its validation errors instead of returning them */ +public class QueryUpdateServiceTestUtil +{ + public static @NotNull QueryUpdateService getUpdateService(@NotNull TableInfo table) + { + QueryUpdateService qus = table.getUpdateService(); + if (qus == null) + throw new IllegalArgumentException("No QueryUpdateService for " + table.getName()); + return qus; + } + + public static @NotNull TableInfo getTable(User user, Container c, SchemaKey schema, String query) + { + UserSchema userSchema = QueryService.get().getUserSchema(user, c, schema); + if (userSchema == null) + throw new IllegalArgumentException("No schema " + schema + " in " + c.getPath()); + TableInfo table = userSchema.getTable(query); + if (table == null) + throw new IllegalArgumentException("No table " + schema + "." + query + " in " + c.getPath()); + return table; + } + + public static List> insert(TableInfo table, User user, Container c, List> rows) throws Exception + { + BatchValidationException errors = new BatchValidationException(); + List> inserted = getUpdateService(table).insertRows(user, c, rows, errors, null, null); + if (errors.hasErrors()) + throw errors; + return inserted; + } + + public static List> update(TableInfo table, User user, Container c, List> rows) throws Exception + { + BatchValidationException errors = new BatchValidationException(); + List> updated = getUpdateService(table).updateRows(user, c, rows, null, errors, null, null); + if (errors.hasErrors()) + throw errors; + return updated; + } + + public static int merge(TableInfo table, User user, Container c, List> rows) throws Exception + { + BatchValidationException errors = new BatchValidationException(); + int count = getUpdateService(table).mergeRows(user, c, MapDataIterator.of(rows), errors, null, null); + if (errors.hasErrors()) + throw errors; + return count; + } + + public static List> delete(TableInfo table, User user, Container c, List> keys) throws Exception + { + return getUpdateService(table).deleteRows(user, c, keys, null, null); + } +} diff --git a/api/src/org/labkey/api/query/suggestions/FilterSuggestionTestContext.java b/api/src/org/labkey/api/query/suggestions/FilterSuggestionTestContext.java new file mode 100644 index 00000000000..57b25e92bd6 --- /dev/null +++ b/api/src/org/labkey/api/query/suggestions/FilterSuggestionTestContext.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2026 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.labkey.api.query.suggestions; + +import org.jetbrains.annotations.NotNull; +import org.labkey.api.data.Container; +import org.labkey.api.data.ContainerFilter; +import org.labkey.api.data.TableInfo; +import org.labkey.api.security.User; + +/** A fixed context for tests that call a FilterSuggestionProvider directly */ +public record FilterSuggestionTestContext(@NotNull TableInfo getTable, @NotNull ContainerFilter getContainerFilter, + @NotNull Container getContainer, @NotNull User getUser) implements FilterSuggestionContext +{ +} diff --git a/api/src/org/labkey/api/reports/ExternalScriptEngine.java b/api/src/org/labkey/api/reports/ExternalScriptEngine.java index 6856cd6469c..69241e574c2 100644 --- a/api/src/org/labkey/api/reports/ExternalScriptEngine.java +++ b/api/src/org/labkey/api/reports/ExternalScriptEngine.java @@ -65,6 +65,7 @@ import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; +import java.util.stream.Collectors; import static org.labkey.api.reports.report.r.ParamReplacementSvc.SubstitutionSyntax.INLINE; @@ -765,21 +766,15 @@ public void testFullyReplacedScriptSucceeds() throws ScriptException } @Test - public void testUnreplacedSubstitutionThrows() + public void testUnreplacedSubstitutionsThrow() { - String script = "print(\"${unknownParam}\")"; - ScriptException e = assertThrows(ScriptException.class, () -> _engine.writeScriptFile(script, _context, List.of("R"))); - assertTrue("Exception message should name the unreplaced parameter", e.getMessage().contains("unknownParam")); - } - - @Test - public void testMultipleUnreplacedSubstitutionsAreAllNamed() - { - String script = "${firstUnknown} and ${" + KNOWN_PARAM + "} and ${secondUnknown}"; - ScriptException e = assertThrows(ScriptException.class, () -> _engine.writeScriptFile(script, _context, List.of("R"))); - assertTrue("Exception message should name the first unreplaced parameter", e.getMessage().contains("firstUnknown")); - assertTrue("Exception message should name the second unreplaced parameter", e.getMessage().contains("secondUnknown")); - assertFalse("Exception message should not include the known, replaced parameter", e.getMessage().contains(KNOWN_PARAM)); + for (List unknowns : List.of(List.of("unknownParam"), List.of("firstUnknown", "secondUnknown"))) + { + String script = unknowns.stream().map(p -> "${" + p + "}").collect(Collectors.joining(" and ${" + KNOWN_PARAM + "} and ")); + ScriptException e = assertThrows(script, ScriptException.class, () -> _engine.writeScriptFile(script, _context, List.of("R"))); + unknowns.forEach(p -> assertTrue("Exception message should name " + p, e.getMessage().contains(p))); + assertFalse("Exception message should not include the known, replaced parameter", e.getMessage().contains(KNOWN_PARAM)); + } } } } diff --git a/api/src/org/labkey/api/security/permissions/AbstractContainerScopingTest.java b/api/src/org/labkey/api/security/permissions/AbstractContainerScopingTest.java index 39c9d9f4879..b2792c1090b 100644 --- a/api/src/org/labkey/api/security/permissions/AbstractContainerScopingTest.java +++ b/api/src/org/labkey/api/security/permissions/AbstractContainerScopingTest.java @@ -29,8 +29,10 @@ import org.labkey.api.security.SecurityManager; import org.labkey.api.security.SecurityPolicyManager; import org.labkey.api.security.User; +import org.labkey.api.security.UserPrincipal; import org.labkey.api.security.UserManager; import org.labkey.api.security.ValidEmail; +import org.labkey.api.security.roles.ReaderRole; import org.labkey.api.security.roles.Role; import org.labkey.api.security.roles.RoleManager; import org.labkey.api.util.JunitUtil; @@ -60,6 +62,8 @@ * then assert only on data they create. *
  • {@link #createUserInRole(Container, Class)} — make a user with a role assigned in one folder only * (auto-cleaned). Use this to obtain a caller who is, say, admin in folder A, but has no rights in folder B.
  • + *
  • {@link #createRestrictedContainer(String, Module...)} — a throwaway container only site admins can read.
  • + *
  • {@link #createProject(String, Module...)} — a throwaway top-level project, for code that depends on project-level state.
  • *
  • {@link #grantRootRole(User, Class)} — grant a site-wide role such as Platform Developer (auto-cleaned).
  • *
  • {@link #get(ActionURL, User)} / {@link #post(ActionURL, User)} — dispatch an in-JVM request as a given user * and inspect the {@link MockHttpServletResponse} status. Parameters travel on the {@link ActionURL}.
  • @@ -117,6 +121,17 @@ protected Container createContainer(String name, org.labkey.api.module.Module... return c; } + /** Like {@link #createContainer(String, Module...)}, but with its own policy, so only site admins can read it */ + protected Container createRestrictedContainer(String name, Module... enabledModules) + { + Container c = createContainer(name, enabledModules); + // Non-empty, so the folder doesn't inherit the parent's policy + MutableSecurityPolicy policy = new MutableSecurityPolicy(c); + policy.addRoleAssignment(getAdmin(), ReaderRole.class); + SecurityPolicyManager.savePolicyForTests(policy, getAdmin()); + return c; + } + /** * Create a throwaway subfolder of {@code parent} (for example, one from {@link #createContainer(String, Module...)}), * registered for cleanup ahead of its parent. @@ -128,6 +143,22 @@ protected Container createChildContainer(Container parent, String name, Module.. return c; } + /** + * Create a throwaway top-level project, registered for automatic cleanup. Use it only when the code under test + * depends on project-level state (project settings, the project's own policy, /Shared-vs-project lookups); + * otherwise {@link #createContainer(String, Module...)} is enough. + */ + protected Container createProject(String name, Module... enabledModules) + { + String projectName = getClass().getName().replaceAll("[^A-Za-z0-9]", "_") + "-" + name; + Container existing = ContainerManager.getForPath(projectName); + if (existing != null) + ContainerManager.deleteAll(existing, getAdmin()); + Container c = activateModules(ContainerManager.createContainer(ContainerManager.getRoot(), projectName, getAdmin()), enabledModules); + _containers.add(c); + return c; + } + /** * Like {@link #createContainer(String, Module...)}, but created once and reused by every test in the class, then * deleted after the last one. Container deletes are slow, so prefer this whenever a test only asserts on data it @@ -182,14 +213,14 @@ protected User createUserInRole(Container scope, Class role) thr } /** - * Grant {@code role} to an existing {@code user} in {@code scope}, on top of any roles it already holds in that - * container. Use this to build a caller with different roles in different folders (e.g. delete rights in a source + * Grant {@code role} to an existing user or group (including Guests) in {@code scope}, on top of any roles it + * already holds in that container. Use this to build a caller with different roles in different folders (e.g. delete rights in a source * folder but only read access in a target folder). */ - protected void grantRole(User user, Container scope, Class role) throws Exception + protected void grantRole(UserPrincipal principal, Container scope, Class role) throws Exception { MutableSecurityPolicy policy = new MutableSecurityPolicy(scope.getPolicy()); - policy.addRoleAssignment(user, role); + policy.addRoleAssignment(principal, role); SecurityPolicyManager.savePolicyForTests(policy, getAdmin()); } diff --git a/api/src/org/labkey/api/util/ExceptionUtil.java b/api/src/org/labkey/api/util/ExceptionUtil.java index a26402a2826..edb08ba8e83 100644 --- a/api/src/org/labkey/api/util/ExceptionUtil.java +++ b/api/src/org/labkey/api/util/ExceptionUtil.java @@ -42,6 +42,7 @@ import org.labkey.api.data.Container; import org.labkey.api.data.ContainerManager; import org.labkey.api.data.CoreSchema; +import org.labkey.api.data.RequestTestUtil; import org.labkey.api.data.DbScope; import org.labkey.api.data.RequestCancellation; import org.labkey.api.data.RuntimeSQLException; @@ -1733,7 +1734,7 @@ public void testCancelledQuery() throws Exception User me = TestContext.get().getUser(); // A statement cancelled by something other than the server is still an error - RequestCancellation.TestCase.runOnRequestThread(() -> RequestCancellation.TestCase.doRequest(null, () -> { + RequestTestUtil.runOnRequestThread(() -> RequestTestUtil.doRequest(null, () -> { assertFalse(isIgnorable(cancelledQuery())); ExceptionResponse answer = handleIt(me, cancelledQuery()); assertEquals(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, answer.response.status); @@ -1742,7 +1743,7 @@ public void testCancelledQuery() throws Exception })); // The client is still waiting on a timed-out request, so it gets an error, but nothing's logged - RequestCancellation.TestCase.runOnRequestThread(() -> RequestCancellation.TestCase.doRequest(RequestCancellation.Source.TIMEOUT, () -> { + RequestTestUtil.runOnRequestThread(() -> RequestTestUtil.doRequest(RequestCancellation.Source.TIMEOUT, () -> { assertTrue(isIgnorable(cancelledQuery())); assertTrue(isRequestTimeout(cancelledQuery())); assertTrue(isRequestTimeout(new AbortedRequestException("test"))); @@ -1762,7 +1763,7 @@ public void testCancelledQuery() throws Exception })); // Nobody's waiting on a disconnected client - RequestCancellation.TestCase.runOnRequestThread(() -> RequestCancellation.TestCase.doRequest(RequestCancellation.Source.CLIENT_DISCONNECT, () -> { + RequestTestUtil.runOnRequestThread(() -> RequestTestUtil.doRequest(RequestCancellation.Source.CLIENT_DISCONNECT, () -> { assertTrue(isIgnorable(cancelledQuery())); assertFalse(isRequestTimeout(cancelledQuery())); assertFalse(isRequestTimeout(new AbortedRequestException("test"))); diff --git a/api/src/org/labkey/api/util/JunitUtil.java b/api/src/org/labkey/api/util/JunitUtil.java index af7e4dfbe98..1fdacb96ddd 100644 --- a/api/src/org/labkey/api/util/JunitUtil.java +++ b/api/src/org/labkey/api/util/JunitUtil.java @@ -48,7 +48,9 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; +import java.util.function.Predicate; import java.util.stream.Stream; @@ -162,6 +164,74 @@ public static void createRaces(final Runnable runnable, final int threads, final throw new IllegalStateException("Did not execute runnable the expected number of times: " + iterations + " vs. " + expected); } + @FunctionalInterface + public interface ThrowingRunnable + { + void run() throws Exception; + } + + /** + * Runs body on a new thread that carries the caller's TestContext, waits up to a minute for it, and rethrows + * whatever it threw. Use it for work that must not share the test thread's connection, transaction, or request state. + */ + public static void runOnNewThread(String threadName, ThrowingRunnable body) throws Exception + { + TestContext context = TestContext.get(); + AtomicReference failure = new AtomicReference<>(); + Thread thread = new Thread(() -> { + try + { + if (context != null) + TestContext.setTestContext(context.getRequest(), context.getUser()); + body.run(); + } + catch (Throwable t) + { + failure.set(t); + } + finally + { + DbScope.finishedWithThread(); + } + }, threadName); + + thread.start(); + thread.join(60_000); + Assert.assertFalse("Thread '" + threadName + "' didn't exit", thread.isAlive()); + + switch (failure.get()) + { + case null -> {} + case Error e -> throw e; + case Exception e -> throw e; + default -> throw new RuntimeException(failure.get()); + } + } + + /** True if t or anything in its cause chain matches */ + public static boolean hasCause(@Nullable Throwable t, Predicate match) + { + for (; t != null; t = ExceptionUtil.getCause(t)) + if (match.test(t)) + return true; + return false; + } + + /** Skips the test unless the labkey scope is PostgreSQL */ + public static void assumePostgres() + { + Assume.assumeTrue("Requires PostgreSQL", DbScope.getLabKeyScope().getSqlDialect().isPostgreSQL()); + } + + /** Skips the test unless the JVM runs with -ea, for tests of code that only runs inside an assert */ + public static void assumeAssertionsEnabled() + { + boolean enabled = false; + //noinspection AssertWithSideEffects,ConstantValue + assert enabled = true; + Assume.assumeTrue("Requires assertions to be enabled (-ea)", enabled); + } + private static final java.nio.file.Path SAMPLE_DATA_PATH = Paths.get("test", "sampledata"); private static final Object MAP_LOCK = new Object(); diff --git a/api/src/org/labkey/api/util/TracedOperation.java b/api/src/org/labkey/api/util/TracedOperation.java index 6585be9cd3c..1136dfc1c09 100644 --- a/api/src/org/labkey/api/util/TracedOperation.java +++ b/api/src/org/labkey/api/util/TracedOperation.java @@ -336,18 +336,10 @@ public void testRunWithOperation() IllegalStateException thrown = new IllegalStateException("test"); AtomicReference failed = new AtomicReference<>(); - try - { - TracedOperation.builder("labkey.test").resource("test").describedAs("test").run(op -> { - failed.set(op); - throw thrown; - }); - fail("Expected the work's exception to propagate"); - } - catch (IllegalStateException e) - { - assertSame(thrown, e); - } + assertSame(thrown, assertThrows(IllegalStateException.class, () -> TracedOperation.builder("labkey.test").resource("test").describedAs("test").run(op -> { + failed.set(op); + throw thrown; + }))); assertFalse(failed.get()._completed); assertTrue(failed.get()._closed); } diff --git a/api/src/org/mitre/dsmiley/httpproxy/LabKeyProxyServlet.java b/api/src/org/mitre/dsmiley/httpproxy/LabKeyProxyServlet.java index 818ff5e8234..7bc3af755e5 100644 --- a/api/src/org/mitre/dsmiley/httpproxy/LabKeyProxyServlet.java +++ b/api/src/org/mitre/dsmiley/httpproxy/LabKeyProxyServlet.java @@ -23,6 +23,7 @@ import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.function.Consumer; import static org.apache.commons.lang3.StringUtils.trimToEmpty; @@ -248,89 +249,52 @@ public static class TestCase extends Assert private static final String ASSERTED_HEADER = "X-Proxy-Asserted"; /** Every header on the forwarded request, so a stray passthrough under another name fails the test. */ - private List forwarded(BasicHttpRequest proxyRequest) - { - return Arrays.stream(proxyRequest.getHeaders()).map(h -> h.getName() + "=" + h.getValue()).toList(); - } - - private List forward(@Nullable String clientHeaderName, @Nullable String assertedValue) + private List forward(Consumer setup) { MockHttpServletRequest servletRequest = new MockHttpServletRequest(); - if (null != clientHeaderName) - servletRequest.addHeader(clientHeaderName, "fromClient"); - if (null != assertedValue) - assertHeader(servletRequest, ASSERTED_HEADER, assertedValue); - + setup.accept(servletRequest); BasicHttpRequest proxyRequest = new BasicHttpRequest("GET", "/"); new LabKeyProxyServlet().copyRequestHeaders(servletRequest, proxyRequest); - - return forwarded(proxyRequest); - } - - @Test - public void testAssertedHeaderReplacesClientCopy() - { - assertEquals(List.of(ASSERTED_HEADER + "=fromProxy"), forward(ASSERTED_HEADER, "fromProxy")); + return Arrays.stream(proxyRequest.getHeaders()).map(h -> h.getName() + "=" + h.getValue()).toList(); } - @Test - public void testAssertedHeaderReplacesClientCopyRegardlessOfCase() + private static Consumer clientSends(String name, @Nullable String assertedValue) { - assertEquals(List.of(ASSERTED_HEADER + "=fromProxy"), forward(ASSERTED_HEADER.toLowerCase(), "fromProxy")); - assertEquals(List.of(ASSERTED_HEADER + "=fromProxy"), forward(ASSERTED_HEADER.toUpperCase(), "fromProxy")); + return r -> { + r.addHeader(name, "fromClient"); + assertHeader(r, ASSERTED_HEADER, assertedValue); + }; } - @Test - public void testAssertedHeaderForwardedWhenClientSentNone() - { - assertEquals(List.of(ASSERTED_HEADER + "=fromProxy"), forward(null, "fromProxy")); - } + private record Case(String name, Consumer setup, List expected) {} @Test - public void testClientCopyForwardedWhenNothingAsserted() + public void testCopyRequestHeaders() { - assertEquals(List.of(ASSERTED_HEADER + "=fromClient"), forward(ASSERTED_HEADER, null)); - } - - @Test - public void testNullAssertedValueStripsClientCopy() - { - MockHttpServletRequest servletRequest = new MockHttpServletRequest(); - servletRequest.addHeader(ASSERTED_HEADER, "fromClient"); - assertHeader(servletRequest, ASSERTED_HEADER, null); - - BasicHttpRequest proxyRequest = new BasicHttpRequest("GET", "/"); - new LabKeyProxyServlet().copyRequestHeaders(servletRequest, proxyRequest); - - assertEquals(List.of(), forwarded(proxyRequest)); + List fromProxy = List.of(ASSERTED_HEADER + "=fromProxy"); + for (Case c : List.of( + new Case("asserted replaces client copy", clientSends(ASSERTED_HEADER, "fromProxy"), fromProxy), + new Case("asserted replaces lowercase client copy", clientSends(ASSERTED_HEADER.toLowerCase(), "fromProxy"), fromProxy), + new Case("asserted replaces uppercase client copy", clientSends(ASSERTED_HEADER.toUpperCase(), "fromProxy"), fromProxy), + new Case("asserted forwarded when client sent none", r -> assertHeader(r, ASSERTED_HEADER, "fromProxy"), fromProxy), + new Case("client copy forwarded when nothing asserted", r -> r.addHeader(ASSERTED_HEADER, "fromClient"), List.of(ASSERTED_HEADER + "=fromClient")), + new Case("null asserted value strips client copy", clientSends(ASSERTED_HEADER, null), List.of()), + new Case("other headers untouched", r -> { + r.addHeader("Accept", "text/html"); + r.addHeader("Accept", "text/plain"); + assertHeader(r, ASSERTED_HEADER, "fromProxy"); + }, List.of("Accept=text/html", "Accept=text/plain", ASSERTED_HEADER + "=fromProxy")))) + assertEquals(c.name(), c.expected(), forward(c.setup())); } @Test public void testLaterAssertionWinsRegardlessOfCase() { - MockHttpServletRequest servletRequest = new MockHttpServletRequest(); - assertHeader(servletRequest, ASSERTED_HEADER, "first"); - assertHeader(servletRequest, ASSERTED_HEADER.toLowerCase(), "second"); - - BasicHttpRequest proxyRequest = new BasicHttpRequest("GET", "/"); - new LabKeyProxyServlet().copyRequestHeaders(servletRequest, proxyRequest); - - assertEquals(1, proxyRequest.getHeaders(ASSERTED_HEADER).length); - assertEquals("second", proxyRequest.getHeaders(ASSERTED_HEADER)[0].getValue()); - } - - @Test - public void testOtherHeadersUntouched() - { - MockHttpServletRequest servletRequest = new MockHttpServletRequest(); - servletRequest.addHeader("Accept", "text/html"); - servletRequest.addHeader("Accept", "text/plain"); - assertHeader(servletRequest, ASSERTED_HEADER, "fromProxy"); - - BasicHttpRequest proxyRequest = new BasicHttpRequest("GET", "/"); - new LabKeyProxyServlet().copyRequestHeaders(servletRequest, proxyRequest); - - assertEquals(List.of("Accept=text/html", "Accept=text/plain", ASSERTED_HEADER + "=fromProxy"), forwarded(proxyRequest)); + List forwarded = forward(r -> { + assertHeader(r, ASSERTED_HEADER, "first"); + assertHeader(r, ASSERTED_HEADER.toLowerCase(), "second"); + }); + assertEquals(List.of((ASSERTED_HEADER + "=second").toLowerCase()), forwarded.stream().map(String::toLowerCase).toList()); } } } diff --git a/assay/src/org/labkey/assay/AssayManager.java b/assay/src/org/labkey/assay/AssayManager.java index c0ef31db086..5506424b95c 100644 --- a/assay/src/org/labkey/assay/AssayManager.java +++ b/assay/src/org/labkey/assay/AssayManager.java @@ -1126,7 +1126,7 @@ public static void setup() throws Exception _container = JunitUtil.getTestContainer(); AssayDomainService domainService = new AssayDomainServiceImpl(TestContext.get().getUser(), _container); - GWTProtocol template = domainService.getAssayTemplate("General"); + GWTProtocol template = domainService.getAssayTemplate(TsvAssayProvider.NAME); template.setName("ProtocolCacheTestAssay"); GWTProtocol saved = domainService.saveChanges(template, true); _protocol = ExperimentService.get().getExpProtocol(saved.getProtocolId()); diff --git a/audit/src/org/labkey/audit/model/LogManager.java b/audit/src/org/labkey/audit/model/LogManager.java index b648462fd85..187f6d2915b 100644 --- a/audit/src/org/labkey/audit/model/LogManager.java +++ b/audit/src/org/labkey/audit/model/LogManager.java @@ -31,7 +31,6 @@ import org.labkey.api.collections.CaseInsensitiveHashMap; import org.labkey.api.data.Container; import org.labkey.api.data.ContainerFilter; -import org.labkey.api.data.ContainerManager; import org.labkey.api.data.DbSchema; import org.labkey.api.data.DbScope; import org.labkey.api.data.ObjectFactory; @@ -50,6 +49,7 @@ import org.labkey.api.query.FieldKey; import org.labkey.api.query.UserSchema; import org.labkey.api.security.User; +import org.labkey.api.util.JunitUtil; import org.labkey.api.util.TestContext; import org.labkey.api.view.HttpView; import org.labkey.audit.AuditSchema; @@ -291,8 +291,6 @@ private boolean trimToColumnSizes(@NotNull Domain domain, @NotNull Set snippets = _manager.getChatHistory(other, _conversationId); + Container folder = createRestrictedContainer("Restricted"); + assertFalse(folder.hasPermission(OTHER, ReadPermission.class)); + + _manager.addChatSnippet(_session, OTHER, folder, AGENT, _conversationId, Role.user, "Secret"); + _manager.addChatSnippet(_session, OTHER, folder, AGENT, _conversationId, Role.assistant, "[]"); + + List snippets = _manager.getChatHistory(OTHER, _conversationId); assertEquals(List.of(Role.user, Role.assistant), snippets.stream().map(ChatSnippet::role).toList()); for (ChatSnippet snippet : snippets) { diff --git a/core/src/org/labkey/core/LabKeyAssistantAgentAction.java b/core/src/org/labkey/core/LabKeyAssistantAgentAction.java index 1ef1dcf7a1d..4cff90682f8 100644 --- a/core/src/org/labkey/core/LabKeyAssistantAgentAction.java +++ b/core/src/org/labkey/core/LabKeyAssistantAgentAction.java @@ -6,9 +6,6 @@ import org.jetbrains.annotations.Nullable; import org.json.JSONArray; import org.json.JSONObject; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; import org.junit.Test; import org.labkey.api.data.Container; import org.labkey.api.data.ContainerManager; @@ -18,13 +15,11 @@ import org.labkey.api.mcp.McpContext; import org.labkey.api.mcp.McpService; import org.labkey.api.mcp.PromptForm; -import org.labkey.api.security.MutableSecurityPolicy; import org.labkey.api.security.RequiresLogin; import org.labkey.api.security.RequiresPermission; -import org.labkey.api.security.SecurityPolicyManager; import org.labkey.api.security.User; +import org.labkey.api.security.permissions.AbstractContainerScopingTest; import org.labkey.api.security.permissions.ReadPermission; -import org.labkey.api.security.roles.ReaderRole; import org.labkey.api.settings.AppProps; import org.labkey.api.settings.OptionalFeatureService; import org.labkey.api.util.AbortedRequestException; @@ -201,22 +196,11 @@ static String composePrompt(String userPrompt, @Nullable String previousContaine "\". Call whereAmIWhoAmITalkingTo again if you need its details.]\n\n" + userPrompt; } - public static class TestCase extends Assert + public static class TestCase extends AbstractContainerScopingTest { - private static final String FOLDER_NAME = "LabKeyAssistantTestCase"; - private final User _user = TestContext.get().getUser(); private final Container _junit = JunitUtil.getTestContainer(); - @Before - @After - public void cleanup() - { - Container folder = ContainerManager.getForPath(_junit.getPath() + "/" + FOLDER_NAME); - if (null != folder) - ContainerManager.deleteAll(folder, _user); - } - @Test public void testPromptUnchangedWithoutMove() { @@ -228,7 +212,7 @@ public void testPromptUnchangedWithoutMove() @Test public void testMoveNamesReadableFolder() { - Container folder = ContainerManager.createContainer(_junit, FOLDER_NAME, _user); + Container folder = createContainer("Readable"); String composed = composePrompt("Hi", _junit.getId(), folder, _user); assertTrue(composed, composed.contains("from the folder \"" + _junit.getPath() + "\" to the folder \"" + folder.getPath() + "\"")); assertTrue(composed, composed.endsWith("\n\nHi")); @@ -237,11 +221,7 @@ public void testMoveNamesReadableFolder() @Test public void testMoveHidesUnreadableFolder() { - Container folder = ContainerManager.createContainer(_junit, FOLDER_NAME, _user); - // A non-empty policy of its own, so the folder doesn't inherit the parent's - MutableSecurityPolicy policy = new MutableSecurityPolicy(folder); - policy.addRoleAssignment(_user, ReaderRole.class); - SecurityPolicyManager.savePolicyForTests(policy, _user); + Container folder = createRestrictedContainer("Restricted"); User other = new User("docassistant-other@example.com", Integer.MAX_VALUE - 2); assertFalse(folder.hasPermission(other, ReadPermission.class)); diff --git a/core/src/org/labkey/core/QuartzShutdown.java b/core/src/org/labkey/core/QuartzShutdown.java index c71a6024a21..7c5dfd2c6e1 100644 --- a/core/src/org/labkey/core/QuartzShutdown.java +++ b/core/src/org/labkey/core/QuartzShutdown.java @@ -31,6 +31,7 @@ import org.quartz.TriggerBuilder; import org.quartz.core.JobRunShell; import org.quartz.impl.StdSchedulerFactory; +import org.quartz.simpl.RAMJobStore; import java.time.Duration; import java.util.Arrays; @@ -156,8 +157,8 @@ public void setUp() throws SchedulerException Properties props = new Properties(); props.setProperty(StdSchedulerFactory.PROP_SCHED_INSTANCE_NAME, "QuartzShutdownTest-" + GUID.makeGUID()); - props.setProperty("org.quartz.threadPool.threadCount", "2"); - props.setProperty("org.quartz.jobStore.class", "org.quartz.simpl.RAMJobStore"); + props.setProperty(StdSchedulerFactory.PROP_THREAD_POOL_PREFIX + ".threadCount", "2"); + props.setProperty(StdSchedulerFactory.PROP_JOB_STORE_CLASS, RAMJobStore.class.getName()); _scheduler = new StdSchedulerFactory(props).getScheduler(); _scheduler.start(); } diff --git a/core/src/org/labkey/core/security/SecurityController.java b/core/src/org/labkey/core/security/SecurityController.java index 9ee49717a9e..f13159186ef 100644 --- a/core/src/org/labkey/core/security/SecurityController.java +++ b/core/src/org/labkey/core/security/SecurityController.java @@ -2550,8 +2550,6 @@ public void validateAdministratorRolePermissionAssignment() */ public static class GroupMembershipScopingTestCase extends AbstractContainerScopingTest { - // ProjectAdminRole only applies to projects, so these fixtures are projects rather than /_junit children - private static final String PROJECT_NAME = "GroupMembershipScopingProject"; private static final String SITE_GROUP_NAME = "GroupMembershipScopingSiteGroup"; private Container _project; @@ -2563,7 +2561,8 @@ public static class GroupMembershipScopingTestCase extends AbstractContainerScop public void setup() throws Exception { cleanup(); - _project = ContainerManager.createContainer(ContainerManager.getRoot(), PROJECT_NAME, getAdmin()); + // ProjectAdminRole only applies to projects, so this fixture is a project rather than a /_junit child + _project = createProject("Project"); _siteGroup = SecurityManager.createGroup(ContainerManager.getRoot(), SITE_GROUP_NAME, getAdmin()); _siteGroupMember = createUserInRole(_project, ReaderRole.class); SecurityManager.addMember(_siteGroup, _siteGroupMember); @@ -2573,10 +2572,6 @@ public void setup() throws Exception @After public void cleanup() { - Container project = ContainerManager.getForPath("/" + PROJECT_NAME); - if (project != null) - ContainerManager.deleteAll(project, getAdmin()); - Integer siteGroupId = SecurityManager.getGroupId(null, SITE_GROUP_NAME, false); if (siteGroupId != null) SecurityManager.deleteGroup(SecurityManager.getGroup(siteGroupId), getAdmin()); diff --git a/core/test/src/org/labkey/test/tests/RequestCancellationTest.java b/core/test/src/org/labkey/test/tests/RequestCancellationTest.java index 36a459b343a..bbfac88a46b 100644 --- a/core/test/src/org/labkey/test/tests/RequestCancellationTest.java +++ b/core/test/src/org/labkey/test/tests/RequestCancellationTest.java @@ -21,10 +21,8 @@ import org.junit.experimental.categories.Category; import org.labkey.remoteapi.CommandException; import org.labkey.remoteapi.Connection; -import org.labkey.remoteapi.query.ExecuteSqlCommand; import org.labkey.remoteapi.query.Filter; import org.labkey.remoteapi.query.SelectRowsCommand; -import org.labkey.remoteapi.query.SelectRowsResponse; import org.labkey.test.BaseWebDriverTest; import org.labkey.test.TestProperties; import org.labkey.test.WebTestHelper; @@ -33,19 +31,19 @@ import org.labkey.test.util.ArtifactCollector; import org.labkey.test.util.DataRegionTable; import org.labkey.test.util.OptionalFeatureHelper; -import org.labkey.test.util.core.admin.ServerUsageUtils; +import org.labkey.test.util.RequestCancellationHelper; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; -import java.util.stream.Collectors; -import java.util.stream.IntStream; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.junit.Assume.assumeFalse; +import static org.labkey.test.util.RequestCancellationHelper.WS_CLOSE; +import static org.labkey.test.util.RequestCancellationHelper.WS_MESSAGE; /** * Checks that an abandoned read-only request is canceled on the server end to end: the page tags the request, sends @@ -59,12 +57,11 @@ public class RequestCancellationTest extends BaseWebDriverTest private static final String SLOW_NAMES_SQL = "SELECT a.Name, COUNT(*) AS n FROM core.Modules a, core.Modules b, core.Modules c, core.Modules d, core.Modules e, core.Modules f GROUP BY a.Name"; private static final String SLOW_STATS = "SlowStats"; private static final double SLOW_STATS_ROWS = 3e7; - private static final int METRICS_TIMEOUT = 180_000; private static final int CANCEL_EXIT_TIMEOUT = 30_000; - private static final String WS_MESSAGE = "wsMessage"; - private static final String WS_CLOSE = "wsClose"; private static final String FEATURE_DISABLE_CANCELLING = "disableCancelAbandonedRequests"; + private final RequestCancellationHelper _cancels = new RequestCancellationHelper(this); + @BeforeClass public static void setupProject() throws Exception { @@ -81,22 +78,17 @@ public static void setupProject() throws Exception */ private String getSlowStatsSql() throws IOException, CommandException { - SelectRowsResponse response = new ExecuteSqlCommand("core", "SELECT Name FROM core.Modules ORDER BY Name") - .execute(createDefaultConnection(), getProjectName()); - List names = response.getRows().stream().map(row -> (String) row.get("Name")).toList(); + List names = _cancels.getModuleNames(getProjectName()); int modules = names.size(); // Val needs three of them int joins = Math.max(3, (int) Math.ceil(Math.log(SLOW_STATS_ROWS) / Math.log(modules))); int lastJoinModules = (int) Math.min(modules, Math.ceil(SLOW_STATS_ROWS / Math.pow(modules, joins - 1))); - String from = IntStream.range(0, joins) - .mapToObj(i -> "core.Modules m" + i) - .collect(Collectors.joining(", ")); String lastJoinNames = names.subList(0, lastJoinModules).stream() .map(name -> "'" + name.replace("'", "''") + "'") .collect(Collectors.joining(", ")); return "SELECT m0.Name AS A, m1.Name AS B, CAST(LENGTH(m0.Name) * 10000 + LENGTH(m1.Name) * 100 + LENGTH(m2.Name) AS DOUBLE) AS Val" + - " FROM " + from + " WHERE m" + (joins - 1) + ".Name IN (" + lastJoinNames + ")"; + " FROM " + RequestCancellationHelper.crossJoinModules(joins) + " WHERE m" + (joins - 1) + ".Name IN (" + lastJoinNames + ")"; } @Before @@ -104,7 +96,7 @@ public void preTest() { goToProjectHome(); assertTrue("Cancelling abandoned requests is disabled", isCancellingEnabledOnPage()); - waitForWebSocket(); + _cancels.waitForWebSocket(); } @Test @@ -124,34 +116,34 @@ public void testAbortedSelectDistinctIsCancelledOnServer() throws Exception @Test public void testClosingSummaryStatisticsCancelsItsQuery() throws Exception { - long before = getCancelCount(WS_MESSAGE); + long before = _cancels.getCancelCount(WS_MESSAGE); beginAt(WebTestHelper.buildURL("query", getProjectName(), "executeQuery", Map.of("schemaName", "core", "query.queryName", SLOW_STATS))); - waitForWebSocket(); + _cancels.waitForWebSocket(); DataRegionTable.DataRegion(getDriver()).withName("query").waitFor().clickColumnMenu("Val", false, "Summary Statistics..."); sleep(2000); // Let the server start the stats query before the dialog closes // SummaryStatisticsDialog waits for the stats, which never arrive new Window<>("Summary Statistics", getDriver()).clickButton("Cancel", true); waitForSlowQueriesToStop(); - waitForCancelCount(WS_MESSAGE, before + 1); + _cancels.waitForCancelCount(WS_MESSAGE, before + 1); } @Test public void testClosedTabCancelsItsRequests() throws Exception { - long before = getCancelCount(WS_CLOSE); + long before = _cancels.getCancelCount(WS_CLOSE); doInNewTab(() -> { goToProjectHome(); - waitForWebSocket(); + _cancels.waitForWebSocket(); assertTrue("Request wasn't tagged as cancellable", startSlowRequest("executeSql", Map.of("schemaName", "core", "sql", SLOW_SQL))); sleep(2000); // Let the server start the request before the tab closes return null; }); waitForSlowQueriesToStop(); - waitForCancelCount(WS_CLOSE, before + 1); + _cancels.waitForCancelCount(WS_CLOSE, before + 1); } @Test @@ -177,7 +169,7 @@ public void testOptOutDisablesCancelling() private void abortSlowRequest(String apiFunction, Map config) throws Exception { - long before = getCancelCount(WS_MESSAGE); + long before = _cancels.getCancelCount(WS_MESSAGE); assertTrue("Request wasn't tagged as cancellable", startSlowRequest(apiFunction, config)); sleep(2000); // Let the server start the request before the cancel arrives @@ -186,7 +178,7 @@ private void abortSlowRequest(String apiFunction, Map config) th waitForEquals("Wrong request outcome", () -> "aborted", () -> executeScript("return window.requestCancelTest.outcome;"), WAIT_FOR_JAVASCRIPT); waitForSlowQueriesToStop(); - waitForCancelCount(WS_MESSAGE, before + 1); + _cancels.waitForCancelCount(WS_MESSAGE, before + 1); } /** The cancel count only shows a cancel was sent, not that the query stopped */ @@ -228,12 +220,6 @@ private boolean isCancellingEnabledOnPage() return (Boolean) executeScript("return LABKEY.experimental.cancelAbandonedRequests === true;"); } - private void waitForWebSocket() - { - // The server ignores any message type but "cancel" - waitFor(() -> (Boolean) executeScript("return LABKEY.WebSocket.send({ type: 'ping' });"), "The notification WebSocket didn't open", WAIT_FOR_JAVASCRIPT); - } - /** * Starts a request through a LABKEY.Query function that is cancellable by default, abortable through * window.requestCancelTest.controller @@ -252,36 +238,6 @@ private boolean startSlowRequest(String apiFunction, Map config) """, apiFunction, config); } - /** At least, since the counter is server-wide and other cancels can land meanwhile */ - private void waitForCancelCount(String metric, long minimum) - { - waitFor(() -> getCancelCountUnchecked(metric) >= minimum, "Requests canceled (" + metric + ") never reached " + minimum, METRICS_TIMEOUT); - } - - private long getCancelCountUnchecked(String metric) - { - try - { - return getCancelCount(metric); - } - catch (IOException | CommandException e) - { - throw new RuntimeException(e); - } - } - - /** Server-wide count of requests canceled from one source, e.g. a page's WebSocket message, from Core's usage metrics */ - @SuppressWarnings("unchecked") - private long getCancelCount(String metric) throws IOException, CommandException - { - // The usage report gathers every module's metrics, which can take over a minute on a large database - Connection connection = createDefaultConnection().setTimeout(METRICS_TIMEOUT); - Map core = ServerUsageUtils.getModuleMetrics(connection, "Core"); - Map counts = (Map) core.getOrDefault("simpleMetricCounts", Map.of()); - Map requestCancel = (Map) counts.getOrDefault("requestCancel", Map.of()); - return ((Number) requestCancel.getOrDefault(metric, 0)).longValue(); - } - @Override protected String getProjectName() { diff --git a/experiment/src/org/labkey/experiment/IllegalFieldNameMetricsMaintenanceTask.java b/experiment/src/org/labkey/experiment/IllegalFieldNameMetricsMaintenanceTask.java index 5c0214fdf48..8f53555d093 100644 --- a/experiment/src/org/labkey/experiment/IllegalFieldNameMetricsMaintenanceTask.java +++ b/experiment/src/org/labkey/experiment/IllegalFieldNameMetricsMaintenanceTask.java @@ -31,7 +31,8 @@ import org.labkey.api.exp.api.ExpSampleType; import org.labkey.api.exp.api.ExperimentJSONConverter; import org.labkey.api.exp.api.ExperimentService; -import org.labkey.api.exp.api.SampleTypeService; +import org.labkey.api.exp.api.SampleTypeDomainKind; +import org.labkey.api.exp.api.SampleTypeTestHelper; import org.labkey.api.audit.AbstractAuditTypeProvider; import org.labkey.api.collections.CaseInsensitiveHashSet; import org.labkey.api.exp.property.DomainKind; @@ -44,9 +45,10 @@ import org.labkey.api.util.JunitUtil; import org.labkey.api.util.SystemMaintenance.MaintenanceTask; import org.labkey.api.util.TestContext; +import org.labkey.experiment.api.ExperimentServiceImpl; import java.util.ArrayList; -import java.util.Collections; +import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; @@ -326,7 +328,7 @@ Map toMap() public static class TestCase extends Assert { private static final String ST_NAME = "IllegalNameMetricsTest"; - private static final String KIND = "SampleSet"; + private static final String KIND = SampleTypeDomainKind.NAME; @Before @After @@ -351,16 +353,7 @@ public void testIllegalNameMetrics() throws Exception long baseDupeAlias = count(metrics, FieldNameRule.duplicateImportAlias.name()); long baseParentAlias = count(metrics, "parentAliasConflict"); - List props = new ArrayList<>(); - props.add(new GWTPropertyDescriptor("Name", PropertyType.STRING.getTypeUri())); - props.add(new GWTPropertyDescriptor("WillBecomeReserved", PropertyType.STRING.getTypeUri())); - props.add(new GWTPropertyDescriptor("WillAliasContainer", PropertyType.STRING.getTypeUri())); - props.add(new GWTPropertyDescriptor("DupeAliasOne", PropertyType.STRING.getTypeUri())); - props.add(new GWTPropertyDescriptor("DupeAliasTwo", PropertyType.STRING.getTypeUri())); - - ExpSampleType st = SampleTypeService.get().createSampleType(c, user, ST_NAME, null, props, - Collections.emptyList(), -1, -1, -1, -1, null); - assertNotNull("sample type should be created", st); + ExpSampleType st = SampleTypeTestHelper.create(c, user, ST_NAME, strings("WillBecomeReserved", "WillAliasContainer", "DupeAliasOne", "DupeAliasTwo")); // Make the fields illegal behind the designer's back, which is the state an upgraded server is in: these // configurations were legal when saved and validateProperties would reject them now. @@ -397,18 +390,7 @@ public void testLabelCollisionMetrics() throws Exception long baseLabelVsName = count(metrics, FieldNameRule.labelVsFieldName.name()); long baseLabelVsAlias = count(metrics, FieldNameRule.labelVsImportAlias.name()); - List props = new ArrayList<>(); - props.add(new GWTPropertyDescriptor("Name", PropertyType.STRING.getTypeUri())); - props.add(new GWTPropertyDescriptor("Shadowed", PropertyType.STRING.getTypeUri())); - props.add(new GWTPropertyDescriptor("Winner", PropertyType.STRING.getTypeUri())); - props.add(new GWTPropertyDescriptor("LabelTwinOne", PropertyType.STRING.getTypeUri())); - props.add(new GWTPropertyDescriptor("LabelTwinTwo", PropertyType.STRING.getTypeUri())); - props.add(new GWTPropertyDescriptor("AliasOwner", PropertyType.STRING.getTypeUri())); - props.add(new GWTPropertyDescriptor("LabelStealsAlias", PropertyType.STRING.getTypeUri())); - - ExpSampleType st = SampleTypeService.get().createSampleType(c, user, ST_NAME, null, props, - Collections.emptyList(), -1, -1, -1, -1, null); - assertNotNull("sample type should be created", st); + ExpSampleType st = SampleTypeTestHelper.create(c, user, ST_NAME, strings("Shadowed", "Winner", "LabelTwinOne", "LabelTwinTwo", "AliasOwner", "LabelStealsAlias")); DbScope scope = ExperimentService.get().getSchema().getScope(); SqlExecutor executor = new SqlExecutor(scope); @@ -444,13 +426,7 @@ public void testLabelMatchingOwnFieldIsNotCounted() throws Exception long baseLabelVsAlias = count(metrics, FieldNameRule.labelVsImportAlias.name()); long baseDupeLabel = count(metrics, FieldNameRule.duplicateLabel.name()); - List props = new ArrayList<>(); - props.add(new GWTPropertyDescriptor("Name", PropertyType.STRING.getTypeUri())); - props.add(new GWTPropertyDescriptor("SelfOwner", PropertyType.STRING.getTypeUri())); - - ExpSampleType st = SampleTypeService.get().createSampleType(c, user, ST_NAME, null, props, - Collections.emptyList(), -1, -1, -1, -1, null); - assertNotNull("sample type should be created", st); + ExpSampleType st = SampleTypeTestHelper.create(c, user, ST_NAME, strings("SelfOwner")); // One field owning both its label and the matching alias resolves to that field either way. DbScope scope = ExperimentService.get().getSchema().getScope(); @@ -479,19 +455,13 @@ public void testParentAliasConflict() throws Exception task.run(log); long baseParentAlias = count(IllegalFieldNameMetricsProvider.getInstance().getUsageMetrics(), "parentAliasConflict"); - List props = new ArrayList<>(); - props.add(new GWTPropertyDescriptor("Name", PropertyType.STRING.getTypeUri())); - props.add(new GWTPropertyDescriptor("Collision", PropertyType.STRING.getTypeUri())); - - ExpSampleType st = SampleTypeService.get().createSampleType(c, user, ST_NAME, null, props, - Collections.emptyList(), -1, -1, -1, -1, null); - assertNotNull("sample type should be created", st); + ExpSampleType st = SampleTypeTestHelper.create(c, user, ST_NAME, strings("Collision")); // A parent alias header that collides with a field name. Saving this through the designer is blocked, so // write it directly to reproduce a pre-validation configuration. DbScope scope = ExperimentService.get().getSchema().getScope(); - new SqlExecutor(scope).execute(SQLFragment.unsafe( - "UPDATE exp.materialsource SET materialparentimportaliasmap = ? WHERE lsid = ?") + new SqlExecutor(scope).execute(SQLFragment.unsafe("UPDATE ").append(ExperimentServiceImpl.get().getTinfoSampleType()) + .unsafeAppend(" SET materialparentimportaliasmap = ? WHERE lsid = ?") .add("{\"Collision\":\"materialInputs/Whatever\"}").add(st.getLSID())); task.run(log); @@ -501,13 +471,18 @@ public void testParentAliasConflict() throws Exception private static void update(SqlExecutor executor, int domainId, String fieldName, String column, String value) { - SQLFragment sql = SQLFragment.unsafe("UPDATE exp.propertydescriptor SET "); + SQLFragment sql = SQLFragment.unsafe("UPDATE ").append(OntologyManager.getTinfoPropertyDescriptor()).unsafeAppend(" SET "); sql.appendIdentifier(column).unsafeAppend(" = ?").add(value); - sql.unsafeAppend(" WHERE name = ? AND propertyid IN (SELECT propertyid FROM exp.propertydomain WHERE domainid = ?)") - .add(fieldName).add(domainId); + sql.unsafeAppend(" WHERE name = ? AND propertyid IN (SELECT propertyid FROM ").append(OntologyManager.getTinfoPropertyDomain()) + .unsafeAppend(" WHERE domainid = ?)").add(fieldName).add(domainId); assertEquals("expected to rewrite one field", 1, executor.execute(sql)); } + private static GWTPropertyDescriptor[] strings(String... names) + { + return Arrays.stream(names).map(n -> new GWTPropertyDescriptor(n, PropertyType.STRING.getTypeUri())).toArray(GWTPropertyDescriptor[]::new); + } + /** Sums a rule's per-kind counts for the sample type kind. */ @SuppressWarnings("unchecked") private static long count(Map metrics, String rule) diff --git a/experiment/src/org/labkey/experiment/SpecialCharacterMetricsMaintenanceTask.java b/experiment/src/org/labkey/experiment/SpecialCharacterMetricsMaintenanceTask.java index 75b576eaf42..7cb5dd8af75 100644 --- a/experiment/src/org/labkey/experiment/SpecialCharacterMetricsMaintenanceTask.java +++ b/experiment/src/org/labkey/experiment/SpecialCharacterMetricsMaintenanceTask.java @@ -35,6 +35,7 @@ import org.labkey.api.exp.api.ExperimentService; import org.labkey.api.exp.api.SampleTypeDomainKind; import org.labkey.api.exp.api.SampleTypeService; +import org.labkey.api.exp.api.SampleTypeTestHelper; import org.labkey.api.gwt.client.model.GWTPropertyDescriptor; import org.labkey.api.gwt.client.model.GWTPropertyValidator; import org.labkey.api.gwt.client.model.PropertyValidatorType; @@ -400,11 +401,7 @@ public void testMissingPhysicalTableSkipped() throws Exception { User user = TestContext.get().getUser(); Container c = JunitUtil.getTestContainer(); - List props = new ArrayList<>(); - props.add(new GWTPropertyDescriptor("Name", PropertyType.STRING.getTypeUri())); - props.add(new GWTPropertyDescriptor("Prop", PropertyType.STRING.getTypeUri())); - ExpSampleType st = SampleTypeService.get().createSampleType(c, user, ST_NAME, null, props, - Collections.emptyList(), -1, -1, -1, -1, null); + ExpSampleType st = SampleTypeTestHelper.create(c, user, ST_NAME, new GWTPropertyDescriptor("Prop", PropertyType.STRING.getTypeUri())); DbScope scope = ExperimentService.get().getSchema().getScope(); String tableName = st.getDomain().getStorageTableName(); diff --git a/experiment/src/org/labkey/experiment/api/DataMapDiffColumnTestCase.java b/experiment/src/org/labkey/experiment/api/DataMapDiffColumnTestCase.java index 78ed611b515..f7ddb962c59 100644 --- a/experiment/src/org/labkey/experiment/api/DataMapDiffColumnTestCase.java +++ b/experiment/src/org/labkey/experiment/api/DataMapDiffColumnTestCase.java @@ -111,7 +111,7 @@ public void testTsvExport() throws Exception Set required = new LinkedHashSet<>(exported); displayColumns.forEach(dc -> dc.addQueryFieldKeys(required)); Collection selectColumns = QueryService.get().getColumns(table, required).values(); - SimpleFilter filter = new SimpleFilter(FieldKey.fromParts("Comment"), comment); + SimpleFilter filter = new SimpleFilter(FieldKey.fromParts(AbstractAuditTypeProvider.COLUMN_NAME_COMMENT), comment); StringBuilder actual = new StringBuilder(); StringBuilder expected = new StringBuilder(); diff --git a/experiment/src/org/labkey/experiment/api/ExpMaterialTableImpl.java b/experiment/src/org/labkey/experiment/api/ExpMaterialTableImpl.java index ffd2afe8957..f2048e4fcfb 100644 --- a/experiment/src/org/labkey/experiment/api/ExpMaterialTableImpl.java +++ b/experiment/src/org/labkey/experiment/api/ExpMaterialTableImpl.java @@ -67,7 +67,6 @@ import org.labkey.api.dataiterator.DataIteratorBuilder; import org.labkey.api.dataiterator.DataIteratorContext; import org.labkey.api.dataiterator.LoggingDataIterator; -import org.labkey.api.dataiterator.MapDataIterator; import org.labkey.api.dataiterator.SimpleTranslator; import org.labkey.api.exp.Lsid; import org.labkey.api.exp.MvColumn; @@ -80,6 +79,7 @@ import org.labkey.api.exp.api.ExperimentUrls; import org.labkey.api.exp.api.NameExpressionOptionService; import org.labkey.api.exp.api.SampleTypeService; +import org.labkey.api.exp.api.SampleTypeTestHelper; import org.labkey.api.exp.api.StorageProvisioner; import org.labkey.api.exp.property.DefaultValidatorKind; import org.labkey.api.exp.property.Domain; @@ -102,7 +102,6 @@ import org.labkey.api.ontology.Unit; import org.labkey.api.qc.SampleStatusService; import org.labkey.api.query.AliasedColumn; -import org.labkey.api.query.BatchValidationException; import org.labkey.api.query.DetailsURL; import org.labkey.api.query.ExprColumn; import org.labkey.api.query.FieldKey; @@ -111,6 +110,7 @@ import org.labkey.api.query.QueryForeignKey; import org.labkey.api.query.QueryService; import org.labkey.api.query.QueryUpdateService; +import org.labkey.api.query.QueryUpdateServiceTestUtil; import org.labkey.api.query.QueryUrls; import org.labkey.api.query.RowIdForeignKey; import org.labkey.api.query.UserSchema; @@ -2688,7 +2688,7 @@ public void testModifiedBoundaryNotSkipped() throws Exception // Drive the targeted update with a watermark equal to the row's own Modified, simulating same-tick capture. updateRows(st, List.of(CaseInsensitiveHashMap.of(RowId.name(), root, "rootProp", "boundary"))); Timestamp rowModified = new SqlSelector(ExperimentServiceImpl.getExpSchema().getScope(), - new SQLFragment("SELECT modified FROM exp.material WHERE rowid = ?").add(root)).getObject(Timestamp.class); + SQLFragment.unsafe("SELECT Modified FROM ").append(ExperimentServiceImpl.get().getTinfoMaterial()).unsafeAppend(" WHERE RowId = ?").add(root)).getObject(Timestamp.class); InvalidationCounters counters = getInvalidateCounters(st.getLSID()); counters.pendingUpdateSince.set(rowModified); counters.update.incrementAndGet(); @@ -3148,7 +3148,7 @@ private ExpSampleType createSampleType(String name) throws Exception private ExpSampleType createSampleType(String name, List indices) throws Exception { List props = new ArrayList<>(); - props.add(new GWTPropertyDescriptor("name", "string")); + props.add(SampleTypeTestHelper.nameProperty()); GWTPropertyDescriptor rootProp = new GWTPropertyDescriptor("rootProp", "string"); rootProp.setDerivationDataScope(ExpSchema.DerivationDataScopeType.ParentOnly.name()); // -> m_sample join props.add(rootProp); @@ -3160,17 +3160,7 @@ private ExpSampleType createSampleType(String name, List indices) thro private ExpMaterialTableImpl getSamplesTable(ExpSampleType st) { - return (ExpMaterialTableImpl) QueryService.get().getUserSchema(_user, _c, SamplesSchema.SCHEMA_NAME).getTable(st.getName()); - } - - private @NotNull QueryUpdateService getUpdateService(ExpSampleType st) - { - TableInfo table = getSamplesTable(st); - QueryUpdateService service = table.getUpdateService(); - if (service == null) - throw new IllegalArgumentException("No QueryUpdateService found for table " + st.getName()); - - return service; + return (ExpMaterialTableImpl) SampleTypeTestHelper.getTable(_c, _user, st); } private List insertRoots(ExpSampleType st, String... names) throws Exception @@ -3191,11 +3181,7 @@ private List insertAliquots(ExpSampleType st, String rootName, int coun private List insert(ExpSampleType st, List> rows) throws Exception { - BatchValidationException errors = new BatchValidationException(); - List> inserted = getUpdateService(st).insertRows(_user, _c, rows, errors, null, null); - if (errors.hasErrors()) - throw errors; - + List> inserted = SampleTypeTestHelper.insert(_c, _user, st, rows); if (inserted == null || inserted.isEmpty()) return Collections.emptyList(); @@ -3207,23 +3193,17 @@ private List insert(ExpSampleType st, List> rows) t private void updateRows(ExpSampleType st, List> rows) throws Exception { - BatchValidationException errors = new BatchValidationException(); - getUpdateService(st).updateRows(_user, _c, rows, null, errors, null, null); - if (errors.hasErrors()) - throw errors; + SampleTypeTestHelper.update(_c, _user, st, rows); } private void deleteRows(ExpSampleType st, List> keys) throws Exception { - getUpdateService(st).deleteRows(_user, _c, keys, null, null); + QueryUpdateServiceTestUtil.delete(getSamplesTable(st), _user, _c, keys); } private void mergeRows(ExpSampleType st, List> rows) throws Exception { - BatchValidationException errors = new BatchValidationException(); - getUpdateService(st).mergeRows(_user, _c, MapDataIterator.of(rows), errors, null, null); - if (errors.hasErrors()) - throw errors; + QueryUpdateServiceTestUtil.merge(getSamplesTable(st), _user, _c, rows); } /** diff --git a/experiment/src/org/labkey/experiment/api/ExperimentServiceImpl.java b/experiment/src/org/labkey/experiment/api/ExperimentServiceImpl.java index 29ab9b55571..065e7cb0e3b 100644 --- a/experiment/src/org/labkey/experiment/api/ExperimentServiceImpl.java +++ b/experiment/src/org/labkey/experiment/api/ExperimentServiceImpl.java @@ -159,6 +159,7 @@ import org.labkey.api.exp.api.ProvenanceService; import org.labkey.api.exp.api.SampleChangeNotify; import org.labkey.api.exp.api.SampleTypeService; +import org.labkey.api.exp.api.SampleTypeTestHelper; import org.labkey.api.exp.api.SimpleRunRecord; import org.labkey.api.exp.list.ListService; import org.labkey.api.exp.property.Domain; @@ -10886,16 +10887,8 @@ public void testEditLineagePermission() throws Exception final User admin = TestContext.get().getUser(); final Container c = JunitUtil.getTestContainer(); - List props = new ArrayList<>(); - props.add(new GWTPropertyDescriptor("name", "string")); - ExpSampleType st = SampleTypeService.get().createSampleType(c, admin, "LineageGuardSamples", null, props, Collections.emptyList(), -1, -1, -1, -1, null); - - UserSchema schema = QueryService.get().getUserSchema(admin, c, SchemaKey.fromParts("Samples")); - QueryUpdateService svc = schema.getTable("LineageGuardSamples").getUpdateService(); - BatchValidationException errors = new BatchValidationException(); - svc.insertRows(admin, c, List.of(CaseInsensitiveHashMap.of("name", "sample")), errors, null, null); - if (errors.hasErrors()) - throw errors; + ExpSampleType st = SampleTypeTestHelper.create(c, admin, "LineageGuardSamples"); + SampleTypeTestHelper.insert(c, admin, st, List.of(CaseInsensitiveHashMap.of("name", "sample"))); ExpMaterial sample = st.getSample(c, "sample"); String lsid = sample.getLSID(); @@ -10939,14 +10932,12 @@ public void testMaterialPropertyPermissions() throws Exception GWTPropertyDescriptor score = new GWTPropertyDescriptor("score", "int"); score.setMvEnabled(true); - List props = new ArrayList<>(); - props.add(new GWTPropertyDescriptor("name", "string")); - props.add(new GWTPropertyDescriptor("color", "string")); - props.add(new GWTPropertyDescriptor("count", "int")); - props.add(new GWTPropertyDescriptor("collected", "dateTime")); - props.add(new GWTPropertyDescriptor("shipped", "boolean")); - props.add(score); - ExpSampleType st = SampleTypeService.get().createSampleType(c, admin, "PropertyGuardSamples", null, props, Collections.emptyList(), -1, -1, -1, -1, null); + ExpSampleType st = SampleTypeTestHelper.create(c, admin, "PropertyGuardSamples", + new GWTPropertyDescriptor("color", "string"), + new GWTPropertyDescriptor("count", "int"), + new GWTPropertyDescriptor("collected", "dateTime"), + new GWTPropertyDescriptor("shipped", "boolean"), + score); DomainProperty color = st.getDomain().getPropertyByName("color"); // Author has Insert but not Update diff --git a/experiment/src/org/labkey/experiment/api/SampleProvidedAmountAuditTestCase.java b/experiment/src/org/labkey/experiment/api/SampleProvidedAmountAuditTestCase.java index 37d08069c79..5e4010bc351 100644 --- a/experiment/src/org/labkey/experiment/api/SampleProvidedAmountAuditTestCase.java +++ b/experiment/src/org/labkey/experiment/api/SampleProvidedAmountAuditTestCase.java @@ -15,7 +15,6 @@ */ package org.labkey.experiment.api; -import org.jetbrains.annotations.NotNull; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; @@ -29,15 +28,12 @@ import org.labkey.api.data.Sort; import org.labkey.api.data.TableInfo; import org.labkey.api.data.TableSelector; -import org.labkey.api.dataiterator.MapDataIterator; import org.labkey.api.exp.api.ExpSampleType; import org.labkey.api.exp.api.SampleTypeService; -import org.labkey.api.exp.query.SamplesSchema; +import org.labkey.api.exp.api.SampleTypeTestHelper; import org.labkey.api.gwt.client.model.GWTPropertyDescriptor; -import org.labkey.api.query.BatchValidationException; import org.labkey.api.query.FieldKey; -import org.labkey.api.query.QueryService; -import org.labkey.api.query.QueryUpdateService; +import org.labkey.api.query.QueryUpdateServiceTestUtil; import org.labkey.api.security.User; import org.labkey.api.util.JunitUtil; import org.labkey.api.util.PageFlowUtil; @@ -49,9 +45,13 @@ import java.util.List; import java.util.Map; +import static org.labkey.api.audit.AbstractAuditTypeProvider.COLUMN_NAME_ROW_ID; import static org.labkey.api.audit.AuditHandler.USER_PROVIDED_DATA_PREFIX; import static org.labkey.api.exp.query.ExpMaterialTable.Column.StoredAmount; import static org.labkey.api.exp.query.ExpMaterialTable.Column.Units; +import static org.labkey.experiment.samples.SampleTimelineAuditProvider.METADATA_COLUMN_NAME; +import static org.labkey.experiment.samples.SampleTimelineAuditProvider.SAMPLE_NAME_COLUMN_NAME; +import static org.labkey.experiment.samples.SampleTimelineAuditProvider.SAMPLE_TYPE_ID_COLUMN_NAME; /** * GH Issue 1640: DetailedAuditLogDataIterator flushes audit events every 1,001 rows, and each sample's @@ -91,10 +91,7 @@ public void testInsertKeepsProvidedAmountWithRow() throws Exception expected.put("S-" + i, i); } - BatchValidationException errors = new BatchValidationException(); - getUpdateService(st).insertRows(_user, _c, rows, errors, null, null); - if (errors.hasErrors()) - throw errors; + SampleTypeTestHelper.insert(_c, _user, st, rows); assertProvidedAmounts(st, expected); } @@ -108,10 +105,7 @@ public void testMergeKeepsProvidedAmountWithRow() throws Exception for (int i = 1; i <= existingCount; i++) existing.add(sampleRow("S-" + i, i)); - BatchValidationException errors = new BatchValidationException(); - getUpdateService(st).insertRows(_user, _c, existing, errors, null, null); - if (errors.hasErrors()) - throw errors; + SampleTypeTestHelper.insert(_c, _user, st, existing); // The first half updates existing samples and the second half inserts new ones, all in one merge Map expected = new HashMap<>(); @@ -123,9 +117,7 @@ public void testMergeKeepsProvidedAmountWithRow() throws Exception expected.put("S-" + i, amount); } - getUpdateService(st).mergeRows(_user, _c, MapDataIterator.of(rows), errors, null, null); - if (errors.hasErrors()) - throw errors; + QueryUpdateServiceTestUtil.merge(SampleTypeTestHelper.getTable(_c, _user, st), _user, _c, rows); assertProvidedAmounts(st, expected); } @@ -140,11 +132,11 @@ private void assertProvidedAmounts(ExpSampleType st, Map expect { AbstractAuditTypeProvider provider = (AbstractAuditTypeProvider) AuditLogService.get().getAuditProvider(SampleTimelineAuditEvent.EVENT_TYPE); TableInfo table = provider.createStorageTableInfo(); - SimpleFilter filter = new SimpleFilter(FieldKey.fromParts("SampleTypeId"), st.getRowId()); + SimpleFilter filter = new SimpleFilter(FieldKey.fromParts(SAMPLE_TYPE_ID_COLUMN_NAME), st.getRowId()); Map latestMetadata = new HashMap<>(); - new TableSelector(table, PageFlowUtil.set("RowId", "SampleName", "Metadata"), filter, new Sort("RowId")) - .forEach(rs -> latestMetadata.put(rs.getString("SampleName"), rs.getString("Metadata"))); + new TableSelector(table, PageFlowUtil.set(COLUMN_NAME_ROW_ID, SAMPLE_NAME_COLUMN_NAME, METADATA_COLUMN_NAME), filter, new Sort(COLUMN_NAME_ROW_ID)) + .forEach(rs -> latestMetadata.put(rs.getString(SAMPLE_NAME_COLUMN_NAME), rs.getString(METADATA_COLUMN_NAME))); assertEquals("Timeline event count", expected.size(), latestMetadata.size()); for (Map.Entry entry : expected.entrySet()) @@ -164,17 +156,7 @@ private void assertProvidedAmounts(ExpSampleType st, Map expect private ExpSampleType createSampleType(String name) throws Exception { - List props = List.of(new GWTPropertyDescriptor("name", "string")); + List props = List.of(SampleTypeTestHelper.nameProperty()); return SampleTypeService.get().createSampleType(_c, _user, name, null, props, Collections.emptyList(), -1, -1, -1, -1, null, null, null, null, null, "mL"); } - - private @NotNull QueryUpdateService getUpdateService(ExpSampleType st) - { - TableInfo table = QueryService.get().getUserSchema(_user, _c, SamplesSchema.SCHEMA_NAME).getTable(st.getName()); - QueryUpdateService service = table == null ? null : table.getUpdateService(); - if (service == null) - throw new IllegalArgumentException("No QueryUpdateService found for table " + st.getName()); - - return service; - } } diff --git a/experiment/src/org/labkey/experiment/api/SampleTypeFilterSuggestionProvider.java b/experiment/src/org/labkey/experiment/api/SampleTypeFilterSuggestionProvider.java index e11ec801fbf..2f9107089eb 100644 --- a/experiment/src/org/labkey/experiment/api/SampleTypeFilterSuggestionProvider.java +++ b/experiment/src/org/labkey/experiment/api/SampleTypeFilterSuggestionProvider.java @@ -28,14 +28,14 @@ import org.labkey.api.data.UnloggedTableGeneration; import org.labkey.api.exp.api.ExpSampleType; import org.labkey.api.exp.api.SampleTypeService; +import org.labkey.api.exp.api.SampleTypeTestHelper; import org.labkey.api.exp.query.ExpMaterialTable; import org.labkey.api.exp.query.ExpSchema; -import org.labkey.api.exp.query.SamplesSchema; import org.labkey.api.gwt.client.model.GWTPropertyDescriptor; -import org.labkey.api.query.BatchValidationException; import org.labkey.api.query.QueryService; -import org.labkey.api.query.QueryUpdateService; +import org.labkey.api.query.QueryUpdateServiceTestUtil; import org.labkey.api.query.suggestions.FilterSuggestionContext; +import org.labkey.api.query.suggestions.FilterSuggestionTestContext; import org.labkey.api.query.suggestions.FilterSuggestionProvider; import org.labkey.api.query.suggestions.SuggestionColumn; import org.labkey.api.security.User; @@ -115,16 +115,11 @@ public void testDataChangeToken() throws Exception Set seen = new HashSet<>(); assertNewToken(seen, st, "initial"); - BatchValidationException errors = new BatchValidationException(); - List> inserted = getUpdateService(st).insertRows(_user, _c, List.of(CaseInsensitiveHashMap.of("name", "S-1", "prop", "a")), errors, null, null); - if (errors.hasErrors()) - throw errors; + List> inserted = SampleTypeTestHelper.insert(_c, _user, st, List.of(CaseInsensitiveHashMap.of("name", "S-1", "prop", "a"))); assertNewToken(seen, st, "insert"); Object rowId = Objects.requireNonNull(inserted).getFirst().get(ROW_ID); - getUpdateService(st).updateRows(_user, _c, List.of(CaseInsensitiveHashMap.of(ROW_ID, rowId, "prop", "b")), null, errors, null, null); - if (errors.hasErrors()) - throw errors; + SampleTypeTestHelper.update(_c, _user, st, List.of(CaseInsensitiveHashMap.of(ROW_ID, rowId, "prop", "b"))); assertNewToken(seen, st, "update"); // Updates without a watermark and schema changes drop the materialized view without bumping the data counters @@ -133,7 +128,7 @@ public void testDataChangeToken() throws Exception SampleTypeServiceImpl.get().refreshSampleTypeMaterializedView(st, SampleTypeServiceImpl.SampleChangeType.schema); assertNewToken(seen, st, "schema change"); - getUpdateService(st).deleteRows(_user, _c, List.of(CaseInsensitiveHashMap.of(ROW_ID, rowId)), null, null); + QueryUpdateServiceTestUtil.delete(getSamplesTable(st), _user, _c, List.of(CaseInsensitiveHashMap.of(ROW_ID, rowId))); assertNewToken(seen, st, "delete"); // Simulates the cache-clear listener; the replacement counters restart from the clock @@ -181,48 +176,18 @@ private static SuggestionColumn nameColumn() private static ExpSampleType createSampleType(String name, @Nullable String nameExpression, @Nullable String aliquotNameExpression) throws Exception { - List props = List.of(new GWTPropertyDescriptor("name", "string"), new GWTPropertyDescriptor("prop", "string")); + List props = List.of(SampleTypeTestHelper.nameProperty(), new GWTPropertyDescriptor("prop", "string")); return SampleTypeService.get().createSampleType(_c, _user, name, null, props, List.of(), -1, -1, -1, -1, nameExpression, aliquotNameExpression, null, null, null, null); } private static TableInfo getSamplesTable(ExpSampleType st) { - return Objects.requireNonNull(QueryService.get().getUserSchema(_user, _c, SamplesSchema.SCHEMA_NAME).getTable(st.getName())); - } - - private static QueryUpdateService getUpdateService(ExpSampleType st) - { - return Objects.requireNonNull(getSamplesTable(st).getUpdateService()); + return SampleTypeTestHelper.getTable(_c, _user, st); } private static FilterSuggestionContext context(TableInfo table) { - return new FilterSuggestionContext() - { - @Override - public @NotNull TableInfo getTable() - { - return table; - } - - @Override - public @NotNull ContainerFilter getContainerFilter() - { - return ContainerFilter.current(_c, _user); - } - - @Override - public @NotNull Container getContainer() - { - return _c; - } - - @Override - public @NotNull User getUser() - { - return _user; - } - }; + return new FilterSuggestionTestContext(table, ContainerFilter.current(_c, _user), _c, _user); } } } diff --git a/experiment/src/org/labkey/experiment/api/SampleTypeServiceImpl.java b/experiment/src/org/labkey/experiment/api/SampleTypeServiceImpl.java index 3d77ac3aea2..3b149558850 100644 --- a/experiment/src/org/labkey/experiment/api/SampleTypeServiceImpl.java +++ b/experiment/src/org/labkey/experiment/api/SampleTypeServiceImpl.java @@ -85,6 +85,7 @@ import org.labkey.api.exp.api.SampleChangeNotify; import org.labkey.api.exp.api.SampleTypeDomainKindProperties; import org.labkey.api.exp.api.SampleTypeService; +import org.labkey.api.exp.api.SampleTypeTestHelper; import org.labkey.api.exp.property.Domain; import org.labkey.api.exp.property.DomainKind; import org.labkey.api.exp.property.DomainProperty; @@ -2597,10 +2598,10 @@ public void testSampleTypeLookupIsContainerScoped() throws Exception projB = ContainerManager.createContainer(root, "SampleScopeB" + suffix, user); Container subA = ContainerManager.createContainer(projA, "sub", user); - ExpSampleType stLocal = svc.createSampleType(subA, user, "ScopeLocal", null, nameProp(), Collections.emptyList(), -1, -1, -1, -1, null, null); - ExpSampleType stProject = svc.createSampleType(projA, user, "ScopeProject", null, nameProp(), Collections.emptyList(), -1, -1, -1, -1, null, null); - stShared = svc.createSampleType(shared, user, "ScopeShared" + suffix, null, nameProp(), Collections.emptyList(), -1, -1, -1, -1, null, null); - ExpSampleType stForeign = svc.createSampleType(projB, user, "ScopeForeign", null, nameProp(), Collections.emptyList(), -1, -1, -1, -1, null, null); + ExpSampleType stLocal = SampleTypeTestHelper.create(subA, user, "ScopeLocal"); + ExpSampleType stProject = SampleTypeTestHelper.create(projA, user, "ScopeProject"); + stShared = SampleTypeTestHelper.create(shared, user, "ScopeShared" + suffix); + ExpSampleType stForeign = SampleTypeTestHelper.create(projB, user, "ScopeForeign"); // In scope from subA (current, project, Shared) -- resolves by rowId and by LSID. assertNotNull("Local sample type should resolve by rowId", svc.getSampleType(subA, stLocal.getRowId(), true)); @@ -2628,12 +2629,5 @@ public void testSampleTypeLookupIsContainerScoped() throws Exception ContainerManager.deleteAll(projB, user); } } - - private List nameProp() - { - List props = new ArrayList<>(); - props.add(new GWTPropertyDescriptor("name", "string")); - return props; - } } } diff --git a/list/src/org/labkey/list/model/ListQueryUpdateService.java b/list/src/org/labkey/list/model/ListQueryUpdateService.java index e6df43da2f4..1d19b03e01e 100644 --- a/list/src/org/labkey/list/model/ListQueryUpdateService.java +++ b/list/src/org/labkey/list/model/ListQueryUpdateService.java @@ -74,6 +74,7 @@ import org.labkey.api.query.QueryService; import org.labkey.api.query.QueryUpdateService; import org.labkey.api.query.QueryUpdateServiceException; +import org.labkey.api.query.QueryUpdateServiceTestUtil; import org.labkey.api.query.UserSchema; import org.labkey.api.query.ValidationError; import org.labkey.api.query.ValidationException; @@ -108,6 +109,7 @@ import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; @@ -1311,7 +1313,7 @@ static Map keyMap(Object key) static int auditCount(ListDefinition list, Container c, User user, String comment) { SimpleFilter filter = new SimpleFilter(FieldKey.fromParts(ListAuditProvider.COLUMN_NAME_LIST_ID), list.getListId()); - filter.addCondition(FieldKey.fromParts("Comment"), comment); + filter.addCondition(FieldKey.fromParts(AbstractAuditTypeProvider.COLUMN_NAME_COMMENT), comment); return AuditLogService.get().getAuditEvents(c, user, ListManager.LIST_AUDIT_EVENT, filter, null).size(); } @@ -1693,10 +1695,7 @@ private void updateFromProject(ContainerFilter.Type cfType, List keys) t List> rows = keys.stream().map(key -> (Map) CaseInsensitiveHashMap.of(KEY_NAME, key, VALUE_FIELD, UPDATED)).toList(); try (DbScope.Transaction tx = table.getSchema().getScope().ensureTransaction()) { - BatchValidationException errors = new BatchValidationException(); - table.getUpdateService().updateRows(_user, _project, rows, null, errors, null, null); - if (errors.hasErrors()) - throw errors; + QueryUpdateServiceTestUtil.update(table, _user, _project, rows); tx.commit(); } } @@ -1707,115 +1706,64 @@ private interface Mutation } /** The project row comes first, so a check that ran per batch or per row would already have changed it */ - private void assertRejected(Container folder, Mutation mutation) throws Exception + private void assertRejected(String label, Container folder, Mutation mutation) throws Exception { Object projectKey = insertRow(_project); Object otherKey = insertRow(folder); - try - { - mutation.apply(List.of(projectKey, otherKey)); - fail("expected the change to a row in " + folder.getName() + " to be rejected"); - } - catch (UnauthorizedException expected) - { - // expected - } + assertThrows(label + " should be rejected", UnauthorizedException.class, () -> mutation.apply(List.of(projectKey, otherKey))); for (Object key : List.of(projectKey, otherKey)) { Map row = selectRow(key); - assertNotNull("row " + key + " should remain", row); - assertNotEquals("row " + key + " should be unchanged", UPDATED, row.get(VALUE_FIELD)); + assertNotNull(label + ": row " + key + " should remain", row); + assertNotEquals(label + ": row " + key + " should be unchanged", UPDATED, row.get(VALUE_FIELD)); } } - @Test - public void deleteRejectsRowsInFolderWithoutDeletePermission() throws Exception - { - assertRejected(_readOnlyFolder, keys -> deleteFromProject(WIDE, keys, null)); - } - - @Test - public void deleteRejectsRowsInSubfolderWithDeletePermission() throws Exception - { - assertRejected(_editableFolder, keys -> deleteFromProject(WIDE, keys, null)); - } + private enum Op { DELETE, TRIGGER_DELETE, UPDATE } + /** Each operation, against a read-only folder, an editable subfolder, and rows the narrow filter hides */ @Test - public void deleteRejectsRowsHiddenByContainerFilter() throws Exception + public void rejectsChangesToRowsOutsideTheProject() throws Exception { - assertRejected(_editableFolder, keys -> deleteFromProject(NARROW, keys, null)); - } + record Case(Op op, Container folder, ContainerFilter.Type cf) {} + List cases = new ArrayList<>(); + for (Op op : Op.values()) + { + cases.add(new Case(op, _readOnlyFolder, WIDE)); + cases.add(new Case(op, _editableFolder, WIDE)); + cases.add(new Case(op, _editableFolder, NARROW)); + } + cases.add(new Case(Op.DELETE, _unreadableFolder, WIDE)); - @Test - public void deleteRejectsRowsInUnreadableFolder() throws Exception - { - assertRejected(_unreadableFolder, keys -> deleteFromProject(WIDE, keys, null)); + for (Case c : cases) + { + String label = c.op() + " " + c.cf() + " in " + c.folder().getName(); + DeleteCountingTrigger trigger = c.op() == Op.TRIGGER_DELETE ? new DeleteCountingTrigger() : null; + assertRejected(label, c.folder(), keys -> { + if (c.op() == Op.UPDATE) + updateFromProject(c.cf(), keys); + else + deleteFromProject(c.cf(), keys, trigger); + }); + if (trigger != null) + assertEquals(label + ": the check should run before any row reaches the trigger", 0, trigger._deletes.get()); + } } + /** Both delete paths; the per-row path also hands the row to the trigger */ @Test public void deletesRowsInWorkbook() throws Exception { - Object key = insertRow(_workbook); - deleteFromProject(WIDE, List.of(key), null); - assertNull("the workbook row should be gone", selectRow(key)); - } - - @Test - public void triggerPathRejectsRowsInFolderWithoutDeletePermission() throws Exception - { - DeleteCountingTrigger trigger = new DeleteCountingTrigger(); - - assertRejected(_readOnlyFolder, keys -> deleteFromProject(WIDE, keys, trigger)); - assertEquals("the check should run before any row reaches the trigger", 0, trigger._deletes.get()); - } - - @Test - public void triggerPathRejectsRowsInSubfolderWithDeletePermission() throws Exception - { - DeleteCountingTrigger trigger = new DeleteCountingTrigger(); - - assertRejected(_editableFolder, keys -> deleteFromProject(WIDE, keys, trigger)); - assertEquals("the check should run before any row reaches the trigger", 0, trigger._deletes.get()); - } - - @Test - public void triggerPathRejectsRowsHiddenByContainerFilter() throws Exception - { - DeleteCountingTrigger trigger = new DeleteCountingTrigger(); - - assertRejected(_editableFolder, keys -> deleteFromProject(NARROW, keys, trigger)); - assertEquals("the check should run before any row reaches the trigger", 0, trigger._deletes.get()); - } - - @Test - public void triggerPathDeletesRowsInWorkbook() throws Exception - { - DeleteCountingTrigger trigger = new DeleteCountingTrigger(); - Object key = insertRow(_workbook); - - deleteFromProject(WIDE, List.of(key), trigger); - assertNull("the workbook row should be gone", selectRow(key)); - assertEquals("expected the per-row path to hand the row to the trigger", 1, trigger._deletes.get()); - } - - @Test - public void updateRejectsRowsInFolderWithoutUpdatePermission() throws Exception - { - assertRejected(_readOnlyFolder, keys -> updateFromProject(WIDE, keys)); - } - - @Test - public void updateRejectsRowsInSubfolderWithUpdatePermission() throws Exception - { - assertRejected(_editableFolder, keys -> updateFromProject(WIDE, keys)); - } - - @Test - public void updateRejectsRowsHiddenByContainerFilter() throws Exception - { - assertRejected(_editableFolder, keys -> updateFromProject(NARROW, keys)); + for (DeleteCountingTrigger trigger : Arrays.asList(null, new DeleteCountingTrigger())) + { + Object key = insertRow(_workbook); + deleteFromProject(WIDE, List.of(key), trigger); + assertNull("the workbook row should be gone", selectRow(key)); + if (trigger != null) + assertEquals("expected the per-row path to hand the row to the trigger", 1, trigger._deletes.get()); + } } @Test diff --git a/pipeline/src/org/labkey/pipeline/PipelineController.java b/pipeline/src/org/labkey/pipeline/PipelineController.java index 35ac20d7add..26632ad2303 100644 --- a/pipeline/src/org/labkey/pipeline/PipelineController.java +++ b/pipeline/src/org/labkey/pipeline/PipelineController.java @@ -1781,8 +1781,8 @@ public static class ContainerScopingTestCase extends AbstractContainerScopingTes public void testSavePipelineTriggerContainerScoping() throws Exception { User admin = getAdmin(); - Container folderA = createContainer("A"); - Container folderB = createContainer("B"); + Container folderA = getSharedContainer("A"); + Container folderB = getSharedContainer("B"); // A pipeline trigger configuration that lives in folder B (Type/PipelineId are NOT NULL columns; their // values need not be valid registered names for the container guard to apply). @@ -1828,7 +1828,7 @@ public void testSavePipelineTriggerContainerScoping() throws Exception public void testTriggerRunAsUser() throws Exception { User siteAdmin = getAdmin(); - Container folder = createContainer("RunAs"); + Container folder = getSharedContainer("A"); Container project = folder.getProject(); User reader = createUserInRole(project, ReaderRole.class); User folderAdmin = createUserInRole(folder, FolderAdminRole.class); @@ -1895,7 +1895,7 @@ private Integer saveTrigger(Container c, User user, @Nullable Integer rowId, Use @Test public void testFolderAdminCanManageTriggerWithoutParameterFunction() throws Exception { - Container c = createContainer("NoFunction"); + Container c = getSharedContainer("A"); User folderAdmin = createUserInRole(c, FolderAdminRole.class); assertFalse(folderAdmin.isTrustedAnalyst()); @@ -1913,7 +1913,7 @@ public void testFolderAdminCanManageTriggerWithoutParameterFunction() throws Exc @Test public void testFolderAdminCannotInsertParameterFunction() throws Exception { - Container c = createContainer("InsertFunction"); + Container c = getSharedContainer("A"); User folderAdmin = createUserInRole(c, FolderAdminRole.class); List configurations = List.of( @@ -1940,7 +1940,7 @@ public void testFolderAdminCannotInsertParameterFunction() throws Exception @Test public void testFolderAdminCannotChangeParameterFunction() throws Exception { - Container c = createContainer("ChangeFunction"); + Container c = getSharedContainer("A"); User folderAdmin = createUserInRole(c, FolderAdminRole.class); int rowId = seedTrigger(c, FUNCTION); @@ -1975,7 +1975,7 @@ public void testFolderAdminCannotChangeParameterFunction() throws Exception @Test public void testFolderAdminCanEditTriggerWithUnchangedParameterFunction() throws Exception { - Container c = createContainer("UnchangedFunction"); + Container c = getSharedContainer("A"); User folderAdmin = createUserInRole(c, FolderAdminRole.class); int rowId = seedTrigger(c, FUNCTION); @@ -1997,8 +1997,8 @@ public void testFolderAdminCanEditTriggerWithUnchangedParameterFunction() throws @Test public void testUpdateRowsContainerScoping() throws Exception { - Container folderA = createContainer("UpdateA"); - Container folderB = createContainer("UpdateB"); + Container folderA = getSharedContainer("A"); + Container folderB = getSharedContainer("B"); User adminA = createUserInRole(folderA, FolderAdminRole.class); int rowId = seedTrigger(folderB, null); String name = (String) storedRow(rowId).get("Name"); @@ -2027,9 +2027,9 @@ public void testUpdateRowsContainerScoping() throws Exception @Test public void testTrustedAnalystCanManageParameterFunction() throws Exception { - Container c = createContainer("TrustedFunction"); + Container c = getSharedContainer("A"); User developer = createUserInRole(c, FolderAdminRole.class); - grantRole(developer, ContainerManager.getRoot(), PlatformDeveloperRole.class); + grantRootRole(developer, PlatformDeveloperRole.class); assertTrue(developer.isTrustedAnalyst()); Map row = triggerRow(configJson(FUNCTION)); @@ -2052,10 +2052,10 @@ public void testTrustedAnalystCanManageParameterFunction() throws Exception @Test public void testInvalidJsonRejectedForAllUsers() throws Exception { - Container c = createContainer("InvalidJson"); + Container c = getSharedContainer("A"); User folderAdmin = createUserInRole(c, FolderAdminRole.class); User developer = createUserInRole(c, FolderAdminRole.class); - grantRole(developer, ContainerManager.getRoot(), PlatformDeveloperRole.class); + grantRootRole(developer, PlatformDeveloperRole.class); for (User user : List.of(folderAdmin, developer)) { @@ -2079,7 +2079,7 @@ public void testInvalidJsonRejectedForAllUsers() throws Exception @Test public void testFolderAdminCanRepairInvalidConfiguration() throws Exception { - Container c = createContainer("RepairJson"); + Container c = getSharedContainer("A"); User folderAdmin = createUserInRole(c, FolderAdminRole.class); int rowId = seedTrigger(c, null); Table.update(getAdmin(), triggerTable(), new CaseInsensitiveHashMap<>(Map.of("Configuration", INVALID_JSON)), rowId); @@ -2099,9 +2099,9 @@ public void testFolderAdminCanRepairInvalidConfiguration() throws Exception @Test public void testLoadRowsRejectedInFavorOfInsertRows() throws Exception { - Container c = createContainer("LoadRows"); + Container c = getSharedContainer("A"); User developer = createUserInRole(c, FolderAdminRole.class); - grantRole(developer, ContainerManager.getRoot(), PlatformDeveloperRole.class); + grantRootRole(developer, PlatformDeveloperRole.class); Map row = triggerRow(configJson(null)); // IMPORT backs the import action; MERGE backs ETL targets diff --git a/query/src/org/labkey/query/QueryServiceImpl.java b/query/src/org/labkey/query/QueryServiceImpl.java index 484493adc32..409466f9b1d 100644 --- a/query/src/org/labkey/query/QueryServiceImpl.java +++ b/query/src/org/labkey/query/QueryServiceImpl.java @@ -3550,7 +3550,7 @@ public void testSelect() throws SQLException public void testInClauseInnerJoin() { QueryService qs = QueryService.get(); - TableInfo users = DbSchema.get("core", DbSchemaType.Module).getTable("users"); + TableInfo users = CoreSchema.getInstance().getTableInfoUsers(); assertNotNull(users); List cols = List.of(users.getColumn("userid"), users.getColumn("displayname")); @@ -3648,15 +3648,7 @@ public void testParameters() throws SQLException " ti TINYINT DEFAULT NULL," + " s VARCHAR DEFAULT NULL)\n" + "SELECT bint, bit, char, dec, d, i, text, num, real, sint, ts, ti, s FROM core.Users WHERE 0=1"; - QueryDef qd = new QueryDef(); - qd.setSchema("core"); - qd.setName("junit" + GUID.makeHash()); - qd.setContainer(JunitUtil.getTestContainer().getId()); - qd.setSql(sql); - QueryDefinition qdef = new CustomQueryDefinitionImpl(TestContext.get().getUser(),JunitUtil.getTestContainer(),qd); - List errors = new ArrayList<>(); - TableInfo t = qdef.getTable(errors, false); - assertTrue(errors.isEmpty()); + TableInfo t = coreQueryTable(sql); assertEquals(JdbcType.BIGINT, t.getColumn("bint").getJdbcType()); assertEquals(JdbcType.BOOLEAN, t.getColumn("bit").getJdbcType()); assertEquals(JdbcType.CHAR, t.getColumn("char").getJdbcType()); @@ -3874,16 +3866,8 @@ public void testRightAndIsnumeric() throws SQLException " CASE WHEN isnumeric('abc') = 1 THEN 1 ELSE 0 END AS n6 " + "FROM core.Containers"; - QueryDef qd = new QueryDef(); - qd.setSchema("core"); - qd.setName("junit" + GUID.makeHash()); - qd.setContainer(JunitUtil.getTestContainer().getId()); - qd.setSql(sql); - QueryDefinition qdef = new CustomQueryDefinitionImpl(TestContext.get().getUser(), JunitUtil.getTestContainer(), qd); - List errors = new ArrayList<>(); - TableInfo t = qdef.getTable(errors, false); - String dialect = t == null ? "?" : t.getSqlDialect().getProductName(); - assertTrue("Query parse errors on " + dialect + ": " + errors, errors.isEmpty()); + TableInfo t = coreQueryTable(sql); + String dialect = t.getSqlDialect().getProductName(); try (Results results = new TableSelector(t).getResults()) { @@ -3899,6 +3883,21 @@ public void testRightAndIsnumeric() throws SQLException } } + /** Parses sql as a custom query over the core schema in the junit container, failing on any parse error */ + private static TableInfo coreQueryTable(String sql) + { + QueryDef qd = new QueryDef(); + qd.setSchema("core"); + qd.setName("junit" + GUID.makeHash()); + qd.setContainer(JunitUtil.getTestContainer().getId()); + qd.setSql(sql); + List errors = new ArrayList<>(); + TableInfo t = new CustomQueryDefinitionImpl(TestContext.get().getUser(), JunitUtil.getTestContainer(), qd).getTable(errors, false); + assertTrue("Query parse errors on " + CoreSchema.getInstance().getSqlDialect().getProductName() + ": " + errors, errors.isEmpty()); + assertNotNull(t); + return t; + } + // 2026 (Jan 1 = Thursday) makes the two rules agree except on Sundays; 2027 (Jan 1 = Friday) puts them one // apart every day and starts in the prior ISO year. A mid-year sample in a Mon-Thu year passes either way. private static final String[] WEEK_DATES = { @@ -3910,15 +3909,10 @@ public void testRightAndIsnumeric() throws SQLException }; @Test - public void testWeekUs() throws SQLException + public void testWeeks() throws SQLException { // Weeks start Sunday and week 1 holds Jan 1, matching SQL Server's DATEPART(week, x) under DATEFIRST 7. assertWeeks("weekus", 1, 1, 2, 1, 29); - } - - @Test - public void testWeekIso() throws SQLException - { // ISO 8601: weeks start Monday and week 1 holds the year's first Thursday, so 2027-01-01 lands in 2026's week 53. assertWeeks("weekiso", 1, 1, 1, 53, 28); } @@ -3931,16 +3925,8 @@ private void assertWeeks(String method, int... expected) throws SQLException .append("(CAST('").append(WEEK_DATES[i]).append(" 00:00:00' AS TIMESTAMP)) AS w").append(i + 1); sql.append(" FROM core.Containers"); - QueryDef qd = new QueryDef(); - qd.setSchema("core"); - qd.setName("junit" + GUID.makeHash()); - qd.setContainer(JunitUtil.getTestContainer().getId()); - qd.setSql(sql.toString()); - QueryDefinition qdef = new CustomQueryDefinitionImpl(TestContext.get().getUser(), JunitUtil.getTestContainer(), qd); - List errors = new ArrayList<>(); - TableInfo t = qdef.getTable(errors, false); - String dialect = t == null ? "?" : t.getSqlDialect().getProductName(); - assertTrue("Query parse errors on " + dialect + ": " + errors, errors.isEmpty()); + TableInfo t = coreQueryTable(sql.toString()); + String dialect = t.getSqlDialect().getProductName(); try (Results results = new TableSelector(t).getResults()) { diff --git a/query/src/org/labkey/query/sql/Method.java b/query/src/org/labkey/query/sql/Method.java index d14e5fd5bc4..1d1a493cbc4 100644 --- a/query/src/org/labkey/query/sql/Method.java +++ b/query/src/org/labkey/query/sql/Method.java @@ -2216,9 +2216,8 @@ private static String selectWithoutParameters(SQLFragment expr) @Test public void testJsonOperators() { + JunitUtil.assumePostgres(); SqlDialect d = CoreSchema.getInstance().getSqlDialect(); - if (!d.isPostgreSQL()) - return; record Case(String json, String operator, String operand, String expected) {} List cases = List.of( diff --git a/query/src/org/labkey/query/suggestions/ColumnFactsCache.java b/query/src/org/labkey/query/suggestions/ColumnFactsCache.java index 9b4508070f5..28db6a5827f 100644 --- a/query/src/org/labkey/query/suggestions/ColumnFactsCache.java +++ b/query/src/org/labkey/query/suggestions/ColumnFactsCache.java @@ -42,14 +42,15 @@ import org.labkey.api.data.dialect.SqlDialect; import org.labkey.api.exp.PropertyType; import org.labkey.api.exp.api.ExpSampleType; -import org.labkey.api.exp.api.SampleTypeService; +import org.labkey.api.exp.api.SampleTypeTestHelper; import org.labkey.api.exp.query.SamplesSchema; import org.labkey.api.gwt.client.model.GWTPropertyDescriptor; -import org.labkey.api.query.BatchValidationException; import org.labkey.api.query.FieldKey; import org.labkey.api.query.QueryService; +import org.labkey.api.query.QueryUpdateServiceTestUtil; import org.labkey.api.query.UserSchema; import org.labkey.api.query.suggestions.FilterSuggestionContext; +import org.labkey.api.query.suggestions.FilterSuggestionTestContext; import org.labkey.api.query.suggestions.SuggestionColumn; import org.labkey.api.security.User; import org.labkey.api.security.UserManager; @@ -760,8 +761,7 @@ public static void setup() throws Exception _c = JunitUtil.getTestContainer(); _user = TestContext.get().getUser(); - List props = List.of( - new GWTPropertyDescriptor("name", PropertyType.STRING.getTypeUri()), + ExpSampleType sampleType = SampleTypeTestHelper.create(_c, _user, SAMPLE_TYPE, new GWTPropertyDescriptor("color", PropertyType.STRING.getTypeUri()), new GWTPropertyDescriptor("thawCount", PropertyType.INTEGER.getTypeUri()), new GWTPropertyDescriptor("concentration", PropertyType.DOUBLE.getTypeUri()), @@ -769,7 +769,6 @@ public static void setup() throws Exception new GWTPropertyDescriptor("subject", PropertyType.STRING.getTypeUri()), calculated("viewer", PropertyType.STRING, "USERNAME()") ); - ExpSampleType sampleType = SampleTypeService.get().createSampleType(_c, _user, SAMPLE_TYPE, null, props, List.of(), -1, -1, -1, -1, null, null, null, null, null, null); List colors = List.of("red", "green", "blue"); List> rows = new ArrayList<>(); @@ -784,10 +783,7 @@ public static void setup() throws Exception row.put("subject", String.format("SUBJ-%06d", i)); rows.add(row); } - BatchValidationException errors = new BatchValidationException(); - Objects.requireNonNull(getTable(sampleType.getName()).getUpdateService()).insertRows(_user, _c, rows, errors, null, null); - if (errors.hasErrors()) - throw errors; + SampleTypeTestHelper.insert(_c, _user, sampleType, rows); } @AfterClass @@ -821,38 +817,13 @@ private static GWTPropertyDescriptor calculated(String name, PropertyType type, private static TableInfo getTable(String name) { - return Objects.requireNonNull(QueryService.get().getUserSchema(_user, _c, SamplesSchema.SCHEMA_NAME).getTable(name)); + return QueryUpdateServiceTestUtil.getTable(_user, _c, SamplesSchema.SCHEMA_SAMPLES, name); } private static FilterSuggestionContext context(TableInfo table, User user) { - return new FilterSuggestionContext() - { - @Override - public @NotNull TableInfo getTable() - { - return table; - } - - @Override - public @NotNull ContainerFilter getContainerFilter() - { - // The table's filter for every user, so only the user can differ between contexts - return Objects.requireNonNullElseGet(table.getContainerFilter(), () -> ContainerFilter.current(_c, _user)); - } - - @Override - public @NotNull Container getContainer() - { - return _c; - } - - @Override - public @NotNull User getUser() - { - return user; - } - }; + // The table's filter for every user, so only the user can differ between contexts + return new FilterSuggestionTestContext(table, Objects.requireNonNullElseGet(table.getContainerFilter(), () -> ContainerFilter.current(_c, _user)), _c, user); } private static Map byFieldKey(FilterSuggestionColumns.Described described) diff --git a/search/src/org/labkey/search/model/SecurityQuery.java b/search/src/org/labkey/search/model/SecurityQuery.java index 0c1774aa2d8..71fb32b11af 100644 --- a/search/src/org/labkey/search/model/SecurityQuery.java +++ b/search/src/org/labkey/search/model/SecurityQuery.java @@ -407,55 +407,30 @@ public Class getRequiredPermission() }; } - @Test - public void testCategoryWithNoRequiredPermissionGoesToBaseRead() - { - SearchCategory wiki = new SearchCategory("wiki", "Wiki Pages"); - - CategoryPermissions result = SecurityQuery.groupCategoriesByRequiredPermission(List.of(wiki)); - - assertEquals(Set.of("wiki"), result.baseReadCategoryNames()); - assertTrue(result.categoriesByPermission().isEmpty()); - } + private record Case(String name, List categories, Set baseRead, Map, Set> byPermission) {} @Test - public void testCategoriesSharingAPermissionAreGroupedTogether() + public void testGroupCategoriesByRequiredPermission() { - // Mirrors the real assay/assayBatch/assayRun categories, which all require the same permission. + SearchCategory wiki = new SearchCategory("wiki", "Wiki Pages"); + // Mirrors the real assay/assayBatch/assayRun categories, which all require the same permission SearchCategory assay = categoryRequiring("assay", InsertPermission.class); SearchCategory assayBatch = categoryRequiring("assayBatch", InsertPermission.class); SearchCategory assayRun = categoryRequiring("assayRun", InsertPermission.class); - - CategoryPermissions result = SecurityQuery.groupCategoriesByRequiredPermission(List.of(assay, assayBatch, assayRun)); - - assertTrue(result.baseReadCategoryNames().isEmpty()); - assertEquals(Set.of(InsertPermission.class), result.categoriesByPermission().keySet()); - assertEquals(Set.of(assay, assayBatch, assayRun), Set.copyOf(result.categoriesByPermission().get(InsertPermission.class))); - } - - @Test - public void testCategoriesWithDifferentPermissionsAreNotGroupedTogether() - { - SearchCategory data = categoryRequiring("data", InsertPermission.class); SearchCategory media = categoryRequiring("media", DeletePermission.class); - CategoryPermissions result = SecurityQuery.groupCategoriesByRequiredPermission(List.of(data, media)); - - assertEquals(Set.of(InsertPermission.class, DeletePermission.class), result.categoriesByPermission().keySet()); - assertEquals(List.of(data), result.categoriesByPermission().get(InsertPermission.class)); - assertEquals(List.of(media), result.categoriesByPermission().get(DeletePermission.class)); - } - - @Test - public void testMixOfBaseReadAndPermissionRequiringCategories() - { - SearchCategory wiki = new SearchCategory("wiki", "Wiki Pages"); - SearchCategory data = categoryRequiring("data", InsertPermission.class); - - CategoryPermissions result = SecurityQuery.groupCategoriesByRequiredPermission(List.of(wiki, data)); - - assertEquals(Set.of("wiki"), result.baseReadCategoryNames()); - assertEquals(List.of(data), result.categoriesByPermission().get(InsertPermission.class)); + for (Case c : List.of( + new Case("no required permission", List.of(wiki), Set.of("wiki"), Map.of()), + new Case("shared permission", List.of(assay, assayBatch, assayRun), Set.of(), Map.of(InsertPermission.class, Set.of(assay, assayBatch, assayRun))), + new Case("different permissions", List.of(assay, media), Set.of(), Map.of(InsertPermission.class, Set.of(assay), DeletePermission.class, Set.of(media))), + new Case("mixed", List.of(wiki, assay), Set.of("wiki"), Map.of(InsertPermission.class, Set.of(assay))))) + { + CategoryPermissions result = SecurityQuery.groupCategoriesByRequiredPermission(c.categories()); + assertEquals(c.name(), c.baseRead(), result.baseReadCategoryNames()); + Map, Set> byPermission = new HashMap<>(); + result.categoriesByPermission().forEach((permission, categories) -> byPermission.put(permission, Set.copyOf(categories))); + assertEquals(c.name(), c.byPermission(), byPermission); + } } } diff --git a/study/src/org/labkey/study/controllers/reports/ReportsController.java b/study/src/org/labkey/study/controllers/reports/ReportsController.java index f4edebb2dd8..057561a992e 100644 --- a/study/src/org/labkey/study/controllers/reports/ReportsController.java +++ b/study/src/org/labkey/study/controllers/reports/ReportsController.java @@ -74,6 +74,7 @@ import org.labkey.api.study.Visit; import org.labkey.api.study.reports.CrosstabReport; import org.labkey.api.study.reports.CrosstabReportDescriptor; +import org.labkey.api.util.GUID; import org.labkey.api.util.ImageUtil; import org.labkey.api.util.PageFlowUtil; import org.labkey.api.util.ReturnURLString; @@ -106,6 +107,7 @@ import org.labkey.study.reports.ReportManager; import org.labkey.study.reports.StudyCrosstabReport; import org.labkey.study.reports.StudyQueryReport; +import org.labkey.study.reports.StudyRReport; import org.labkey.vfs.FileLike; import org.springframework.validation.BindException; import org.springframework.validation.Errors; @@ -1328,19 +1330,20 @@ public void bindJson(JSONObject json) public static class ContainerScopingTestCase extends AbstractContainerScopingTest { + // Containers are shared across tests, so report names and keys are unique per call @Test public void testShowReportRequiresReadPermission() throws Exception { // ShowReportAction resolves a report by global rowId with getReport(container, rowId) -- container-scoped, // but with no owner/policy check. Without the fix a plain container Reader could render another user's // PRIVATE report by guessing its rowId. The fix adds the per-report canReadReport() check. - Container folder = createContainer("A"); + Container folder = getSharedContainer("A"); // A PRIVATE report: owned by the admin (descriptor owner set), so only the owner / a site admin may read it. Report report = ReportService.get().createReportInstance(QueryReport.TYPE); - report.getDescriptor().setReportName("scoping-private-report"); + report.getDescriptor().setReportName("scoping-private-report-" + GUID.makeGUID()); report.getDescriptor().setOwner(getAdmin().getUserId()); - int reportId = ReportService.get().saveReportEx(new DefaultContainerUser(folder, getAdmin()), "scoping-report-key", report).getRowId(); + int reportId = ReportService.get().saveReportEx(new DefaultContainerUser(folder, getAdmin()), "scoping-report-key-" + GUID.makeGUID(), report).getRowId(); ActionURL url = new ActionURL(ShowReportAction.class, folder).addParameter("reportId", String.valueOf(reportId)); @@ -1367,18 +1370,19 @@ public void testOverwritingSavedReports() throws Exception @Test public void testUpdateCannotConvertToScriptReport() throws Exception { - Container folder = createContainer("A"); + Container folder = getSharedContainer("A"); + String name = "grid-to-script-report-" + GUID.makeGUID(); Report gridReport = ReportService.get().createReportInstance(QueryReport.TYPE); - gridReport.getDescriptor().setReportName("grid-to-script-report"); + gridReport.getDescriptor().setReportName(name); int rowId = ReportService.get() - .saveReportEx(new DefaultContainerUser(folder, getAdmin()), "grid-to-script-key", gridReport) + .saveReportEx(new DefaultContainerUser(folder, getAdmin()), name, gridReport) .getRowId(); User editor = createUserInRole(folder, EditorRole.class); ActionURL url = new ActionURL(SaveReportViewAction.class, folder) - .addParameter("reportType", "Study.rReport") - .addParameter("label", "grid-to-script-report") + .addParameter("reportType", StudyRReport.TYPE) + .addParameter("label", name) .addParameter("shareReport", "true") .addParameter("params", "reportId=db%3A" + rowId + "&script=print%281%29"); post(url, editor); @@ -1395,21 +1399,22 @@ public void testUpdateCannotConvertToScriptReport() throws Exception */ private void assertReportNotStolen(Class action, String reportType, Class attackerRole, boolean shareReport) throws Exception { - Container attackerFolder = createContainer("A"); - Container victimFolder = createContainer("B"); + Container attackerFolder = getSharedContainer("A"); + Container victimFolder = getSharedContainer("B"); // Shared (no descriptor owner), the case the save path treats as editable by any container Editor. + String victimKey = "scoping-victim-key-" + GUID.makeGUID(); Report victimReport = ReportService.get().createReportInstance(QueryReport.TYPE); - victimReport.getDescriptor().setReportName("scoping-victim-report"); + victimReport.getDescriptor().setReportName("scoping-victim-report-" + GUID.makeGUID()); int victimRowId = ReportService.get() - .saveReportEx(new DefaultContainerUser(victimFolder, getAdmin()), "scoping-victim-key", victimReport) + .saveReportEx(new DefaultContainerUser(victimFolder, getAdmin()), victimKey, victimReport) .getRowId(); User attacker = createUserInRole(attackerFolder, attackerRole); ActionURL url = new ActionURL(action, attackerFolder) .addParameter("reportType", reportType) - .addParameter("label", "scoping-stolen-report") + .addParameter("label", "scoping-stolen-report-" + GUID.makeGUID()) .addParameter("params", "reportId=db%3A" + victimRowId); if (shareReport) url.addParameter("shareReport", "true"); @@ -1425,7 +1430,7 @@ private void assertReportNotStolen(Class action, String re assertEquals("The victim's report was re-homed into a folder the caller controls", victimFolder.getId(), row.getContainerId()); assertEquals("The victim's report was overwritten by a caller with no permission in its folder", - "scoping-victim-key", row.getReportKey()); + victimKey, row.getReportKey()); } } diff --git a/wiki/src/org/labkey/wiki/WikiController.java b/wiki/src/org/labkey/wiki/WikiController.java index ff4843a3234..bc91f4752b7 100644 --- a/wiki/src/org/labkey/wiki/WikiController.java +++ b/wiki/src/org/labkey/wiki/WikiController.java @@ -3024,7 +3024,7 @@ public void testCopyWikiChecksSourceBeforeCreatingFolder() throws Exception public void testCopyWikiCannotCreateProjectWithoutSiteAdmin() throws Exception { User limitedAdmin = createUserInRole(_source, FolderAdminRole.class); - String newPath = "/" + getClass().getName().replaceAll("[^A-Za-z0-9]", "_") + "-NewProject"; + String newPath = "/CopyWikiNewProject-" + GUID.makeGUID(); try { diff --git a/wiki/src/org/labkey/wiki/WikiTOC.java b/wiki/src/org/labkey/wiki/WikiTOC.java index 1132dd3846d..91754383071 100644 --- a/wiki/src/org/labkey/wiki/WikiTOC.java +++ b/wiki/src/org/labkey/wiki/WikiTOC.java @@ -25,9 +25,7 @@ import org.labkey.api.data.Container; import org.labkey.api.data.ContainerManager; import org.labkey.api.security.Group; -import org.labkey.api.security.MutableSecurityPolicy; import org.labkey.api.security.SecurityManager; -import org.labkey.api.security.SecurityPolicyManager; import org.labkey.api.security.User; import org.labkey.api.security.permissions.AbstractContainerScopingTest; import org.labkey.api.security.permissions.AdminPermission; @@ -367,18 +365,16 @@ public void testTocRequiresReadInTargetFolder() throws Exception { User user = createUserInRole(_host, ReaderRole.class); String html = renderToc(user); - assertTrue("Expected no-permission message, html was: " + html, html.contains("You do not have permission to see this data.")); + assertTrue("Expected no-permission message, html was: " + html, html.contains(WikiManager.get().getNoPermissionsMessage(user).toString())); assertFalse("Target folder's page leaked into the TOC", html.contains(PAGE_TITLE)); grantRole(user, _target, ReaderRole.class); html = renderToc(user); assertTrue("Reader in the target folder should see its pages, html was: " + html, html.contains(PAGE_TITLE)); - MutableSecurityPolicy policy = new MutableSecurityPolicy(_host.getPolicy()); - policy.addRoleAssignment(SecurityManager.getGroup(Group.groupGuests), ReaderRole.class); - SecurityPolicyManager.savePolicyForTests(policy, getAdmin()); + grantRole(SecurityManager.getGroup(Group.groupGuests), _host, ReaderRole.class); html = renderToc(User.guest); - assertTrue("Expected guest login prompt, html was: " + html, html.contains("Please log in to see this data.")); + assertTrue("Expected guest login prompt, html was: " + html, html.contains(WikiManager.get().getNoPermissionsMessage(User.guest).toString())); assertFalse("Target folder's page leaked into the guest TOC", html.contains(PAGE_TITLE)); } From b493b3dde080636409c6aa51cc8765bd25306a74 Mon Sep 17 00:00:00 2001 From: labkey-jeckels Date: Thu, 19 Nov 2026 09:02:04 -0800 Subject: [PATCH 02/10] Build fix --- core/test/src/org/labkey/test/tests/RequestCancellationTest.java | 1 + 1 file changed, 1 insertion(+) diff --git a/core/test/src/org/labkey/test/tests/RequestCancellationTest.java b/core/test/src/org/labkey/test/tests/RequestCancellationTest.java index bbfac88a46b..e6322de20ec 100644 --- a/core/test/src/org/labkey/test/tests/RequestCancellationTest.java +++ b/core/test/src/org/labkey/test/tests/RequestCancellationTest.java @@ -37,6 +37,7 @@ import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; +import java.util.stream.Collectors; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; From 726edf23a7f40f583e4f4aa01d78638fe864ba40 Mon Sep 17 00:00:00 2001 From: labkey-jeckels Date: Fri, 20 Nov 2026 13:16:04 -0800 Subject: [PATCH 03/10] Fix unreplaced-substitution test whose param name contained the known param --- api/src/org/labkey/api/reports/ExternalScriptEngine.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/api/src/org/labkey/api/reports/ExternalScriptEngine.java b/api/src/org/labkey/api/reports/ExternalScriptEngine.java index 69241e574c2..1897745aed6 100644 --- a/api/src/org/labkey/api/reports/ExternalScriptEngine.java +++ b/api/src/org/labkey/api/reports/ExternalScriptEngine.java @@ -768,7 +768,7 @@ public void testFullyReplacedScriptSucceeds() throws ScriptException @Test public void testUnreplacedSubstitutionsThrow() { - for (List unknowns : List.of(List.of("unknownParam"), List.of("firstUnknown", "secondUnknown"))) + for (List unknowns : List.of(List.of("missingParam"), List.of("firstUnknown", "secondUnknown"))) { String script = unknowns.stream().map(p -> "${" + p + "}").collect(Collectors.joining(" and ${" + KNOWN_PARAM + "} and ")); ScriptException e = assertThrows(script, ScriptException.class, () -> _engine.writeScriptFile(script, _context, List.of("R"))); From 603200ca03f9c3926dd8fb21cc7eebfebb72b8ce Mon Sep 17 00:00:00 2001 From: labkey-jeckels Date: Fri, 20 Nov 2026 13:17:09 -0800 Subject: [PATCH 04/10] Use BatchSize for detailed audit flushes so the provided-amount audit test runs with 25 rows --- .../DetailedAuditLogDataIterator.java | 3 ++- .../api/SampleProvidedAmountAuditTestCase.java | 18 +++++++++++++----- 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/api/src/org/labkey/api/dataiterator/DetailedAuditLogDataIterator.java b/api/src/org/labkey/api/dataiterator/DetailedAuditLogDataIterator.java index fbac5d6e1b1..c1cb0e00e53 100644 --- a/api/src/org/labkey/api/dataiterator/DetailedAuditLogDataIterator.java +++ b/api/src/org/labkey/api/dataiterator/DetailedAuditLogDataIterator.java @@ -18,6 +18,7 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.labkey.api.audit.AuditHandler; +import org.labkey.api.data.BatchSize; import org.labkey.api.data.ColumnInfo; import org.labkey.api.data.Container; import org.labkey.api.data.TableInfo; @@ -102,7 +103,7 @@ public boolean next() throws BatchValidationException { boolean hasNext = _data.next(); - if (!hasNext || _rowData.size() > 1000) + if (!hasNext || _rowData.size() >= BatchSize.get(BatchSize.Kind.ROWS)) { if (!_rowData.isEmpty()) { diff --git a/experiment/src/org/labkey/experiment/api/SampleProvidedAmountAuditTestCase.java b/experiment/src/org/labkey/experiment/api/SampleProvidedAmountAuditTestCase.java index 5e4010bc351..5ae14f58464 100644 --- a/experiment/src/org/labkey/experiment/api/SampleProvidedAmountAuditTestCase.java +++ b/experiment/src/org/labkey/experiment/api/SampleProvidedAmountAuditTestCase.java @@ -23,6 +23,7 @@ import org.labkey.api.audit.AuditLogService; import org.labkey.api.audit.SampleTimelineAuditEvent; import org.labkey.api.collections.CaseInsensitiveHashMap; +import org.labkey.api.data.BatchSize; import org.labkey.api.data.Container; import org.labkey.api.data.SimpleFilter; import org.labkey.api.data.Sort; @@ -54,12 +55,13 @@ import static org.labkey.experiment.samples.SampleTimelineAuditProvider.SAMPLE_TYPE_ID_COLUMN_NAME; /** - * GH Issue 1640: DetailedAuditLogDataIterator flushes audit events every 1,001 rows, and each sample's - * provided amount must stay with that sample across flushes. + * GH Issue 1640: DetailedAuditLogDataIterator flushes audit events every {@link BatchSize.Kind#ROWS} rows, and each + * sample's provided amount must stay with that sample across flushes. */ public class SampleProvidedAmountAuditTestCase extends Assert { - private static final int ROW_COUNT = 2500; // spans three audit batches + private static final int BATCH_SIZE = 10; + private static final int ROW_COUNT = 25; // spans three audit batches; the merge's update and insert halves each cross a flush private static final String PROVIDED_AMOUNT_KEY = USER_PROVIDED_DATA_PREFIX + StoredAmount.label(); private static Container _c; @@ -91,7 +93,10 @@ public void testInsertKeepsProvidedAmountWithRow() throws Exception expected.put("S-" + i, i); } - SampleTypeTestHelper.insert(_c, _user, st, rows); + try (AutoCloseable ignored = BatchSize.override(BatchSize.Kind.ROWS, BATCH_SIZE)) + { + SampleTypeTestHelper.insert(_c, _user, st, rows); + } assertProvidedAmounts(st, expected); } @@ -117,7 +122,10 @@ public void testMergeKeepsProvidedAmountWithRow() throws Exception expected.put("S-" + i, amount); } - QueryUpdateServiceTestUtil.merge(SampleTypeTestHelper.getTable(_c, _user, st), _user, _c, rows); + try (AutoCloseable ignored = BatchSize.override(BatchSize.Kind.ROWS, BATCH_SIZE)) + { + QueryUpdateServiceTestUtil.merge(SampleTypeTestHelper.getTable(_c, _user, st), _user, _c, rows); + } assertProvidedAmounts(st, expected); } From 66cbae1f16cf668872e1d00a76f1b85f0d353abc Mon Sep 17 00:00:00 2001 From: labkey-jeckels Date: Fri, 20 Nov 2026 13:22:41 -0800 Subject: [PATCH 05/10] Shorten fixed sleeps and timeouts in slow BVT server-side tests --- .../org/labkey/api/cache/BlockingCache.java | 4 +- .../labkey/api/data/AsyncQueryRequest.java | 41 ++++++++++++------- .../labkey/api/data/TransactionFilter.java | 38 +++++++++++++---- .../api/files/FileSystemWatcherImpl.java | 29 +++++++------ .../experiment/api/ExperimentStressTest.java | 2 +- .../pipeline/api/PipelineQueueImpl.java | 2 +- .../query/suggestions/ColumnFactsCache.java | 2 +- 7 files changed, 77 insertions(+), 41 deletions(-) diff --git a/api/src/org/labkey/api/cache/BlockingCache.java b/api/src/org/labkey/api/cache/BlockingCache.java index 18289a23c01..4b1a0e80273 100644 --- a/api/src/org/labkey/api/cache/BlockingCache.java +++ b/api/src/org/labkey/api/cache/BlockingCache.java @@ -315,7 +315,7 @@ private CacheLoader createLoader(final AtomicInteger calls, fi public void testBlockingGet() { final AtomicInteger calls = new AtomicInteger(); - final BlockingCache bc = new BlockingCache<>(_cache, createLoader(calls, 1000)); + final BlockingCache bc = new BlockingCache<>(_cache, createLoader(calls, 200)); final CountDownLatch start = new CountDownLatch(1); Runnable r = () -> { Random r1 = new Random(); @@ -348,7 +348,7 @@ private void createAndStartThreads(Runnable r, CountDownLatch start, int count) public void testTimeout() { final AtomicInteger calls = new AtomicInteger(); - final BlockingCache bc = new BlockingCache<>(_cache, createLoader(calls, 5000), 1000); + final BlockingCache bc = new BlockingCache<>(_cache, createLoader(calls, 3000), 1000); final AtomicInteger timeouts = new AtomicInteger(); final CountDownLatch start = new CountDownLatch(1); diff --git a/api/src/org/labkey/api/data/AsyncQueryRequest.java b/api/src/org/labkey/api/data/AsyncQueryRequest.java index 681dcc01d57..55098dd38fc 100644 --- a/api/src/org/labkey/api/data/AsyncQueryRequest.java +++ b/api/src/org/labkey/api/data/AsyncQueryRequest.java @@ -68,6 +68,7 @@ public class AsyncQueryRequest private static final String CLIENT_DISCONNECTED_TAG = "labkey.client_disconnected"; private static final String ELAPSED_TAG = "labkey.async_query.ms"; private static final long WORKER_EXIT_TIMEOUT_MS = 10_000; + private static volatile long _workerExitTimeoutMs = WORKER_EXIT_TIMEOUT_MS; /** Cancelled workers whose requests stopped waiting for them, re-cancelled by the request timeout sweep until they finish */ private static final Set> _detached = ConcurrentHashMap.newKeySet(); @@ -308,13 +309,14 @@ synchronized public T waitForResult(final Callable callable) throws SQLExcept */ synchronized private void awaitWorkerAfterInterrupt(Thread worker) { - long deadline = System.currentTimeMillis() + WORKER_EXIT_TIMEOUT_MS; + long timeout = _workerExitTimeoutMs; + long deadline = System.currentTimeMillis() + timeout; while (!_finished) { long remaining = deadline - System.currentTimeMillis(); if (remaining <= 0) { - _log.warn("Async query thread '{}' still running {} ms after its request was interrupted", worker.getName(), WORKER_EXIT_TIMEOUT_MS); + _log.warn("Async query thread '{}' still running {} ms after its request was interrupted", worker.getName(), timeout); // The worker still holds this thread's connection. Detaching keeps the thread's next request off it; marking // discards it even if this request's cleanup releases it while the worker is still using it. ConnectionWrapper.getConnectionsByScopeForEffectiveThread(Thread.currentThread()).values().forEach(c -> c.forEach(ConnectionWrapper::markCancelled)); @@ -635,7 +637,7 @@ public void testStuckWorkerDetached() throws Exception } }, "AsyncQueryRequest stuck worker test"); - try + try (AutoCloseable _ = overrideWorkerExitTimeout()) { requestThread.start(); assertTrue("Worker never got a connection", holding.await(10, TimeUnit.SECONDS)); @@ -711,17 +713,28 @@ public void testDetachedWorkerCancelled() throws Exception } }, "AsyncQueryRequest detached worker test"); - requestThread.start(); - assertTrue("Worker never registered its statement", registered.await(10, TimeUnit.SECONDS)); - requestThread.interrupt(); - requestThread.join(WORKER_EXIT_TIMEOUT_MS + 10_000); - assertFalse("Request thread didn't exit", requestThread.isAlive()); - assertTrue("Expected an aborted request, got " + failure.get(), failure.get() instanceof AbortedRequestException); - - // The sweep's 5 s interval, with slack - assertTrue("Worker didn't finish", workerDone.await(20, TimeUnit.SECONDS)); - assertTrue("Query wasn't cancelled: " + queryFailure.get(), queryFailure.get() instanceof SQLException e && SqlDialect.isCancelException(e)); - assertTrue("Cancel took too long: " + queryMs.get() + " ms", queryMs.get() < 15_000); + try (AutoCloseable _ = overrideWorkerExitTimeout(); + AutoCloseable _ = TransactionFilter.shortenSweepInterval()) + { + requestThread.start(); + assertTrue("Worker never registered its statement", registered.await(10, TimeUnit.SECONDS)); + requestThread.interrupt(); + requestThread.join(WORKER_EXIT_TIMEOUT_MS + 10_000); + assertFalse("Request thread didn't exit", requestThread.isAlive()); + assertTrue("Expected an aborted request, got " + failure.get(), failure.get() instanceof AbortedRequestException); + + // The sweep's interval, with slack + assertTrue("Worker didn't finish", workerDone.await(20, TimeUnit.SECONDS)); + assertTrue("Query wasn't cancelled: " + queryFailure.get(), queryFailure.get() instanceof SQLException e && SqlDialect.isCancelException(e)); + assertTrue("Cancel took too long: " + queryMs.get() + " ms", queryMs.get() < 15_000); + } + } + + /** Shortens the wait for a stuck worker server-wide; close the result to restore it */ + private static AutoCloseable overrideWorkerExitTimeout() + { + _workerExitTimeoutMs = 1_000; + return () -> _workerExitTimeoutMs = WORKER_EXIT_TIMEOUT_MS; } } } diff --git a/api/src/org/labkey/api/data/TransactionFilter.java b/api/src/org/labkey/api/data/TransactionFilter.java index 2eecbddeffd..cfb0c0e17be 100644 --- a/api/src/org/labkey/api/data/TransactionFilter.java +++ b/api/src/org/labkey/api/data/TransactionFilter.java @@ -76,6 +76,11 @@ public class TransactionFilter implements Filter // NOTE: can't use ThreadLocal for this as you can't inspect the values for other threads private static final Map _pendingRequests = Collections.synchronizedMap(new WeakHashMap<>()); + private static final long SWEEP_INTERVAL_MS = 5_000; + private static final long TEST_SWEEP_INTERVAL_MS = 250; + private static final Object SWEEP_LOCK = new Object(); + private static volatile long _sweepIntervalMs = SWEEP_INTERVAL_MS; + public static final String READ_ONLY_ATTRIBUTE_NAME = "ReadOnlyHttpRequest"; /** Read-only, but a legitimate export on a large instance can outlast the read-only timeout */ public static final String EXPORT_ATTRIBUTE_NAME = "ExportHttpRequest"; @@ -181,8 +186,10 @@ else if (timeout > 0 && isTimedOut(thread, tracker, cutoff)) } try { - //noinspection BusyWait - Thread.sleep(5_000); + synchronized (SWEEP_LOCK) + { + SWEEP_LOCK.wait(_sweepIntervalMs); + } } catch (InterruptedException e) { @@ -431,6 +438,23 @@ public static int getPendingRequestCount() return _pendingRequests.size(); } + /** Server-wide, for tests that wait on the request timeout sweep. Close the result to restore the default interval. */ + static AutoCloseable shortenSweepInterval() + { + setSweepInterval(TEST_SWEEP_INTERVAL_MS); + return () -> setSweepInterval(SWEEP_INTERVAL_MS); + } + + private static void setSweepInterval(long ms) + { + _sweepIntervalMs = ms; + // Wakes the sweep so the new interval applies now rather than after the current wait + synchronized (SWEEP_LOCK) + { + SWEEP_LOCK.notifyAll(); + } + } + public static void shutDown(long msWaitForRequests) { while (msWaitForRequests > 0) @@ -487,7 +511,7 @@ public void testSweep() throws Exception int originalTimeout = AppProps.getInstance().getReadOnlyHttpRequestTimeout(); setReadOnlyTimeout(2); - try + try (AutoCloseable _ = shortenSweepInterval()) { RequestTestUtil.runOnRequestThread(() -> { Thread thread = Thread.currentThread(); @@ -500,7 +524,7 @@ public void testSweep() throws Exception fail("Query wasn't cancelled"); } catch (RuntimeException ignored) {} // Checked by its source below - // Timeout, HeartBeat's up-to-2 s lag, and the sweep's 5 s interval, with slack + // Timeout, HeartBeat's up-to-2 s lag, and the sweep's interval, with slack assertTrue("Cancel took too long", System.currentTimeMillis() - start < 15_000); assertEquals(RequestCancellation.Source.TIMEOUT, RequestCancellation.getSource(thread)); }); @@ -509,7 +533,7 @@ public void testSweep() throws Exception RequestTestUtil.doRequest(null, () -> { getRequestSummary(thread).request().setAttribute(EXPORT_ATTRIBUTE_NAME, true); // Long enough for a sweep after the timeout despite HeartBeat's lag - new SqlSelector(scope, "SELECT pg_sleep(12)").getObject(Object.class); + new SqlSelector(scope, "SELECT pg_sleep(5)").getObject(Object.class); assertNull("Export was cancelled", RequestCancellation.getSource(thread)); }); }); @@ -579,7 +603,7 @@ public void testSweepResendsLostCancel() throws Exception int originalTimeout = AppProps.getInstance().getReadOnlyHttpRequestTimeout(); setReadOnlyTimeout(0); - try + try (AutoCloseable _ = shortenSweepInterval()) { RequestTestUtil.runOnRequestThread(() -> { Thread thread = Thread.currentThread(); @@ -600,7 +624,7 @@ public void testSweepResendsLostCancel() throws Exception fail("Query wasn't cancelled"); } catch (RuntimeException ignored) {} // Checked by its source below - // The sweep's 5 s interval, with slack + // The sweep's interval, with slack assertTrue("Cancel took too long", System.currentTimeMillis() - start < 15_000); assertEquals(RequestCancellation.Source.WS_MESSAGE, RequestCancellation.getSource(thread)); } diff --git a/api/src/org/labkey/api/files/FileSystemWatcherImpl.java b/api/src/org/labkey/api/files/FileSystemWatcherImpl.java index 9d4b968329f..3bd1eed2c99 100644 --- a/api/src/org/labkey/api/files/FileSystemWatcherImpl.java +++ b/api/src/org/labkey/api/files/FileSystemWatcherImpl.java @@ -31,7 +31,6 @@ import org.labkey.api.util.ExceptionUtil; import org.labkey.api.util.FileUtil; import org.labkey.api.util.ShutdownListener; -import org.labkey.api.util.StringUtilsLabKey; import org.labkey.api.util.logging.LogHelper; import org.labkey.api.writer.PrintWriters; @@ -54,6 +53,7 @@ import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.BooleanSupplier; import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE; import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE; @@ -565,7 +565,7 @@ public void overflow() assertTrue(FileUtil.createNewFile(b)); assertTrue(FileUtil.createNewFile(c)); - waitForEvents(events, 3); + waitForEvents(events, () -> events.get() >= 3); try (PrintWriter pw = PrintWriters.getPrintWriter(a)) { @@ -577,16 +577,17 @@ public void overflow() pw.println("Hello World"); } - waitForEvents(events, SystemUtils.IS_OS_WINDOWS ? 7 : 5); + waitForEvents(events, () -> events.get() >= (SystemUtils.IS_OS_WINDOWS ? 7 : 5)); assertTrue(a.delete()); assertTrue(b.delete()); - waitForEvents(events, SystemUtils.IS_OS_WINDOWS ? 11 : 8); + waitForEvents(events, () -> events.get() >= (SystemUtils.IS_OS_WINDOWS ? 11 : 8)); FileUtil.deleteDir(testFolder); - waitForEvents(events, SystemUtils.IS_OS_WINDOWS ? 14 : 10); + // The delete of a file inside a deleted directory may never be reported, so wait only for what the assertions require + waitForEvents(events, () -> !directoryDeleted.isEmpty()); assertEquals(3, created.size()); assertTrue(created.containsAll(Set.of("a", "b", "c"))); @@ -603,23 +604,21 @@ public void overflow() assertNull(plm); } - private void waitForEvents(AtomicInteger events, int targetCount) throws InterruptedException + private void waitForEvents(AtomicInteger events, BooleanSupplier done) throws InterruptedException { - int i = 2; - Thread.sleep(i * 1000); - int maxSleepSeconds = 10; + long start = System.currentTimeMillis(); + long deadline = start + TimeUnit.SECONDS.toMillis(10); - while (events.get() < targetCount && i < maxSleepSeconds) + while (!done.getAsBoolean() && System.currentTimeMillis() < deadline) { //noinspection BusyWait - Thread.sleep(1000); - i++; + Thread.sleep(50); } - LOG.info("Waiting for file watcher events took {}", StringUtilsLabKey.pluralize(i, "second")); + // Lets duplicate or trailing events for this step land before the next step starts + Thread.sleep(250); - LOG.info("Actual event count: {} vs. target: {}", events.get(), targetCount); - //assertEquals(expectedEventCount, events.get()); + LOG.info("Waiting for file watcher events took {} ms; event count: {}", System.currentTimeMillis() - start, events.get()); } } } diff --git a/experiment/src/org/labkey/experiment/api/ExperimentStressTest.java b/experiment/src/org/labkey/experiment/api/ExperimentStressTest.java index 325d50a697f..7ad3ebea531 100644 --- a/experiment/src/org/labkey/experiment/api/ExperimentStressTest.java +++ b/experiment/src/org/labkey/experiment/api/ExperimentStressTest.java @@ -216,7 +216,7 @@ private void _sampleTypeInserts(RunMode mode) throws Throwable try { - Thread.sleep(randomInt(10) * 200); + Thread.sleep(randomInt(10) * 20L); insertSamples(user, c, sampleTypeName, parentNames, rowsToInsert, mode == RunMode.withaliquot); } catch (Exception e) diff --git a/pipeline/src/org/labkey/pipeline/api/PipelineQueueImpl.java b/pipeline/src/org/labkey/pipeline/api/PipelineQueueImpl.java index b7d75ec777c..5f842df619e 100644 --- a/pipeline/src/org/labkey/pipeline/api/PipelineQueueImpl.java +++ b/pipeline/src/org/labkey/pipeline/api/PipelineQueueImpl.java @@ -305,7 +305,7 @@ protected TestJob() {} @Override public void run() { - long til = System.currentTimeMillis() + 1000; + long til = System.currentTimeMillis() + 100; double[] a = new double[10000]; while (til > System.currentTimeMillis()) { diff --git a/query/src/org/labkey/query/suggestions/ColumnFactsCache.java b/query/src/org/labkey/query/suggestions/ColumnFactsCache.java index 28db6a5827f..c682a187693 100644 --- a/query/src/org/labkey/query/suggestions/ColumnFactsCache.java +++ b/query/src/org/labkey/query/suggestions/ColumnFactsCache.java @@ -1068,7 +1068,7 @@ public void testColumnsReachedThroughAuditLoggedLookupsReadNoData() @Test public void testBudget() throws Exception { - ColumnFactsCache cache = new ColumnFactsCache(_testCache, _executor, new TestSource(2_000)); + ColumnFactsCache cache = new ColumnFactsCache(_testCache, _executor, new TestSource(500)); TableInfo table = getTable(SAMPLE_TYPE); long start = System.currentTimeMillis(); From d2266ad0b9074bf535a4679097bd3c3b4b33a1da Mon Sep 17 00:00:00 2001 From: labkey-jeckels Date: Fri, 20 Nov 2026 13:54:45 -0800 Subject: [PATCH 06/10] Create test studies and containers once per class in slow BVT tests --- .../experiment/api/ExperimentStressTest.java | 6 +++--- .../study/model/DatasetLsidImportHelper.java | 18 +++++++++--------- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/experiment/src/org/labkey/experiment/api/ExperimentStressTest.java b/experiment/src/org/labkey/experiment/api/ExperimentStressTest.java index 7ad3ebea531..31a22b84720 100644 --- a/experiment/src/org/labkey/experiment/api/ExperimentStressTest.java +++ b/experiment/src/org/labkey/experiment/api/ExperimentStressTest.java @@ -18,7 +18,7 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.AfterClass; -import org.junit.Before; +import org.junit.BeforeClass; import org.junit.Test; import org.labkey.api.collections.CaseInsensitiveHashMap; import org.labkey.api.data.Container; @@ -51,8 +51,8 @@ public class ExperimentStressTest { private static final Logger LOG = LogManager.getLogger(ExperimentStressTest.class); - @Before - public void setup() + @BeforeClass + public static void setup() { Container junit = ContainerManager.getForPath(JunitUtil.getTestContainerPath()); if (junit != null) diff --git a/study/src/org/labkey/study/model/DatasetLsidImportHelper.java b/study/src/org/labkey/study/model/DatasetLsidImportHelper.java index 7460cdcfa84..baae138c91a 100644 --- a/study/src/org/labkey/study/model/DatasetLsidImportHelper.java +++ b/study/src/org/labkey/study/model/DatasetLsidImportHelper.java @@ -19,9 +19,9 @@ import org.apache.commons.beanutils.Converter; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.junit.After; +import org.junit.AfterClass; import org.junit.Assert; -import org.junit.Before; +import org.junit.BeforeClass; import org.junit.Test; import org.labkey.api.collections.CaseInsensitiveHashMap; import org.labkey.api.data.Container; @@ -148,18 +148,18 @@ else if (keyValue != null) public final static class TestCase extends Assert { - private StudyImpl _visitStudy; - private StudyImpl _dateStudy; + private static StudyImpl _visitStudy; + private static StudyImpl _dateStudy; - @Before - public void initialize() + @BeforeClass + public static void initialize() { // create studies _visitStudy = createStudy(TimepointType.VISIT, "Visit Study"); _dateStudy = createStudy(TimepointType.DATE, "Date Study"); } - private StudyImpl createStudy(TimepointType timepointType, String name) + private static StudyImpl createStudy(TimepointType timepointType, String name) { TestContext context = TestContext.get(); Container c = ContainerManager.createContainer(JunitUtil.getTestContainer(), GUID.makeHash(), context.getUser()); @@ -170,8 +170,8 @@ private StudyImpl createStudy(TimepointType timepointType, String name) return StudyManager.getInstance().createTestStudy(context.getUser(), study); } - @After - public void tearDown() + @AfterClass + public static void tearDown() { JunitUtil.deleteTestContainer(); } From b1de32817ada57586b83a78afb78d52f2ca5d7bb Mon Sep 17 00:00:00 2001 From: labkey-jeckels Date: Fri, 20 Nov 2026 14:11:41 -0800 Subject: [PATCH 07/10] Wait for the file watcher events the test asserts instead of OS-specific event counts --- api/src/org/labkey/api/files/FileSystemWatcherImpl.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/api/src/org/labkey/api/files/FileSystemWatcherImpl.java b/api/src/org/labkey/api/files/FileSystemWatcherImpl.java index 3bd1eed2c99..a721719eb05 100644 --- a/api/src/org/labkey/api/files/FileSystemWatcherImpl.java +++ b/api/src/org/labkey/api/files/FileSystemWatcherImpl.java @@ -15,7 +15,6 @@ */ package org.labkey.api.files; -import org.apache.commons.lang3.SystemUtils; import org.apache.logging.log4j.Logger; import org.imca_cat.pollingwatchservice.PathWatchService; import org.imca_cat.pollingwatchservice.PollingWatchService; @@ -565,7 +564,8 @@ public void overflow() assertTrue(FileUtil.createNewFile(b)); assertTrue(FileUtil.createNewFile(c)); - waitForEvents(events, () -> events.get() >= 3); + // Event counts differ by OS, so wait for what the assertions check + waitForEvents(events, () -> created.containsAll(Set.of("a", "b", "c"))); try (PrintWriter pw = PrintWriters.getPrintWriter(a)) { @@ -577,12 +577,12 @@ public void overflow() pw.println("Hello World"); } - waitForEvents(events, () -> events.get() >= (SystemUtils.IS_OS_WINDOWS ? 7 : 5)); + waitForEvents(events, () -> modified.containsAll(Set.of("a", "c"))); assertTrue(a.delete()); assertTrue(b.delete()); - waitForEvents(events, () -> events.get() >= (SystemUtils.IS_OS_WINDOWS ? 11 : 8)); + waitForEvents(events, () -> deleted.containsAll(Set.of("a", "b"))); FileUtil.deleteDir(testFolder); From f4c1325d211b8527722aa27e76d5d310b4a92ba8 Mon Sep 17 00:00:00 2001 From: labkey-jeckels Date: Fri, 20 Nov 2026 15:16:51 -0800 Subject: [PATCH 08/10] Release test studies after deleting their container so MemTracker doesn't report them as leaks --- study/src/org/labkey/study/model/DatasetLsidImportHelper.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/study/src/org/labkey/study/model/DatasetLsidImportHelper.java b/study/src/org/labkey/study/model/DatasetLsidImportHelper.java index baae138c91a..1d7f3e5f624 100644 --- a/study/src/org/labkey/study/model/DatasetLsidImportHelper.java +++ b/study/src/org/labkey/study/model/DatasetLsidImportHelper.java @@ -174,6 +174,9 @@ private static StudyImpl createStudy(TimepointType timepointType, String name) public static void tearDown() { JunitUtil.deleteTestContainer(); + // MemTracker reports studies still referenced after their container is deleted as leaks + _visitStudy = null; + _dateStudy = null; } @Test From 52c61a62e58669f1edef82608de02f088346ba46 Mon Sep 17 00:00:00 2001 From: labkey-jeckels Date: Sun, 22 Nov 2026 17:25:00 -0800 Subject: [PATCH 09/10] Address review findings in test helpers and server tests --- .../org/labkey/api/data/ConnectionUsage.java | 3 +- .../api/data/RepeatedCommitTaskMonitor.java | 3 +- .../org/labkey/api/data/RequestTestUtil.java | 5 +- .../labkey/api/mcp/AbstractAgentAction.java | 98 +++++++++---------- api/src/org/labkey/api/util/JunitUtil.java | 7 +- .../dsmiley/httpproxy/LabKeyProxyServlet.java | 3 +- wiki/src/org/labkey/wiki/WikiTOC.java | 2 + 7 files changed, 59 insertions(+), 62 deletions(-) diff --git a/api/src/org/labkey/api/data/ConnectionUsage.java b/api/src/org/labkey/api/data/ConnectionUsage.java index adf17a8e047..6d468912fa3 100644 --- a/api/src/org/labkey/api/data/ConnectionUsage.java +++ b/api/src/org/labkey/api/data/ConnectionUsage.java @@ -21,6 +21,7 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import org.junit.function.ThrowingRunnable; import org.labkey.api.util.JunitUtil; import java.sql.Connection; @@ -241,7 +242,7 @@ public void restore() _enabled = _wasEnabled; } - private static Snapshot measureOnNewThread(JunitUtil.ThrowingRunnable block) throws Exception + private static Snapshot measureOnNewThread(ThrowingRunnable block) throws Exception { AtomicReference result = new AtomicReference<>(); JunitUtil.runOnNewThread("ConnectionUsage test", () -> { diff --git a/api/src/org/labkey/api/data/RepeatedCommitTaskMonitor.java b/api/src/org/labkey/api/data/RepeatedCommitTaskMonitor.java index 4d1e836b62a..b758465113b 100644 --- a/api/src/org/labkey/api/data/RepeatedCommitTaskMonitor.java +++ b/api/src/org/labkey/api/data/RepeatedCommitTaskMonitor.java @@ -424,7 +424,8 @@ public void testWarnings() scope().addCommitTask(TestCase.task(i), CommitTaskOption.PRECOMMIT); postCommit.accept(i); }), - new Case("only the queue that runs", 0, false, THRESHOLD, postCommit))) + new Case("only the queue that runs", 0, false, THRESHOLD, postCommit), + new Case("rollback queue runs on rollback", 1, false, THRESHOLD, i -> scope().addCommitTask(TestCase.task(i), CommitTaskOption.POSTROLLBACK)))) assertEquals(c.name(), c.expectedWarnings(), warningsFor(c.commit(), c.count(), c.register())); } diff --git a/api/src/org/labkey/api/data/RequestTestUtil.java b/api/src/org/labkey/api/data/RequestTestUtil.java index 73f1768ecf2..84097999401 100644 --- a/api/src/org/labkey/api/data/RequestTestUtil.java +++ b/api/src/org/labkey/api/data/RequestTestUtil.java @@ -19,6 +19,7 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.junit.Assert; +import org.junit.function.ThrowingRunnable; import org.labkey.api.util.JunitUtil; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; @@ -30,8 +31,8 @@ /** Test helpers for driving in-JVM requests through TransactionFilter and observing their database sessions */ public class RequestTestUtil { - /** Runs body on a new thread that carries this test's TestContext, rethrowing whatever it throws */ - public static void runOnRequestThread(JunitUtil.ThrowingRunnable body) throws Exception + /** {@link JunitUtil#runOnNewThread} with a fixed thread name; doRequest supplies the request itself */ + public static void runOnRequestThread(ThrowingRunnable body) throws Exception { JunitUtil.runOnNewThread("Test request", body); } diff --git a/api/src/org/labkey/api/mcp/AbstractAgentAction.java b/api/src/org/labkey/api/mcp/AbstractAgentAction.java index f3615073f0a..e14c861ebcc 100644 --- a/api/src/org/labkey/api/mcp/AbstractAgentAction.java +++ b/api/src/org/labkey/api/mcp/AbstractAgentAction.java @@ -520,12 +520,21 @@ public void unterminatedFenceFallsBackToHtml() assertFalse("opening fence must be stripped: " + html, html.contains("```")); } - /** - * One parse case. Each expected entry is a segment type, optionally with content: "html~text" (html contains - * text), "sql=SQL", "expression=SQL|JDBCTYPE", "expression=SQL|" (no jdbcType), "expression=SQL" (jdbcType - * unchecked). leak, when non-null, is the expected hasLeakedPayload(). - */ - private record Case(String name, List responses, Boolean leak, boolean noPayloadInProse, String... expected) {} + /** Expected segment: its type, plus whichever content fields the case checks. noJdbcType means the key must be absent. */ + private record Seg(String type, @Nullable String sql, @Nullable String jdbcType, boolean noJdbcType, @Nullable String htmlContains) {} + + private static Seg html() { return new Seg("html", null, null, false, null); } + private static Seg html(String contains) { return new Seg("html", null, null, false, contains); } + private static Seg sql() { return new Seg("sql", null, null, false, null); } + private static Seg sql(String sql) { return new Seg("sql", sql, null, false, null); } + /** jdbcType unchecked */ + private static Seg expr(String sql) { return new Seg("expression", sql, null, false, null); } + private static Seg expr(String sql, String jdbcType) { return new Seg("expression", sql, jdbcType, false, null); } + /** A non-JSON body: raw SQL with no jdbcType */ + private static Seg rawExpr(String sql) { return new Seg("expression", sql, null, true, null); } + + /** One parse case. leak, when non-null, is the expected hasLeakedPayload(). */ + private record Case(String name, List responses, Boolean leak, boolean noPayloadInProse, Seg... expected) {} private static String fence(String tag, String body, String closer) { @@ -542,49 +551,49 @@ public void testBuildSegments() List cases = new ArrayList<>(List.of( new Case("empty response list", List.of(), null, false), new Case("blank messages", List.of("", " "), null, false), - new Case("prose only", List.of("Hello, here is some advice."), null, false, "html~Hello, here is some advice."), - new Case("expression fence", List.of(fence("```expression", expressionPayload("SELECT 1", "INTEGER"), "```")), null, false, "expression=SELECT 1|INTEGER"), + new Case("prose only", List.of("Hello, here is some advice."), null, false, html("Hello, here is some advice.")), + new Case("expression fence", List.of(fence("```expression", expressionPayload("SELECT 1", "INTEGER"), "```")), null, false, expr("SELECT 1", "INTEGER")), // Legacy / model-misbehavior fallback: a non-JSON body is raw SQL with no jdbcType - new Case("raw sql expression body", List.of(fence("```expression", "SELECT 1", "```")), null, false, "expression=SELECT 1|"), - new Case("sql fence", List.of(fence("```sql", "SELECT 1", "```")), null, false, "sql=SELECT 1"), + new Case("raw sql expression body", List.of(fence("```expression", "SELECT 1", "```")), null, false, rawExpr("SELECT 1")), + new Case("sql fence", List.of(fence("```sql", "SELECT 1", "```")), null, false, sql("SELECT 1")), new Case("interleaved prose and fences", List.of(String.join("\n", "Here are two options.", "", "Option A (illustrative):", "```sql", "SELECT a FROM t", "```", "", "Option B (ready to apply):", "```expression", expressionPayload("SELECT b FROM t", "VARCHAR"), "```", "Pick whichever fits.")), - null, false, "html", "sql=SELECT a FROM t", "html", "expression=SELECT b FROM t|VARCHAR", "html"), + null, false, html(), sql("SELECT a FROM t"), html(), expr("SELECT b FROM t", "VARCHAR"), html()), new Case("multiple expression fences", List.of(fence("```expression", expressionPayload("SELECT 1", "INTEGER"), "```") + "\n" + fence("```expression", expressionPayload("SELECT 2", "BIGINT"), "```")), - null, false, "expression=SELECT 1|INTEGER", "expression=SELECT 2|BIGINT"), + null, false, expr("SELECT 1", "INTEGER"), expr("SELECT 2", "BIGINT")), // An unterminated fence costs only its own block: the four-backtick opener is never closed by the shorter closer new Case("unterminated fence keeps later responses", List.of(fence("````expression", expressionPayload("SELECT 1", "INTEGER"), "```"), "Corrected:\n" + fence("```expression", expressionPayload("SELECT 2", "BIGINT"), "```")), - null, false, "html", "expression=SELECT 2|BIGINT"), + null, false, html(), expr("SELECT 2", "BIGINT")), // Only sql/expression are split out; other fenced blocks stay in the html segment - new Case("unknown fence language", List.of(fence("```python", "print('hi')", "```")), null, false, "html"), - new Case("case-insensitive tag", List.of(fence("```EXPRESSION", expressionPayload("SELECT 1", "INTEGER"), "```")), null, false, "expression=SELECT 1|INTEGER"), - new Case("longer closer ends shorter opener", List.of(fence("```expression", payload, "````")), null, false, "expression=Int7 + Int6|INTEGER"), + new Case("unknown fence language", List.of(fence("```python", "print('hi')", "```")), null, false, html()), + new Case("case-insensitive tag", List.of(fence("```EXPRESSION", expressionPayload("SELECT 1", "INTEGER"), "```")), null, false, expr("SELECT 1", "INTEGER")), + new Case("longer closer ends shorter opener", List.of(fence("```expression", payload, "````")), null, false, expr("Int7 + Int6", "INTEGER")), // Per CommonMark the short line is fence content, not a closer, so the block never terminates - new Case("shorter closer doesn't end longer opener", List.of(fence("````expression", payload, "```")), null, false, "html"), + new Case("shorter closer doesn't end longer opener", List.of(fence("````expression", payload, "```")), null, false, html()), // No opening fence, so the payload lands in prose and the user gets no Apply affordance - new Case("leak: missing fence", List.of("Adding Int7 and Int6.\n\n" + payload + "\n```"), true, false, "html"), + new Case("leak: missing fence", List.of("Adding Int7 and Int6.\n\n" + payload + "\n```"), true, false, html()), // The illustrative sql tag renders the payload as a read-only code block - new Case("leak: sql fence", List.of(fence("```sql", payload, "```")), true, false, "sql"), + new Case("leak: sql fence", List.of(fence("```sql", payload, "```")), true, false, sql()), // Narration inside the fence means the body doesn't parse and Apply would write JSON to the field - new Case("leak: non-JSON expression body", List.of(fence("```expression", narrated, "```")), true, false, "expression=" + narrated), + new Case("leak: non-JSON expression body", List.of(fence("```expression", narrated, "```")), true, false, expr(narrated)), // Parses, but with nothing to unpack buildSqlSegment falls back to the raw body - new Case("leak: no expression key", List.of(fence("```expression", noExpressionKey, "```")), true, false, "expression=" + noExpressionKey), + new Case("leak: no expression key", List.of(fence("```expression", noExpressionKey, "```")), true, false, expr(noExpressionKey)), // "jdbcType" is a key on the expression segment itself, not part of the SQL the user sees - new Case("well-formed expression", List.of(fence("```expression", payload, "```")), false, false, "expression=Int7 + Int6|INTEGER"), - new Case("prose without payload", List.of("Which date field should be used?"), false, false, "html"), + new Case("well-formed expression", List.of(fence("```expression", payload, "```")), false, false, expr("Int7 + Int6", "INTEGER")), + new Case("prose without payload", List.of("Which date field should be used?"), false, false, html()), // Only the info string's first word is the tag - new Case("extra info string token", List.of(fence("```expression json", payload, "```")), null, true, "expression=Int7 + Int6|INTEGER"), + new Case("extra info string token", List.of(fence("```expression json", payload, "```")), null, true, expr("Int7 + Int6", "INTEGER")), // Tool calling can split one assistant turn mid-fence; the scan joins the turns so the block still closes - new Case("fence split across responses", List.of("Adding Int7 and Int6.\n\n```expression\n" + payload, "```"), null, true, "html", "expression=Int7 + Int6|INTEGER"), - new Case("multiline sql body", List.of(fence("```expression", expressionPayload(multiline, "VARCHAR"), "```")), null, false, "expression=" + multiline + "|VARCHAR"), + new Case("fence split across responses", List.of("Adding Int7 and Int6.\n\n```expression\n" + payload, "```"), null, true, html(), expr("Int7 + Int6", "INTEGER")), + new Case("multiline sql body", List.of(fence("```expression", expressionPayload(multiline, "VARCHAR"), "```")), null, false, expr(multiline, "VARCHAR")), new Case("responses concatenated in order", List.of("First response prose.", fence("```expression", expressionPayload("SELECT 1", "INTEGER"), "```")), - null, false, "html", "expression=SELECT 1|INTEGER") + null, false, html(), expr("SELECT 1", "INTEGER")) )); for (int n = 3; n <= 6; n++) { String delim = "`".repeat(n); - cases.add(new Case("fence length " + n, List.of(fence(delim + "expression", payload, delim)), null, true, "expression=Int7 + Int6|INTEGER")); + cases.add(new Case("fence length " + n, List.of(fence(delim + "expression", payload, delim)), null, true, expr("Int7 + Int6", "INTEGER"))); } for (Case c : cases) @@ -600,30 +609,17 @@ public void testBuildSegments() } } - private static void assertSegment(String name, JSONObject seg, String expected) + private static void assertSegment(String name, JSONObject seg, Seg expected) { - String[] html = expected.split("~", 2); - if (html.length == 2 && html[0].equals("html")) - { - assertEquals(name, "html", seg.getString("type")); - assertTrue(name + ": " + seg, seg.getString("html").contains(html[1])); - return; - } - String[] typeAndSql = expected.split("=", 2); - assertEquals(name, typeAndSql[0], seg.getString("type")); - if (typeAndSql.length == 1) - return; - int bar = typeAndSql[1].lastIndexOf('|'); - String sql = bar < 0 || typeAndSql[0].equals("sql") ? typeAndSql[1] : typeAndSql[1].substring(0, bar); - assertEquals(name, sql, seg.getString("sql")); - if (bar >= 0 && typeAndSql[0].equals("expression")) - { - String jdbcType = typeAndSql[1].substring(bar + 1); - if (jdbcType.isEmpty()) - assertFalse(name + ": jdbcType should be absent when body isn't JSON", seg.has("jdbcType")); - else - assertEquals(name, jdbcType, seg.getString("jdbcType")); - } + assertEquals(name, expected.type(), seg.getString("type")); + if (expected.htmlContains() != null) + assertTrue(name + ": " + seg, seg.getString("html").contains(expected.htmlContains())); + if (expected.sql() != null) + assertEquals(name, expected.sql(), seg.getString("sql")); + if (expected.jdbcType() != null) + assertEquals(name, expected.jdbcType(), seg.getString("jdbcType")); + if (expected.noJdbcType()) + assertFalse(name + ": jdbcType should be absent when body isn't JSON", seg.has("jdbcType")); } } } diff --git a/api/src/org/labkey/api/util/JunitUtil.java b/api/src/org/labkey/api/util/JunitUtil.java index 1fdacb96ddd..5d308fb08a1 100644 --- a/api/src/org/labkey/api/util/JunitUtil.java +++ b/api/src/org/labkey/api/util/JunitUtil.java @@ -21,6 +21,7 @@ import org.junit.Assert; import org.junit.Assume; import org.junit.AssumptionViolatedException; +import org.junit.function.ThrowingRunnable; import org.labkey.api.collections.CaseInsensitiveHashMap; import org.labkey.api.data.Container; import org.labkey.api.data.ContainerManager; @@ -164,12 +165,6 @@ public static void createRaces(final Runnable runnable, final int threads, final throw new IllegalStateException("Did not execute runnable the expected number of times: " + iterations + " vs. " + expected); } - @FunctionalInterface - public interface ThrowingRunnable - { - void run() throws Exception; - } - /** * Runs body on a new thread that carries the caller's TestContext, waits up to a minute for it, and rethrows * whatever it threw. Use it for work that must not share the test thread's connection, transaction, or request state. diff --git a/api/src/org/mitre/dsmiley/httpproxy/LabKeyProxyServlet.java b/api/src/org/mitre/dsmiley/httpproxy/LabKeyProxyServlet.java index 7bc3af755e5..f50249929d6 100644 --- a/api/src/org/mitre/dsmiley/httpproxy/LabKeyProxyServlet.java +++ b/api/src/org/mitre/dsmiley/httpproxy/LabKeyProxyServlet.java @@ -294,7 +294,8 @@ public void testLaterAssertionWinsRegardlessOfCase() assertHeader(r, ASSERTED_HEADER, "first"); assertHeader(r, ASSERTED_HEADER.toLowerCase(), "second"); }); - assertEquals(List.of((ASSERTED_HEADER + "=second").toLowerCase()), forwarded.stream().map(String::toLowerCase).toList()); + // Header names are case-insensitive; values are not + assertEquals(List.of(ASSERTED_HEADER.toLowerCase() + "=second"), forwarded.stream().map(h -> h.substring(0, h.indexOf('=')).toLowerCase() + h.substring(h.indexOf('='))).toList()); } } } diff --git a/wiki/src/org/labkey/wiki/WikiTOC.java b/wiki/src/org/labkey/wiki/WikiTOC.java index 91754383071..8d73bf05e27 100644 --- a/wiki/src/org/labkey/wiki/WikiTOC.java +++ b/wiki/src/org/labkey/wiki/WikiTOC.java @@ -366,6 +366,7 @@ public void testTocRequiresReadInTargetFolder() throws Exception User user = createUserInRole(_host, ReaderRole.class); String html = renderToc(user); assertTrue("Expected no-permission message, html was: " + html, html.contains(WikiManager.get().getNoPermissionsMessage(user).toString())); + assertFalse("Signed-in user got the guest login prompt, html was: " + html, html.contains(WikiManager.get().getNoPermissionsMessage(User.guest).toString())); assertFalse("Target folder's page leaked into the TOC", html.contains(PAGE_TITLE)); grantRole(user, _target, ReaderRole.class); @@ -375,6 +376,7 @@ public void testTocRequiresReadInTargetFolder() throws Exception grantRole(SecurityManager.getGroup(Group.groupGuests), _host, ReaderRole.class); html = renderToc(User.guest); assertTrue("Expected guest login prompt, html was: " + html, html.contains(WikiManager.get().getNoPermissionsMessage(User.guest).toString())); + assertFalse("Guest got the signed-in no-permission message, html was: " + html, html.contains(WikiManager.get().getNoPermissionsMessage(user).toString())); assertFalse("Target folder's page leaked into the guest TOC", html.contains(PAGE_TITLE)); } From e0407828636131e2944591e40b8354d41cc6134e Mon Sep 17 00:00:00 2001 From: labkey-jeckels Date: Tue, 24 Nov 2026 09:27:07 -0800 Subject: [PATCH 10/10] Code cleanup; remove unneeded Junit actions --- .../api/data/dialect/PostgresSnapshot.java | 3 - api/src/org/labkey/api/util/JunitUtil.java | 8 -- .../labkey/core/junit/JunitController.java | 98 +------------------ query/src/org/labkey/query/sql/Method.java | 4 - 4 files changed, 1 insertion(+), 112 deletions(-) diff --git a/api/src/org/labkey/api/data/dialect/PostgresSnapshot.java b/api/src/org/labkey/api/data/dialect/PostgresSnapshot.java index 6175e3a8be4..24b50362426 100644 --- a/api/src/org/labkey/api/data/dialect/PostgresSnapshot.java +++ b/api/src/org/labkey/api/data/dialect/PostgresSnapshot.java @@ -24,7 +24,6 @@ import org.labkey.api.data.CoreSchema; import org.labkey.api.data.DbSchema; import org.labkey.api.data.SqlSelector; -import org.labkey.api.util.JunitUtil; import org.springframework.dao.DataAccessException; import java.util.Set; @@ -156,8 +155,6 @@ public static class TestCase extends Assert @Test public void testCapture() { - JunitUtil.assumePostgres(); - // JSONObject rejects duplicate keys, so parsing also verifies statement keys are unique JSONObject snapshot = new JSONObject(capture()); diff --git a/api/src/org/labkey/api/util/JunitUtil.java b/api/src/org/labkey/api/util/JunitUtil.java index 5d308fb08a1..91bef051b3a 100644 --- a/api/src/org/labkey/api/util/JunitUtil.java +++ b/api/src/org/labkey/api/util/JunitUtil.java @@ -34,11 +34,9 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; -import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.LinkedList; -import java.util.List; import java.util.Map; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; @@ -212,12 +210,6 @@ public static boolean hasCause(@Nullable Throwable t, Predicate match return false; } - /** Skips the test unless the labkey scope is PostgreSQL */ - public static void assumePostgres() - { - Assume.assumeTrue("Requires PostgreSQL", DbScope.getLabKeyScope().getSqlDialect().isPostgreSQL()); - } - /** Skips the test unless the JVM runs with -ea, for tests of code that only runs inside an assert */ public static void assumeAssertionsEnabled() { diff --git a/core/src/org/labkey/core/junit/JunitController.java b/core/src/org/labkey/core/junit/JunitController.java index f7a7312b87d..aa9350c6389 100644 --- a/core/src/org/labkey/core/junit/JunitController.java +++ b/core/src/org/labkey/core/junit/JunitController.java @@ -16,11 +16,8 @@ package org.labkey.core.junit; -import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; -import org.apache.commons.collections4.IteratorUtils; import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.time.FastDateFormat; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.json.JSONArray; @@ -31,15 +28,12 @@ import org.labkey.api.action.BaseViewAction; import org.labkey.api.action.MutatingApiAction; import org.labkey.api.action.NavTrailAction; -import org.labkey.api.action.PermissionCheckableAction; import org.labkey.api.action.ReadOnlyApiAction; import org.labkey.api.action.SimpleViewAction; import org.labkey.api.action.SpringActionController; import org.labkey.api.jsp.JspTest; import org.labkey.api.security.MethodsAllowed; -import org.labkey.api.security.RequiresNoPermission; import org.labkey.api.security.RequiresSiteAdmin; -import org.labkey.api.security.User; import org.labkey.api.test.TestTimeout; import org.labkey.api.test.TestWhen; import org.labkey.api.util.CPUTimer; @@ -57,15 +51,11 @@ import org.springframework.web.servlet.ModelAndView; import java.io.PrintWriter; -import java.text.DateFormat; -import java.text.Format; import java.util.ArrayList; import java.util.Arrays; -import java.util.Date; import java.util.HashMap; import java.util.LinkedList; import java.util.List; -import java.util.ListIterator; import java.util.Map; import java.util.stream.Collectors; @@ -267,10 +257,6 @@ public ApiResponse execute(Object o, BindException errors) { timeout = testTimeout.value(); } - if (testTimeout != null) - { - timeout = testTimeout.value(); - } TestWhen.When scope = getScope(clazz); // Send back both the class name and the timeout @@ -400,8 +386,7 @@ public void setWhen(String when) { try { - TestWhen.When w = TestWhen.When.valueOf(when); - _scope = w; + _scope = TestWhen.When.valueOf(when); } catch (IllegalArgumentException e) { @@ -435,63 +420,6 @@ private static boolean isLoadableClass(String className) } } - - private static final LinkedList list = new LinkedList<>(); - private static final Format format = FastDateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG); - - @SuppressWarnings({"UnusedDeclaration"}) - @RequiresNoPermission - public static class AliveAction extends SimpleViewAction - { - @Override - public ModelAndView getView(Object o, BindException errors) throws Exception - { - synchronized(AliveAction.class) - { - HttpServletRequest request = getViewContext().getRequest(); - HttpServletResponse response = getViewContext().getResponse(); - TestContext.setTestContext(request, (User) request.getUserPrincipal()); - - Class clazz = findTestClass("org.labkey.api.data.DbSchema$TestCase"); - JunitRunner.RunnerResult result = new JunitRunner.RunnerResult(); - - if (null != clazz) - result = JunitRunner.run(clazz); - - int status = HttpServletResponse.SC_OK; - if (result.junitResult.getFailureCount() != 0 || 0 == result.junitResult.getRunCount()) - status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; - - String time = format.format(new Date()); - String statusString = status + ": " + time + " " + request.getHeader("User-Agent"); - if (list.size() > 20) - list.removeFirst(); - list.add(statusString); - - response.reset(); - response.setStatus(status); - - PrintWriter out = response.getWriter(); - response.setContentType("text/plain"); - - out.println(status == HttpServletResponse.SC_OK ? "OK" : "ERROR"); - out.println(); - out.println("history"); - for (ListIterator it = list.listIterator(list.size()); it.hasPrevious();) - out.println(it.previous()); - - response.flushBuffer(); - return null; - } - } - - @Override - public void addNavTrail(NavTree root) - { - } - } - - private static class TestResultView extends HttpView { private final List> _tests; @@ -607,30 +535,6 @@ public void renderInternal(Object model, PrintWriter out) } } - - @RequiresNoPermission - public static class EchoFormAction extends PermissionCheckableAction - { - @Override - public ModelAndView handleRequest(HttpServletRequest req, HttpServletResponse res) throws Exception - { - PrintWriter out = res.getWriter(); - out.println("
    "); - IteratorUtils.asIterator(req.getParameterNames()).forEachRemaining(name -> { - out.print(""); - out.print(h(name)); - out.println("
    "); - }); - - out.println(""); - return null; - } - } - private static List filterStackTrace(Throwable t) { List lines = new ArrayList<>(); diff --git a/query/src/org/labkey/query/sql/Method.java b/query/src/org/labkey/query/sql/Method.java index 1d1a493cbc4..f4096469afb 100644 --- a/query/src/org/labkey/query/sql/Method.java +++ b/query/src/org/labkey/query/sql/Method.java @@ -20,7 +20,6 @@ import org.apache.commons.lang3.StringUtils; import org.jetbrains.annotations.Nullable; import org.junit.Assert; -import org.junit.Assume; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @@ -68,7 +67,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Set; import java.util.concurrent.Callable; import static org.labkey.query.sql.Method.TimestampDiffInterval.SQL_TSI_FRAC_SECOND; @@ -2216,9 +2214,7 @@ private static String selectWithoutParameters(SQLFragment expr) @Test public void testJsonOperators() { - JunitUtil.assumePostgres(); SqlDialect d = CoreSchema.getInstance().getSqlDialect(); - record Case(String json, String operator, String operand, String expected) {} List cases = List.of( new Case("{\"a\":1}", "->", "a", "1"),