|
1 | 1 | # -*- coding: utf-8 -*-
|
2 | 2 |
|
| 3 | +from functools import wraps |
| 4 | + |
3 | 5 | import pytest
|
4 | 6 | import click
|
5 | 7 |
|
@@ -695,3 +697,55 @@ def cli(foo, bar):
|
695 | 697 | assert "Group 1" in result.output
|
696 | 698 | assert "foo" in result.output
|
697 | 699 | assert "bar" not in result.output
|
| 700 | + |
| 701 | + |
| 702 | +def test_wrapped_functions(runner): |
| 703 | + def make_z(): |
| 704 | + """A unified option interface for making a `z`.""" |
| 705 | + |
| 706 | + def decorator(f): |
| 707 | + @optgroup.group("Group xyz") |
| 708 | + @optgroup.option("-x", type=int) |
| 709 | + @optgroup.option("-y", type=int) |
| 710 | + @wraps(f) |
| 711 | + def new_func(*args, x=0, y=0, **kwargs): |
| 712 | + # Here we handle every detail about how to make a `z` from the given options |
| 713 | + f(*args, z=x + y, **kwargs) |
| 714 | + |
| 715 | + return new_func |
| 716 | + |
| 717 | + return decorator |
| 718 | + |
| 719 | + def make_c(): |
| 720 | + """A unified option interface for making a `c`.""" |
| 721 | + |
| 722 | + def decorator(f): |
| 723 | + @optgroup.group("Group abc") |
| 724 | + @optgroup.option("-a", type=int) |
| 725 | + @optgroup.option("-b", type=int) |
| 726 | + @wraps(f) |
| 727 | + def new_func(*args, a=0, b=0, **kwargs): |
| 728 | + # Here we do the same, but for another object `c` (and many others to come) |
| 729 | + f(*args, c=a * b, **kwargs) |
| 730 | + |
| 731 | + return new_func |
| 732 | + |
| 733 | + return decorator |
| 734 | + |
| 735 | + # Here I want to create a script that has a commen UI to make a `z`. |
| 736 | + # I want to reuse a common set of options for how to make a `z` and don't want |
| 737 | + # to sweat the details. Also, I've decided that I also want a `c` for this script. |
| 738 | + @click.command() |
| 739 | + @make_z() |
| 740 | + @make_c() |
| 741 | + def f(z, c): |
| 742 | + print(z, c) |
| 743 | + |
| 744 | + # Test |
| 745 | + result = runner.invoke(f, ["--help"]) |
| 746 | + assert "Group xyz" in result.output |
| 747 | + assert "-x" in result.output |
| 748 | + assert "-y" in result.output |
| 749 | + assert "Group abc" in result.output |
| 750 | + assert "-a" in result.output |
| 751 | + assert "-b" in result.output |
0 commit comments