Skip to content

Commit

Permalink
Fix for references with simple test case added
Browse files Browse the repository at this point in the history
  • Loading branch information
azimov committed Sep 13, 2023
1 parent 6935ccf commit 903bb76
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 3 deletions.
5 changes: 3 additions & 2 deletions R/SubsetDefinitions.R
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ CohortSubsetDefinition <- R6::R6Class(
#' @param overwrite if a subset operator of the same ID is present, replace it with a new definition
addSubsetOperator = function(subsetOperator) {
checkmate::assertR6(subsetOperator, "SubsetOperator")
private$.subsetOperators <- c(private$.subsetOperators, subsetOperator)
private$.subsetOperators <- c(private$.subsetOperators, subsetOperator$clone(deep = TRUE))
self
},

Expand Down Expand Up @@ -189,7 +189,8 @@ CohortSubsetDefinition <- R6::R6Class(
#' @field subsetOperators list of subset operations
subsetOperators = function(subsetOperators) {
if (missing(subsetOperators)) {
return(private$.subsetOperators)
# We don't want to return references to the operators in case users modify them after this
return(lapply(private$.subsetOperators, function(x) { x$clone(deep = TRUE) }))
}

checkmate::assertList(subsetOperators, types = "SubsetOperator")
Expand Down
6 changes: 5 additions & 1 deletion tests/testthat/test-Subsets.R
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,11 @@ test_that("Subset definition", {
checkmate::expect_list(listDef)
expect_equal(length(subsetDef$subsetOperators), length(listDef$subsetOperators))
checkmate::expect_character(subsetDef$toJSON())

# check reference isn't passed
operators <- subsetDef$subsetOperators
# Operators should not be modfiable after being added to the subset definition
operators[[1]]$cohortIds <- 22
expect_equal(subsetDef$subsetOperators[[1]]$cohortIds, 11)

# Check serialized version is identical to code defined version
subsetDef2 <- CohortSubsetDefinition$new(subsetDef$toJSON())
Expand Down

0 comments on commit 903bb76

Please sign in to comment.