tests/testthat/test-convert_inputs.R

# Tests for convert_to_matrix()

test_that("convert_to_matrix handles data frame edge list", {
  edge_df <- data.frame(
    source = c("A", "B"),
    target = c("B", "C"),
    stringsAsFactors = FALSE
  )

  result <- convert_to_matrix(edge_df, from = "source", to = "target")

  expect_true(is.matrix(result))
  expect_equal(nrow(result), 3)
  expect_equal(ncol(result), 3)
  expect_equal(result["A", "B"], 1)
  expect_equal(result["B", "C"], 1)
  expect_equal(result["A", "C"], 0)
})

test_that("convert_to_matrix handles matrix edge list", {
  edge_mat <- matrix(c("X", "Y", "Y", "Z"), ncol = 2, byrow = TRUE)

  result <- convert_to_matrix(edge_mat)

  expect_true(is.matrix(result))
  expect_equal(result["X", "Y"], 1)
  expect_equal(result["Y", "Z"], 1)
})

test_that("convert_to_matrix returns adjacency matrix with dimnames", {
  adj <- matrix(c(0, 1, 0, 0), nrow = 2)

  result <- convert_to_matrix(adj)

  # Result should have dimnames (added by validation)
  expect_true(is.matrix(result))
  expect_equal(nrow(result), 2)
  expect_equal(ncol(result), 2)
  expect_true(!is.null(rownames(result)))
  expect_true(!is.null(colnames(result)))
})

test_that("convert_to_matrix handles numeric column indices", {
  edge_df <- data.frame(
    col1 = c("A", "B"),
    col2 = c("B", "C"),
    stringsAsFactors = FALSE
  )

  result <- convert_to_matrix(edge_df, from = 1, to = 2)

  expect_equal(result["A", "B"], 1)
  expect_equal(result["B", "C"], 1)
})

test_that("convert_to_matrix respects predefined nodes", {
  edge_df <- data.frame(
    source = "A",
    target = "B",
    stringsAsFactors = FALSE
  )

  result <- convert_to_matrix(edge_df, from = "source", to = "target",
                              nodes = c("A", "B", "C", "D"))

  expect_equal(nrow(result), 4)
  expect_equal(ncol(result), 4)
  expect_equal(rownames(result), c("A", "B", "C", "D"))
})

test_that("convert_to_matrix validates input", {
  # Square matrix with non-binary values should warn but not error
  expect_warning(
    convert_to_matrix(matrix(1:9, nrow = 3, ncol = 3)),
    "non-binary values"
  )

  # Non-square, non-edge-list matrix
  expect_error(convert_to_matrix(matrix(1:6, nrow = 2, ncol = 3)),
               "two-column edge list or a square adjacency matrix")

  # Invalid input type
  expect_error(convert_to_matrix(list(a = 1, b = 2)),
               "Unsupported input type")
})

Try the ISMtools package in your browser

Any scripts or data that you put into this service are public.

ISMtools documentation built on March 13, 2026, 1:06 a.m.