File: test-interrupts.R

package info (click to toggle)
r-cran-reticulate 1.41.0.1%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 3,088 kB
  • sloc: cpp: 5,154; python: 620; sh: 13; makefile: 2
file content (196 lines) | stat: -rw-r--r-- 4,825 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196

test_that("Running Python scripts can be interrupted", {

  skip_on_cran()

  time <- import("time", convert = TRUE)

  # interrupt this process shortly
  interruptor <- callr::r_bg(args = list(pid = Sys.getpid()), function(pid) {
    Sys.sleep(1)
    system2("kill", c("-s", "INT", pid))
    # ps::ps_interrupt(ps::ps_handle(pid))
  })

  # tell Python to sleep
  before <- Sys.time()
  interrupted <- tryCatch(time$sleep(5), interrupt = identity)
  after <- Sys.time()

  # check that we caught an interrupt
  expect_s3_class(interrupted, "interrupt")

  # check that we took a small amount of time
  diff <- difftime(after, before, units = "secs")
  expect_true(diff < 2)

})


test_that("interrupts work when Python is running", {

  skip_on_cran()

  p <- callr::r_bg(args = list(python = py_exe()), function(python) {
    library(reticulate)
    use_python(python)
    get_frames <- function() {
      r_stack <- sys.calls()
      py_stack <- py_capture_output(py_run_string("from traceback import print_stack; print_stack()"))
      list(r = r_stack, py = py_stack)
    }
    frames_before <- get_frames()

    py_run_string("print('Initialized Python')")
    tryCatch({
      py_run_string(glue::trim("
        print('Starting', flush=True)
        i = 0
        while True:
          i += 1
        "))
    }, interrupt = function(e) {
      cat("Caught interrupt; ")
    })

    # confirm that the python stack was unwound correctly
    frames_after <- get_frames()
    stopifnot(identical(frames_before, frames_after))

    cat("Finished!")
  })


  p$poll_io(5000)
  expect_identical(p$read_output_lines(1), "Initialized Python")

  p$poll_io(500)
  expect_identical(p$read_output_lines(1), "Starting")

  p$poll_io(500)
  expect_identical(p$read_output(), "")

  p$interrupt()
  p$wait()

  expect_identical(p$get_exit_status(), 0L)
  expect_identical(p$read_all_output(), "Caught interrupt; Finished!")

})


test_that("interrupts can be caught by Python", {
  skip_on_cran()

  p <- callr::r_bg(args = list(python = py_exe()), function(python) {
    Sys.setenv(RETICULATE_PYTHON = python)
    library(reticulate)
    get_frames <- function() {
      r_stack <- sys.calls()
      py_stack <- py_capture_output(py_run_string("from traceback import print_stack; print_stack()"))
      list(r = r_stack, py = py_stack)
    }
    frames_before <- get_frames()
    py_run_string("print('Initialized Python')")

    py_run_string(glue::trim("
      print('Starting', flush=True)
      try:
        i = 0
        while True:
          i += 1
      except KeyboardInterrupt:
        print('Caught interrupt; ', end='')
      finally:
        print('Running finally; ', end='')

      print('Python finished; ', end = '')
      "))

    # confirm that the python stack was unwound correctly
    frames_after <- get_frames()
    stopifnot(identical(frames_before, frames_after))

    cat("R Finished!")
  })

  p$poll_io(5000)
  expect_identical(p$read_output_lines(1), "Initialized Python")

  p$poll_io(500)
  expect_identical(p$read_output_lines(1), "Starting")

  p$poll_io(500)
  expect_identical(p$read_output(), "")

  p$interrupt()
  p$wait()

  expect_identical(p$get_exit_status(), 0L)
  expect_identical(
    p$read_all_output(),
    "Caught interrupt; Running finally; Python finished; R Finished!")

})


test_that("interrupts can be caught by Python while calling R", {
  skip_on_cran()

  p <- callr::r_bg(args = list(python = py_exe()), function(python) {
    Sys.setenv(RETICULATE_PYTHON = python)
    library(reticulate)

    get_frames <- function() {
      r_stack <- sys.calls()
      py_stack <- py_capture_output(py_run_string("from traceback import print_stack; print_stack()"))
      list(r = r_stack, py = py_stack)
    }
    frames_before <- get_frames()

    py_run_string("print('Initialized Python')")

    py$run_forever_r_func <- function() {
      i <- 0
      repeat {
        i <- i + 1
      }
    }

    py_run_string(glue::trim("
      print('Starting', flush=True)
      try:
        run_forever_r_func()
      except KeyboardInterrupt as e:
        print('Caught interrupt; ', end='')
      finally:
        print('Running finally; ', end='')

      print('Python finished; ', end = '')
      "))

    # confirm that the python stack was unwound correctly
    frames_after <- get_frames()
    stopifnot(identical(frames_before, frames_after))

    cat("R Finished!")
  })

  p$poll_io(5000)
  expect_identical(p$read_output_lines(1), "Initialized Python")

  p$poll_io(500)
  expect_identical(p$read_output_lines(1), "Starting")

  p$poll_io(500)
  expect_identical(p$read_output(), "")

  p$interrupt()
  p$wait()

  expect_identical(p$get_exit_status(), 0L)
  expect_identical(
    p$read_all_output(),
    "Caught interrupt; Running finally; Python finished; R Finished!")

})