Skip to content

Commit

Permalink
Test ExtensibleRate memory management
Browse files Browse the repository at this point in the history
  • Loading branch information
speth authored and ischoegl committed Jan 21, 2023
1 parent 5e5e7df commit 19d55aa
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
24 changes: 24 additions & 0 deletions test/python/test_reaction.py
Expand Up @@ -2,6 +2,7 @@
from pathlib import Path
import sys
import textwrap
import gc

import cantera as ct
import numpy as np
Expand Down Expand Up @@ -1619,6 +1620,29 @@ def test_invalid_module(self):
with pytest.raises(ct.CanteraError, match="SyntaxError"):
ct.Solution(yaml=self._input_template.format(module="user_ext_invalid"))

def test_memory_management(self):
# Make sure objects are being correctly cleaned up and not stuck in
# mixed Python/C++ ownership cycles
import user_ext

gc.collect()
initialRate = user_ext.SquareRate.use_count[0]
initialData = user_ext.SquareRateData.use_count[0]

def run():
gas = ct.Solution("extensible-reactions.yaml", transport_model=None)
assert gas.forward_rate_constants[0] > 0
assert user_ext.SquareRate.use_count[0] == initialRate + 1
assert user_ext.SquareRateData.use_count[0] == initialData + 1

run()

# The number of instances for both classes should go back to its previous value
# after deleting the Solution (may not be zero due to other Solution instances)
# held by other test classes
gc.collect()
assert user_ext.SquareRate.use_count[0] == initialRate
assert user_ext.SquareRateData.use_count[0] == initialData

class InterfaceReactionTests(ReactionTests):
# test suite for surface reaction expressions
Expand Down
15 changes: 15 additions & 0 deletions test/python/user_ext.py
Expand Up @@ -2,17 +2,32 @@

class SquareRateData(ct.ExtensibleRateData):
__slots__ = ("Tsquared",)
use_count = [0] # used in test for memory leak

def __init__(self):
self.use_count[0] += 1

def update(self, gas):
self.Tsquared = gas.T**2
return True

def __del__(self):
self.use_count[0] -= 1

@ct.extension(name="square-rate", data=SquareRateData)
class SquareRate(ct.ExtensibleRate):
__slots__ = ("A",)
use_count = [0] # used in test for memory leak

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.use_count[0] += 1

def set_parameters(self, node, units):
self.A = node["A"]

def eval(self, data):
return self.A * data.Tsquared

def __del__(self):
self.use_count[0] -= 1

0 comments on commit 19d55aa

Please sign in to comment.