Unverified Commit c4d25a67 authored by Peterson, Peter's avatar Peterson, Peter Committed by GitHub
Browse files

Merge pull request #33091 from peterfpeterson/Add_missing_pytest_files_ornlnext

Add missing pytest files ornlnext
parents de467634 5e655e0d
......@@ -19,10 +19,14 @@ repos:
args: [--allow-multiple-documents]
- repo: https://github.com/mantidproject/pre-commit-hooks.git
rev: 8809bbab4c8b9609f559e2428e6255e9407c3efe
rev: 511456a60b0c6cbb079e64a7cd8e3302f04859a6
hooks:
- id: clang-format
exclude: Testing/Tools/cxxtest|tools
- id: cmake-missing-pytest-files
# Exclude sphinx / template file
exclude: test_doctest.py|python_export_maker.py
- repo: https://github.com/cheshirekow/cmake-format-precommit
rev: v0.6.13
......
......@@ -7,10 +7,12 @@
# pylint: disable=invalid-name, anomalous-backslash-in-string, attribute-defined-outside-init
from mantid.api import IFunction1D, FunctionFactory
from mantid.kernel import PhysicalConstants
import numpy as np
class Redfield(IFunction1D):
class Redfield(IFunction1D):
def category(self):
return "Muon\\MuonModelling"
......@@ -24,8 +26,8 @@ class Redfield(IFunction1D):
A0 = self.getParameterValue("A0")
Hloc = self.getParameterValue("Hloc")
tau = self.getParameterValue("Tau")
gmu = 0.01355342
return A0 * 2 * (gmu * Hloc) ** 2 * tau / (1 + (gmu * x * tau) ** 2)
gmu = PhysicalConstants.MuonGyromagneticRatio
return A0 * 2 * np.power((gmu * Hloc), 2) * tau / (1 + np.power((gmu * x * tau), 2))
FunctionFactory.subscribe(Redfield)
# mantid.dataobjects tests
set(TEST_PY_FILES EventListTest.py Workspace2DPickleTest.py)
set(TEST_PY_FILES EventListTest.py SpecialWorkspace2DTest.py Workspace2DPickleTest.py)
check_tests_valid(${CMAKE_CURRENT_SOURCE_DIR} ${TEST_PY_FILES})
......
......@@ -2,7 +2,7 @@
add_subdirectory(nomad)
set(TEST_PY_FILES absorptioncorrutilsTest.py dgsTest.py)
set(TEST_PY_FILES absorptioncorrutilsTest.py deprecatorTest.py dgsTest.py pathTest.py)
check_tests_valid(${CMAKE_CURRENT_SOURCE_DIR} ${TEST_PY_FILES})
......
......@@ -6,6 +6,8 @@
# SPDX - License - Identifier: GPL - 3.0 +
# package imports
from io import StringIO
from mantid.api import PythonAlgorithm
from mantid.kernel import ConfigService, logger
from mantid.utils.deprecator import deprecated_algorithm
......@@ -18,54 +20,69 @@ import tempfile
import unittest
class deprecatorTest(unittest.TestCase):
@deprecated_algorithm('MyNewAlg', '2020-12-25')
class MyOldAlg(PythonAlgorithm):
def category(self):
return 'Inelastic\\Reduction'
def PyInit(self):
self.declareProperty('Meaning', 42, 'Assign a meaning to the Universe')
def PyExec(self):
logger.notice(f'The meaning of the Universe is {self.getPropertyValue("Meaning")}')
def test_deprecated_algorithm(self):
class RedirectStdOut:
r"""redirect logging messages to a file"""
# Adapted from https://stackoverflow.com/a/45899925
@deprecated_algorithm('MyNewAlg', '2020-12-25')
class MyOldAlg(PythonAlgorithm):
CONFIG_KEY = "logging.channels.consoleChannel.class"
def category(self):
return 'Inelastic\\Reduction'
def __init__(self):
self._stdout = None
self._string_io = None
self._original_config = None
self._config = ConfigService.Instance()
def PyInit(self):
self.declareProperty('Meaning', 42, 'Assign a meaning to the Universe')
def __enter__(self):
self._original_config = self._config[self.CONFIG_KEY]
self._stdout = sys.stdout
sys.stdout = self._string_io = StringIO()
# redirect log messages to log_file
self._config[self.CONFIG_KEY] = 'PythonStdoutChannel'
return self
def PyExec(self):
logger.notice(f'The meaning of the Universe is {self.getPropertyValue("Meaning")}')
def __exit__(self, exc_type, exc_val, exc_tb):
sys.stdout = self._stdout
self._config[self.CONFIG_KEY] = self._original_config
@contextmanager
def backup_environment():
r"""redirect logging messages to a file"""
try:
# backup the logging channel and sys.stdout
config = ConfigService.Instance()
backup = dict(channel=config['logging.channels.consoleChannel.class'],
stdout=sys.stdout)
# redirect log messages to log_file
config['logging.channels.consoleChannel.class'] = 'PythonStdoutChannel'
_, log_file = tempfile.mkstemp(suffix='.log')
sys.stdout = open(log_file, 'w', buffering=1)
yield log_file
finally:
# restore the loggin channel and sys.stdout
config['logging.channels.consoleChannel.class'] = backup['channel']
sys.stdout = backup['stdout']
os.remove(log_file) # delete the temporay log file
def __str__(self):
return self._string_io.getvalue()
with backup_environment() as log_file:
class DeprecatorTest(unittest.TestCase):
@staticmethod
def _exec_alg(log_type: str) -> str:
config = ConfigService.Instance()
original_conf = config['algorithms.deprecated']
with RedirectStdOut() as log_file:
alg = MyOldAlg()
alg.initialize()
alg.setProperty("Meaning", 42)
config = ConfigService.Instance()
config['algorithms.deprecated'] = 'Raise'
config['algorithms.deprecated'] = log_type
alg.execute()
self.assertTrue('Error in execution of algorithm MyOldAlg' in open(log_file, 'r').read())
config['algorithms.deprecated'] = 'Log'
alg.execute() # use alias, log error message
self.assertTrue(' Algorithm "MyOldAlg" is deprecated' in open(log_file, 'r').read())
config['algorithms.deprecated'] = original_conf
return str(log_file)
def test_deprecated_algorithm_raise(self):
log_file = self._exec_alg("raise")
self.assertTrue('Error in execution of algorithm MyOldAlg' in log_file)
def test_deprecated_algorithm_log(self):
log_file = self._exec_alg("log")
self.assertTrue(' Algorithm "MyOldAlg" is deprecated' in log_file)
if __name__ == "__main__":
......
......@@ -14,6 +14,8 @@ set(TEST_PY_FILES
CalculateFluxTest.py
CalculateSampleTransmissionTest.py
CheckForSampleLogsTest.py
CleanFileCacheTest.py
ClipPeaksTest.py
ConjoinSpectraTest.py
ConvertQtoHKLMDHistoTest.py
ConvertWANDSCDtoQTest.py
......@@ -23,6 +25,7 @@ set(TEST_PY_FILES
CorrectLogTimesTest.py
CreateLeBailFitInputTest.py
CorrectTOFTest.py
CreateCacheFilenameTest.py
CreateWorkspaceTest.py
CropWorkspaceForMDNormTest.py
CylinderPaalmanPingsCorrection2Test.py
......@@ -34,6 +37,7 @@ set(TEST_PY_FILES
DSFinterpTest.py
EnggCalibrateFullTest.py
EnggCalibrateTest.py
EnggEstimateFocussedBackgroundTest.py
EnggFitTOFFromPeaksTest.py
EnggFitPeaksTest.py
EnggFocusTest.py
......@@ -44,6 +48,8 @@ set(TEST_PY_FILES
ExportSpectraMaskTest.py
FilterLogByTimeTest.py
FitGaussianTest.py
FindGoniometerFromUBTest.py
FindGlobalBMatrixTest.py
FitIncidentSpectrumTest.py
FractionalIndexingTest.py
GenerateLogbookTest.py
......@@ -56,6 +62,7 @@ set(TEST_PY_FILES
HB3APredictPeaksTest.py
HFIRCalculateGoniometerTest.py
HFIRSANS2WavelengthTest.py
IndexPeaksTest.py
IndirectTransmissionTest.py
IndexSatellitePeaksTest.py
LeadPressureCalcTest.py
......
......@@ -6,6 +6,8 @@
# SPDX - License - Identifier: GPL - 3.0 +
#pylint: disable=invalid-name,too-many-public-methods,too-many-arguments
import unittest
from pathlib import Path
from mantid.kernel import *
from mantid.api import *
from testhelpers import run_algorithm
......@@ -36,7 +38,7 @@ class CreateCacheFilename(unittest.TestCase):
# Verify ....
expected = os.path.join(
ConfigService.getUserPropertiesDir(), "cache",
"%s.nxs" % hashlib.sha1("a=3").hexdigest()
"%s.nxs" % hashlib.sha1("a=3".encode('utf-8')).hexdigest()
)
self.assertEqual(
alg_test.getPropertyValue("OutputFilename"),
......@@ -52,7 +54,7 @@ class CreateCacheFilename(unittest.TestCase):
# Verify ....
expected = os.path.join(
ConfigService.getUserPropertiesDir(), "cache",
"%s.nxs" % hashlib.sha1("a=3").hexdigest()
"%s.nxs" % hashlib.sha1("a=3".encode('utf-8')).hexdigest()
)
self.assertEqual(
alg_test.getPropertyValue("OutputFilename"),
......@@ -63,12 +65,8 @@ class CreateCacheFilename(unittest.TestCase):
"""CreateCacheFilename: wrong input
"""
# Execute
alg_test = run_algorithm(
"CreateCacheFilename",
)
# executed?
self.assertFalse(alg_test.isExecuted())
return
with self.assertRaises(RuntimeError):
run_algorithm("CreateCacheFilename",)
def test_glob(self):
"""CreateCacheFilename: globbing
......@@ -95,7 +93,7 @@ class CreateCacheFilename(unittest.TestCase):
s = ','.join(sorted( ['%s=3' % p for p in aprops] ))
expected = os.path.join(
ConfigService.getUserPropertiesDir(), "cache",
"%s.nxs" % hashlib.sha1(s).hexdigest()
"%s.nxs" % hashlib.sha1(s.encode('utf-8')).hexdigest()
)
self.assertEqual(
alg_test.getPropertyValue("OutputFilename"),
......@@ -115,7 +113,7 @@ class CreateCacheFilename(unittest.TestCase):
# Verify ....
expected = os.path.join(
ConfigService.getUserPropertiesDir(), "cache",
"%s.nxs" % hashlib.sha1("a=1,b=2").hexdigest()
"%s.nxs" % hashlib.sha1("a=1,b=2".encode('utf-8')).hexdigest()
)
self.assertEqual(
alg_test.getPropertyValue("OutputFilename"),
......@@ -147,7 +145,7 @@ class CreateCacheFilename(unittest.TestCase):
s = ','.join(sorted( ['%s=fish' % p for p in aprops] + other_props ))
expected = os.path.join(
ConfigService.getUserPropertiesDir(), "cache",
"%s.nxs" % hashlib.sha1(s).hexdigest()
"%s.nxs" % hashlib.sha1(s.encode('utf-8')).hexdigest()
)
self.assertEqual(
alg_test.getPropertyValue("OutputFilename"),
......@@ -168,7 +166,7 @@ class CreateCacheFilename(unittest.TestCase):
# Verify ....
expected = os.path.join(
ConfigService.getUserPropertiesDir(), "cache",
"vanadium_%s.nxs" % hashlib.sha1("a=1,b=2").hexdigest()
"vanadium_%s.nxs" % hashlib.sha1("a=1,b=2".encode('utf-8')).hexdigest()
)
self.assertEqual(
alg_test.getPropertyValue("OutputFilename"),
......@@ -187,12 +185,9 @@ class CreateCacheFilename(unittest.TestCase):
# executed?
self.assertTrue(alg_test.isExecuted())
# Verify ....
expected = os.path.join(
"my_cache",
"%s.nxs" % hashlib.sha1("a=1,b=2").hexdigest()
)
expected = f"{hashlib.sha1('a=1,b=2'.encode('utf-8')).hexdigest()}.nxs"
self.assertEqual(
alg_test.getPropertyValue("OutputFilename"),
Path(alg_test.getPropertyValue("OutputFilename")).name,
expected)
return
......
......@@ -36,10 +36,10 @@ class FindGlobalBMatrixTest(unittest.TestCase):
def test_finds_average_lattice_parameter(self):
# create two peak tables with UB corresponding to different lattice constant, a
peaks1 = CreatePeaksWorkspace(InstrumentWorkspace=self.ws, NumberOfPeaks=0, OutputWorkspace="SXD_peaks1")
UB = np.diag([1.0/3.8, 0.25, 0.1]) # alatt = [3.8, 4, 10]
UB = np.diag([1.0 / 3.9, 0.25, 0.1]) # alatt = [3.9, 4, 10]
SetUB(peaks1, UB=UB)
peaks2 = CreatePeaksWorkspace(InstrumentWorkspace=self.ws, NumberOfPeaks=0, OutputWorkspace="SXD_peaks2")
UB = np.diag([1.0/4.2, 0.25, 0.1]) # alatt = [4.2, 4, 10]
UB = np.diag([1.0 / 4.1, 0.25, 0.1]) # alatt = [4.1, 4, 10]
SetUB(peaks2, UB=UB)
# Add some peaks
add_peaksHKL([peaks1, peaks2], range(0, 3), range(0, 3), 4)
......@@ -48,7 +48,7 @@ class FindGlobalBMatrixTest(unittest.TestCase):
Tolerance=0.15)
# check lattice - should have average a=4.0
self.assert_lattice([peaks1, peaks2], 4.0, 4.0, 10.0, 90.0, 90.0, 90.0, delta_latt=2e-2, delta_angle=2.5e-1)
self.assert_lattice([peaks1, peaks2], 4.0, 4.0, 10.0, 90.0, 90.0, 90.0, delta_latt=5e-2, delta_angle=2.5e-1)
self.assert_matrix([peaks1], getBMatrix(peaks2), getBMatrix, delta=1e-10) # should have same B matrix
self.assert_matrix([peaks1, peaks2], np.eye(3), getUMatrix, delta=5e-2)
......
......@@ -4,55 +4,68 @@
# NScD Oak Ridge National Laboratory, European Spallation Source,
# Institut Laue - Langevin & CSNS, Institute of High Energy Physics, CAS
# SPDX - License - Identifier: GPL - 3.0 +
from mantid.simpleapi import Load, FindUBUsingIndexedPeaks, IndexPeaks
from mantid.simpleapi import (Load, IndexPeaks, AnalysisDataService, LoadEmptyInstrument, PredictPeaks, SetUB,
PredictSatellitePeaks, CombinePeaksWorkspaces)
import unittest
import numpy as np
import numpy.testing as npt
class IndexPeaksTest(unittest.TestCase):
"""
The purpose of the testing is to ensure the Python bindning works
The purpose of the testing is to ensure the Python binding works
with various different input arguments.
"""
def test_exec_with_different_args(self):
# load data
Load(
Filename="test_index_satellite_peaks.integrate", OutputWorkspace="test",
)
FindUBUsingIndexedPeaks(PeaksWorkspace="test")
# defualt args
IndexPeaks(PeaksWorkspace="test", Tolerance=0.12)
# testing zero (default) modVec with maxOrder=1
IndexPeaks(
PeaksWorkspace="test",
Tolerance=0.12,
RoundHKLs=False,
SaveModulationInfo=True,
MaxOrder=1,
)
# testing one non-zero modVec with maxOrder=1
IndexPeaks(
PeaksWorkspace="test",
Tolerance=0.12,
RoundHKLs=False,
SaveModulationInfo=True,
MaxOrder=1,
ModVector1="0,0,0.33333",
)
# testing one non-zero modVec with maxOrder=0
IndexPeaks(
PeaksWorkspace="test",
Tolerance=0.12,
RoundHKLs=False,
SaveModulationInfo=True,
ModVector1="0,0,0.33333",
)
def setUp(self):
# load empty instrument so can create a peak table
self.ws = LoadEmptyInstrument(InstrumentName='SXD', OutputWorkspace='sxd')
ub = np.array([[-0.00601763, 0.07397297, 0.05865706],
[0.05373321, 0.050198, -0.05651455],
[-0.07822144, 0.0295911, -0.04489172]])
SetUB(self.ws, UB=ub)
PredictPeaks(self.ws, WavelengthMin=1, WavelengthMax=1.1,
MinDSpacing=1, MaxDSPacing=1.1, OutputWorkspace='test') # 8 peaks
PredictSatellitePeaks(Peaks='test', SatellitePeaks='test_sat',
ModVector1='0,0,0.33', MaxOrder=1)
self.peaks = CombinePeaksWorkspaces(LHSWorkspace='test_sat', RHSWorkspace='test',
OutputWorkspace='test')
def tearDown(self):
AnalysisDataService.clear()
def test_exec_with_default_args(self):
index_output = IndexPeaks(PeaksWorkspace="test", Tolerance=0.12)
self.assertEqual(index_output[0], 31)
def test_exec_with_mod_vector_supplied_correctly(self):
index_output = IndexPeaks(PeaksWorkspace="test",
Tolerance=0.12,
RoundHKLs=False,
SaveModulationInfo=True,
MaxOrder=1,
ModVector1="0,0,0.33333")
self.assertEqual(index_output[0], 31)
def test_exec_throws_error_saving_mod_info_when_no_mod_vector_supplied(self):
with self.assertRaisesRegex(RuntimeError, "SaveModulationInfo"):
# testing zero (default) modVec with maxOrder=1
IndexPeaks(
PeaksWorkspace="test",
Tolerance=0.12,
RoundHKLs=False,
SaveModulationInfo=True,
MaxOrder=1,
)
def test_exec_throws_error_saving_mod_info_when_zero_max_order(self):
with self.assertRaisesRegex(RuntimeError, "MaxOrder"):
IndexPeaks(
PeaksWorkspace="test",
Tolerance=0.12,
RoundHKLs=False,
SaveModulationInfo=True,
ModVector1="0,0,0.33333",
) # MaxOrder=0 by default
if __name__ == "__main__":
......
......@@ -44,6 +44,7 @@ set(TEST_PY_FILES
D7YIGPositionCalibrationTest.py
D7AbsoluteCrossSectionsTest.py
LoadWANDTest.py
MatchAndMergeWorkspacesTest.py
MDNormSCDPreprocessIncoherentTest.py
MolDynTest.py
MSDFitTest.py
......
......@@ -71,7 +71,3 @@ class SANSBeamCentreFinderTest(unittest.TestCase):
expected_mismatched = (y_data_1[1] ** 2) + (y_data_2[1] ** 2)
squared_expected = expected_matched + expected_mismatched
self.assertEqual(squared_expected, result.total_residual)
if __name__ == '__main__':
unittest.main()
......@@ -5,6 +5,7 @@ set(TEST_PY_FILES
AFM_ZFTest.py
AttributeTest.py
BesselTest.py
ChudleyElliotTest.py
CombGaussLorentzKTTest.py
DampedBesselTest.py
CompositePCRmagnetTest.py
......@@ -31,6 +32,8 @@ set(TEST_PY_FILES
PCRmagnetRedfieldTest.py
PCRmagnetfnormTest.py
PEARLTransVoigtTest.py
PrimStretchedExpFTTest.py
RedfieldTest.py
RFresonanceTest.py
SpinGlassTest.py
StandardSCTest.py
......
......@@ -18,10 +18,11 @@ class RedfieldTest(unittest.TestCase):
self.fail(msg)
def test_function_output(self):
input = [0.0, 4.0, 8.0, 12.0]
expected = [0.2, -0.05237002010607009, 0.061888393844228465, -0.03887640266005458]
input = np.linspace(0, 1000, 4) # Between 0-1000 Gauss
expected = [0.91847597, 0.76278678, 0.5056509, 0.3237545]
tolerance = 1.0e-05
status, output = check_output("Redfield", input, expected, tolerance, A0 = 0.2, Hloc = 0.1, Tau = 0.1)
function_params = {"A0": 10, "Hloc": 50, "Tau": 0.1}
status, output = check_output("Redfield", input, expected, tolerance, **function_params)
if not status:
msg = 'Computed output {} from input {} unequal to expected: {}'
self.fail(msg.format(*[str(i) for i in (output, input, expected)]))
......@@ -29,5 +30,6 @@ class RedfieldTest(unittest.TestCase):
def test_do_fit(self):
do_a_fit(np.arange(0.1, 16, 0.2), 'Redfield', guess = dict(A0 = 0.2, Hloc = 0.1, Tau = 0.1),target = dict(A0 = 0.2, Hloc = 0.1, Tau = 0.1), atol = 0.01)
if __name__ == '__main__':
unittest.main()
set(TEST_FILES
CalculateSlitsTest.h
ConvertToReflectometryQTest.h
CreateTransmissionWorkspace2Test.h
CreateTransmissionWorkspaceAuto2Test.h
FindReflectometryLines2Test.h
NRCalculateSlitResolutionTest.h
ReflectometryBeamStatisticsTest.h
ReflectometryMomentumTransferTest.h
ReflectometryReductionOne2Test.h
ReflectometryReductionOneAuto2Test.h
ReflectometryReductionOneAuto3Test.h
ReflectometryTransformKiKfTest.h
ReflectometryTransformPTest.h
ReflectometryTransformQxQzTest.h
ReflectometrySumInQTest.h
SpecularReflectionCalculateTheta2Test.h
SpecularReflectionCalculateThetaTest.h
SpecularReflectionPositionCorrect2Test.h
SpecularReflectionPositionCorrectTest.h
)
set(TEST_PY_FILES ReflectometryBackgroundSubtractionTest.py ReflectometryReductionOne2Test.py)
if(CXXTEST_FOUND)
include_directories(SYSTEM ${CXXTEST_INCLUDE_DIR})
......
set(TEST_FILES
AlignAndFocusPowderTest.h
ExtractQENSMembersTest.h
IMuonAsymmetryCalculatorTest.h
LoadEventAndCompressTest.h
MuonProcessTest.h
ProcessIndirectFitParametersTest.h
SANSSolidAngleCorrectionTest.h
SofTwoThetaTOFTest.h
StepScanTest.h
)
set(TEST_PY_FILES EQSANSQ2DTest.py SANSBeamFluxCorrectionTest.py)
if(CXXTEST_FOUND)
include_directories(SYSTEM ${CXXTEST_INCLUDE_DIR})
......
......@@ -5,7 +5,6 @@
# Institut Laue - Langevin & CSNS, Institute of High Energy Physics, CAS
# SPDX - License - Identifier: GPL - 3.0 +
from mantid.simpleapi import FindSatellitePeaks, Load
import unittest
import systemtesting
......@@ -64,7 +63,3 @@ class FindSatellitePeaksTestAutoFindQ(systemtesting.MantidSystemTest):
def validate(self):
return self._satellites_refined.name(), 'refine_satellites_auto_q_test_04012021.nxs'
if __name__ == "__main__":
unittest.main()
......@@ -270,7 +270,3 @@ class SANSLOQCan2DReloadWorkspace(systemtesting.MantidSystemTest):
self.disableChecking.append('Axes')
# the change in number is because the run number reported from 99630 is 53615
return '53615main_2D_2.2_10.0','SANSLOQCan2D.nxs'
if __name__ == "__main__":
unittest.main()
......@@ -178,7 +178,3 @@ class SANS2DWaveloopsReloadWorkspace(systemtesting.MantidSystemTest):
# testing one of the workspaces that is produced, best not to choose the
# first one in produced by the loop as this is the least error prone
return '992rear_1D_7.0_11.0','SANS2DWaveloops.nxs'
if __name__ == "__main__":
unittest.main()
......@@ -315,7 +315,3 @@ class SANSBatchReductionRunnerTest(systemtesting.MantidSystemTest):
def validate(self):
return self._success
if __name__ == '__main__':