import functools
import pywintypes


def use_worksheet(ws_name):
    """Decorator to wrap ExcelWorkbookTestCase tests. Before running the test body,
    the active worksheet is changed to that with the name specified."""
    def _wrap_set_worksheet(f):

        @functools.wraps(f)
        def _wrapped(self, *args, **kwargs):
            xlwb = self.workbook.xlWorkbook
            try:
                xlSheet = xlwb.Sheets(ws_name)
                xlSheet.Activate()
            except pywintypes.com_error as e:
                raise ValueError("Failed to change active worksheet in @use_worksheet", ws_name, e)
            f(self, *args, **kwargs)

        return _wrapped
    return _wrap_set_worksheet