139 lines
2.9 KiB
Python
139 lines
2.9 KiB
Python
# Copyright (C) 2023 Entr'ouvert
|
|
#
|
|
# This program is free software: you can redistribute it and/or modify it
|
|
# under the terms of the GNU Affero General Public License as published
|
|
# by the Free Software Foundation, either version 3 of the License, or
|
|
# (at your option) any later version.
|
|
#
|
|
# This program is distributed in the hope that it will be useful,
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
# GNU Affero General Public License for more details.
|
|
#
|
|
# You should have received a copy of the GNU Affero General Public License
|
|
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
|
|
|
import threading
|
|
|
|
from django.core.management import BaseCommand, call_command
|
|
from django.db import transaction
|
|
|
|
from passerelle.utils.defer import (
|
|
run_later,
|
|
run_later_if_in_transaction,
|
|
run_later_middleware,
|
|
run_later_scope,
|
|
)
|
|
|
|
|
|
def test_run_later():
|
|
x = []
|
|
|
|
def f():
|
|
x.append(1)
|
|
|
|
run_later(f)
|
|
assert x == [1]
|
|
with run_later_scope():
|
|
run_later(f)
|
|
assert x == [1]
|
|
assert x == [1, 1]
|
|
|
|
|
|
def test_run_later_nested():
|
|
x = []
|
|
|
|
def f():
|
|
x.append(1)
|
|
|
|
run_later(f)
|
|
assert x == [1]
|
|
with run_later_scope():
|
|
with run_later_scope():
|
|
run_later(f)
|
|
assert x == [1]
|
|
# f is run by the most enclosing scope
|
|
assert x == [1, 1]
|
|
|
|
|
|
def test_run_threading():
|
|
x = []
|
|
|
|
def f(i):
|
|
x.append(i)
|
|
|
|
run_later(f, 1)
|
|
assert x == [1]
|
|
with run_later_scope():
|
|
run_later(f, 2)
|
|
assert x == [1]
|
|
thread = threading.Thread(target=run_later, args=(f, 3))
|
|
thread.start()
|
|
thread.join()
|
|
assert x == [1, 3]
|
|
|
|
assert x == [1, 3, 2]
|
|
|
|
|
|
def test_run_later_if_in_transaction(transactional_db):
|
|
x = []
|
|
|
|
def f():
|
|
x.append(1)
|
|
|
|
run_later_if_in_transaction(f)
|
|
assert x == [1]
|
|
with run_later_scope():
|
|
run_later_if_in_transaction(f)
|
|
assert x == [1, 1]
|
|
with transaction.atomic():
|
|
run_later_if_in_transaction(f)
|
|
assert x == [1, 1]
|
|
assert x == [1, 1]
|
|
assert x == [1, 1, 1]
|
|
|
|
|
|
def test_middleware(rf):
|
|
x = []
|
|
|
|
def view1(request):
|
|
def f():
|
|
x.append(1)
|
|
|
|
assert x == []
|
|
run_later(f)
|
|
assert x == [1]
|
|
|
|
request = rf.get('/')
|
|
view1(request)
|
|
assert x == [1]
|
|
|
|
x = []
|
|
|
|
def view2(request):
|
|
def f():
|
|
x.append(1)
|
|
|
|
assert x == []
|
|
run_later(f)
|
|
assert x == []
|
|
|
|
run_later_middleware(view2)(request)
|
|
assert x == [1]
|
|
|
|
|
|
def test_base_command():
|
|
x = []
|
|
|
|
def f():
|
|
x.append(1)
|
|
|
|
class MyCommand(BaseCommand):
|
|
def handle(self, *args, **kwargs):
|
|
assert x == []
|
|
run_later(f)
|
|
assert x == []
|
|
|
|
call_command(MyCommand())
|
|
assert x == [1]
|