Skip to content

Commit

Permalink
Add client atexit shutdown hook on process exit
Browse files Browse the repository at this point in the history
Signed-off-by: Darach Ennis <[email protected]>
  • Loading branch information
darach committed Sep 9, 2024
1 parent 0e111d1 commit 3be6dc9
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/axiom_py/client.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Client provides an easy-to use client library to connect to Axiom."""

import ndjson
import atexit
import gzip
import ujson
import os
Expand Down Expand Up @@ -128,6 +129,7 @@ class Client: # pylint: disable=R0903
datasets: DatasetsClient
users: UsersClient
annotations: AnnotationsClient
is_closed: bool # track if the client has been closed ( for tests )

def __init__(
self,
Expand Down Expand Up @@ -175,6 +177,14 @@ def __init__(
self.users = UsersClient(self.session)
self.annotations = AnnotationsClient(self.session, self.logger)

# wrap shutdown hook in a lambda passing in self as a ref
atexit.register(lambda: self.shutdown_hook())
self.is_closed = False

def shutdown_hook(self):
self.session.close()
self.is_closed = True

def ingest(
self,
dataset: str,
Expand Down
13 changes: 13 additions & 0 deletions tests/test_client.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
"""This module contains the tests for the axiom client."""

import sys
import os
import unittest
from unittest.mock import patch
import gzip
import ujson
import rfc3339
Expand Down Expand Up @@ -224,6 +226,17 @@ def test_step005_complex_query(self):
agg = res.buckets.totals[0].aggregations[0]
self.assertEqual("event_count", agg.op)

@patch("sys.exit")
def test_client_shutdown_atexit(self, mock_exit):
"""Test client shutdown atexit"""
# Use the mock to test the firing mechanism
self.assertEqual(self.client.is_closed, False)
sys.exit()
mock_exit.assert_called_once()
# Use the hook implementation to assert the client is closed closed
self.client.shutdown_hook()
self.assertEqual(self.client.is_closed, True)

@classmethod
def tearDownClass(cls):
"""A teardown that checks if the dataset still exists and deletes it,
Expand Down

0 comments on commit 3be6dc9

Please sign in to comment.