From 3d6483e8fd59d2e77149aa5d78ec32448be7338c Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Tue, 21 Jul 2020 22:46:49 +0300 Subject: Move tests to module * test/unittest/: Move to wqflask/tests/ --- wqflask/tests/__init__.py | 0 wqflask/tests/base/__init__.py | 0 wqflask/tests/base/test_general_object.py | 21 +++++++++++++++++++++ 3 files changed, 21 insertions(+) create mode 100644 wqflask/tests/__init__.py create mode 100644 wqflask/tests/base/__init__.py create mode 100644 wqflask/tests/base/test_general_object.py (limited to 'wqflask/tests') diff --git a/wqflask/tests/__init__.py b/wqflask/tests/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/wqflask/tests/base/__init__.py b/wqflask/tests/base/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/wqflask/tests/base/test_general_object.py b/wqflask/tests/base/test_general_object.py new file mode 100644 index 00000000..699cb079 --- /dev/null +++ b/wqflask/tests/base/test_general_object.py @@ -0,0 +1,21 @@ +import unittest + +from base.GeneralObject import GeneralObject + + +class TestGeneralObjectTests(unittest.TestCase): + """ + Test the GeneralObject base class + """ + + def test_object_contents(self): + """Test whether base contents are stored properly""" + test_obj = GeneralObject("a", "b", "c") + self.assertEqual("abc", ''.join(test_obj.contents)) + + def test_object_dict(self): + """Test whether the base class is printed properly""" + test_obj = GeneralObject("a", name="test", value=1) + self.assertEqual(str(test_obj), "value = 1\nname = test\n") + self.assertEqual( + repr(test_obj), "value = 1\nname = test\ncontents = ['a']\n") -- cgit v1.2.3 From b4d35b413df6ac11648030afd9ceb76e05e0e0f5 Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Tue, 21 Jul 2020 23:36:48 +0300 Subject: Test utility methods for chunking * wqflask/tests/utility/test_chunks.py: New test --- wqflask/tests/utility/__init__.py | 0 wqflask/tests/utility/test_chunks.py | 19 +++++++++++++++++++ 2 files changed, 19 insertions(+) create mode 100644 wqflask/tests/utility/__init__.py create mode 100644 wqflask/tests/utility/test_chunks.py (limited to 'wqflask/tests') diff --git a/wqflask/tests/utility/__init__.py b/wqflask/tests/utility/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/wqflask/tests/utility/test_chunks.py b/wqflask/tests/utility/test_chunks.py new file mode 100644 index 00000000..8d90a1ec --- /dev/null +++ b/wqflask/tests/utility/test_chunks.py @@ -0,0 +1,19 @@ +"""Test chunking""" + +import unittest + +from utility.chunks import divide_into_chunks + + +class TestChunks(unittest.TestCase): + "Test Utility method for chunking" + def test_divide_into_chunks(self): + "Check that a list is chunked correctly" + self.assertEqual(divide_into_chunks([1, 2, 7, 3, 22, 8, 5, 22, 333], 3), + [[1, 2, 7], [3, 22, 8], [5, 22, 333]]) + self.assertEqual(divide_into_chunks([1, 2, 7, 3, 22, 8, 5, 22, 333], 4), + [[1, 2, 7], [3, 22, 8], [5, 22, 333]]) + self.assertEqual(divide_into_chunks([1, 2, 7, 3, 22, 8, 5, 22, 333], 5), + [[1, 2], [7, 3], [22, 8], [5, 22], [333]]) + self.assertEqual(divide_into_chunks([], 5), + [[]]) -- cgit v1.2.3 From 539e6ac3f211391cf241f2f2b70ed7dbd327fc28 Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Wed, 22 Jul 2020 00:43:12 +0300 Subject: Add unittests for *utility/corestats* --- wqflask/tests/utility/test_corestats.py | 55 +++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 wqflask/tests/utility/test_corestats.py (limited to 'wqflask/tests') diff --git a/wqflask/tests/utility/test_corestats.py b/wqflask/tests/utility/test_corestats.py new file mode 100644 index 00000000..cf91a248 --- /dev/null +++ b/wqflask/tests/utility/test_corestats.py @@ -0,0 +1,55 @@ +"""Test Core Stats""" + +import unittest + +from utility.corestats import Stats + + +class TestChunks(unittest.TestCase): + "Test Utility method for chunking" + + def setUp(self): + self.stat_test = Stats((x for x in range(1, 11))) + + def test_stats_sum(self): + """ Test sequence sum """ + self.assertEqual(self.stat_test.sum(), 55) + self.stat_test = Stats([]) + self.assertEqual(self.stat_test.sum(), None) + + def test_stats_count(self): + """ Test sequence count """ + self.assertEqual(self.stat_test.count(), 10) + self.stat_test = Stats([]) + self.assertEqual(self.stat_test.count(), 0) + + def test_stats_min(self): + """ Test min value in sequence""" + self.assertEqual(self.stat_test.min(), 1) + self.stat_test = Stats([]) + self.assertEqual(self.stat_test.min(), None) + + def test_stats_max(self): + """ Test max value in sequence """ + self.assertEqual(self.stat_test.max(), 10) + self.stat_test = Stats([]) + self.assertEqual(self.stat_test.max(), None) + + def test_stats_avg(self): + """ Test avg of sequence """ + self.assertEqual(self.stat_test.avg(), 5.5) + self.stat_test = Stats([]) + self.assertEqual(self.stat_test.avg(), None) + + def test_stats_stdev(self): + """ Test standard deviation of sequence """ + self.assertEqual(self.stat_test.stdev(), 3.0276503540974917) + self.stat_test = Stats([]) + self.assertEqual(self.stat_test.stdev(), None) + + def test_stats_percentile(self): + """ Test percentile of sequence """ + self.assertEqual(self.stat_test.percentile(20), 3.0) + self.assertEqual(self.stat_test.percentile(101), None) + self.stat_test = Stats([]) + self.assertEqual(self.stat_test.percentile(20), None) -- cgit v1.2.3 From 01bbbc1ee82b43505e65446e4657ca7790453fdf Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Wed, 22 Jul 2020 01:33:10 +0300 Subject: Add unittests for *utility/corr_result_helper* --- wqflask/tests/utility/test_corr_result_helpers.py | 32 +++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 wqflask/tests/utility/test_corr_result_helpers.py (limited to 'wqflask/tests') diff --git a/wqflask/tests/utility/test_corr_result_helpers.py b/wqflask/tests/utility/test_corr_result_helpers.py new file mode 100644 index 00000000..e196fbdf --- /dev/null +++ b/wqflask/tests/utility/test_corr_result_helpers.py @@ -0,0 +1,32 @@ +""" Test correlation helper methods """ + +import unittest +from utility.corr_result_helpers import normalize_values, common_keys, normalize_values_with_samples + + +class TestCorrelationHelpers(unittest.TestCase): + """Test methods for normalising lists""" + + def test_normalize_values(self): + """Test that a list is normalised correctly""" + self.assertEqual( + normalize_values([2.3, None, None, 3.2, 4.1, 5], [ + 3.4, 7.2, 1.3, None, 6.2, 4.1]), + ([2.3, 4.1, 5], [3.4, 6.2, 4.1], 3) + ) + + def test_common_keys(self): + """Test that common keys are returned as a list""" + a = dict(BXD1=9.113, BXD2=9.825, BXD14=8.985, BXD15=9.300) + b = dict(BXD1=9.723, BXD3=9.825, BXD14=9.124, BXD16=9.300) + self.assertEqual(sorted(common_keys(a, b)), ['BXD1', 'BXD14']) + + def test_normalize_values_with_samples(self): + """Test that a sample(dict) is normalised correctly""" + self.assertEqual( + normalize_values_with_samples( + dict(BXD1=9.113, BXD2=9.825, BXD14=8.985, + BXD15=9.300, BXD20=9.300), + dict(BXD1=9.723, BXD3=9.825, BXD14=9.124, BXD16=9.300)), + (({'BXD1': 9.113, 'BXD14': 8.985}, {'BXD1': 9.723, 'BXD14': 9.124}, 2)) + ) -- cgit v1.2.3 From 87fd995209aba0df1f95c1d5d5dd7eefd60d0906 Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Wed, 22 Jul 2020 17:22:14 +0300 Subject: Add unittests for *utility/test_numify* --- wqflask/tests/utility/test_numify.py | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 wqflask/tests/utility/test_numify.py (limited to 'wqflask/tests') diff --git a/wqflask/tests/utility/test_numify.py b/wqflask/tests/utility/test_numify.py new file mode 100644 index 00000000..9d3033d1 --- /dev/null +++ b/wqflask/tests/utility/test_numify.py @@ -0,0 +1,33 @@ +import unittest +from utility.formatting import numify, commify + + +class TestFormatting(unittest.TestCase): + """Test formatting numbers by numifying or commifying""" + + def test_numify(self): + "Test that a number is correctly converted to a English readable string" + self.assertEqual(numify(1, 'item', 'items'), + 'one item') + self.assertEqual(numify(2, 'book'), 'two') + self.assertEqual(numify(2, 'book', 'books'), 'two books') + self.assertEqual(numify(0, 'book', 'books'), 'zero books') + self.assertEqual(numify(0), 'zero') + self.assertEqual(numify(5), 'five') + self.assertEqual(numify(14, 'book', 'books'), '14 books') + self.assertEqual(numify(999, 'book', 'books'), '999 books') + self.assertEqual(numify(1000000, 'book', 'books'), '1,000,000 books') + self.assertEqual(numify(1956), '1956') + + def test_commify(self): + "Test that commas are added correctly" + self.assertEqual(commify(1), '1') + self.assertEqual(commify(123), '123') + self.assertEqual(commify(1234), '1234') + self.assertEqual(commify(12345), '12,345') + self.assertEqual(commify(1234567890), '1,234,567,890') + self.assertEqual(commify(123.0), '123.0') + self.assertEqual(commify(1234.5), '1234.5') + self.assertEqual(commify(1234.56789), '1234.56789') + self.assertEqual(commify(123456.789), '123,456.789') + self.assertEqual(commify(None), None) -- cgit v1.2.3 From 16aaf9885971993863b5e2e8a1b99f8479e2bbb9 Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Thu, 23 Jul 2020 02:52:41 +0300 Subject: Add unittests for *base/data_set* --- wqflask/tests/base/test_data_set.py | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 wqflask/tests/base/test_data_set.py (limited to 'wqflask/tests') diff --git a/wqflask/tests/base/test_data_set.py b/wqflask/tests/base/test_data_set.py new file mode 100644 index 00000000..44a54c7e --- /dev/null +++ b/wqflask/tests/base/test_data_set.py @@ -0,0 +1,35 @@ +import unittest +import mock + +from wqflask import app + +from base.data_set import DatasetType + + +class TestDataSetTypes(unittest.TestCase): + def setUp(self): + self.app_context = app.app_context() + self.app_context.push() + + def tearDown(self): + self.app_context.pop() + + @mock.patch('base.data_set.g') + def test_data_set_type(self, db_mock): + with app.app_context(): + db_mock.get = mock.Mock() + r = mock.Mock() + r.get.return_value = """ + { + "AD-cases-controls-MyersGeno": "Geno", + "AD-cases-controls-MyersPublish": "Publish", + "AKXDGeno": "Geno", + "AXBXAGeno": "Geno", + "AXBXAPublish": "Publish", + "Aging-Brain-UCIPublish": "Publish", + "All Phenotypes": "Publish", + "B139_K_1206_M": "ProbeSet", + "B139_K_1206_R": "ProbeSet" + } + """ + self.assertEqual(DatasetType(r)("All Phenotypes"), "Publish") -- cgit v1.2.3 From a6075ce879c338532de39e100f09d92c17b566e7 Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Thu, 23 Jul 2020 02:54:59 +0300 Subject: Rename test_numify.py to test_formatting.py --- wqflask/tests/utility/test_formatting.py | 33 ++++++++++++++++++++++++++++++++ wqflask/tests/utility/test_numify.py | 33 -------------------------------- 2 files changed, 33 insertions(+), 33 deletions(-) create mode 100644 wqflask/tests/utility/test_formatting.py delete mode 100644 wqflask/tests/utility/test_numify.py (limited to 'wqflask/tests') diff --git a/wqflask/tests/utility/test_formatting.py b/wqflask/tests/utility/test_formatting.py new file mode 100644 index 00000000..9d3033d1 --- /dev/null +++ b/wqflask/tests/utility/test_formatting.py @@ -0,0 +1,33 @@ +import unittest +from utility.formatting import numify, commify + + +class TestFormatting(unittest.TestCase): + """Test formatting numbers by numifying or commifying""" + + def test_numify(self): + "Test that a number is correctly converted to a English readable string" + self.assertEqual(numify(1, 'item', 'items'), + 'one item') + self.assertEqual(numify(2, 'book'), 'two') + self.assertEqual(numify(2, 'book', 'books'), 'two books') + self.assertEqual(numify(0, 'book', 'books'), 'zero books') + self.assertEqual(numify(0), 'zero') + self.assertEqual(numify(5), 'five') + self.assertEqual(numify(14, 'book', 'books'), '14 books') + self.assertEqual(numify(999, 'book', 'books'), '999 books') + self.assertEqual(numify(1000000, 'book', 'books'), '1,000,000 books') + self.assertEqual(numify(1956), '1956') + + def test_commify(self): + "Test that commas are added correctly" + self.assertEqual(commify(1), '1') + self.assertEqual(commify(123), '123') + self.assertEqual(commify(1234), '1234') + self.assertEqual(commify(12345), '12,345') + self.assertEqual(commify(1234567890), '1,234,567,890') + self.assertEqual(commify(123.0), '123.0') + self.assertEqual(commify(1234.5), '1234.5') + self.assertEqual(commify(1234.56789), '1234.56789') + self.assertEqual(commify(123456.789), '123,456.789') + self.assertEqual(commify(None), None) diff --git a/wqflask/tests/utility/test_numify.py b/wqflask/tests/utility/test_numify.py deleted file mode 100644 index 9d3033d1..00000000 --- a/wqflask/tests/utility/test_numify.py +++ /dev/null @@ -1,33 +0,0 @@ -import unittest -from utility.formatting import numify, commify - - -class TestFormatting(unittest.TestCase): - """Test formatting numbers by numifying or commifying""" - - def test_numify(self): - "Test that a number is correctly converted to a English readable string" - self.assertEqual(numify(1, 'item', 'items'), - 'one item') - self.assertEqual(numify(2, 'book'), 'two') - self.assertEqual(numify(2, 'book', 'books'), 'two books') - self.assertEqual(numify(0, 'book', 'books'), 'zero books') - self.assertEqual(numify(0), 'zero') - self.assertEqual(numify(5), 'five') - self.assertEqual(numify(14, 'book', 'books'), '14 books') - self.assertEqual(numify(999, 'book', 'books'), '999 books') - self.assertEqual(numify(1000000, 'book', 'books'), '1,000,000 books') - self.assertEqual(numify(1956), '1956') - - def test_commify(self): - "Test that commas are added correctly" - self.assertEqual(commify(1), '1') - self.assertEqual(commify(123), '123') - self.assertEqual(commify(1234), '1234') - self.assertEqual(commify(12345), '12,345') - self.assertEqual(commify(1234567890), '1,234,567,890') - self.assertEqual(commify(123.0), '123.0') - self.assertEqual(commify(1234.5), '1234.5') - self.assertEqual(commify(1234.56789), '1234.56789') - self.assertEqual(commify(123456.789), '123,456.789') - self.assertEqual(commify(None), None) -- cgit v1.2.3 From f95a42b0a9445a58e68fc83e9b1411bedef67904 Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Fri, 24 Jul 2020 01:43:26 +0300 Subject: Add more tests for GeneralObject * wqflask/tests/base/test_general_object.py: test object's magic methods --- wqflask/tests/base/test_general_object.py | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'wqflask/tests') diff --git a/wqflask/tests/base/test_general_object.py b/wqflask/tests/base/test_general_object.py index 699cb079..df5791e0 100644 --- a/wqflask/tests/base/test_general_object.py +++ b/wqflask/tests/base/test_general_object.py @@ -12,6 +12,7 @@ class TestGeneralObjectTests(unittest.TestCase): """Test whether base contents are stored properly""" test_obj = GeneralObject("a", "b", "c") self.assertEqual("abc", ''.join(test_obj.contents)) + self.assertEqual(len(test_obj), 0) def test_object_dict(self): """Test whether the base class is printed properly""" @@ -19,3 +20,8 @@ class TestGeneralObjectTests(unittest.TestCase): self.assertEqual(str(test_obj), "value = 1\nname = test\n") self.assertEqual( repr(test_obj), "value = 1\nname = test\ncontents = ['a']\n") + self.assertEqual(len(test_obj), 2) + self.assertEqual(getattr(test_obj, "value"), 1) + self.assertEqual(test_obj["value"], 1) + test_obj["test"] = 1 + self.assertEqual(test_obj["test"], 1) -- cgit v1.2.3 From 09bc3137328fbefe41044b5124f3c6a7abaa8982 Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Fri, 24 Jul 2020 02:14:50 +0300 Subject: Add more tests for general_object * wqflask/tests/base/test_general_object.py: test getattr() and `==` --- wqflask/tests/base/test_general_object.py | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/base/test_general_object.py b/wqflask/tests/base/test_general_object.py index df5791e0..c7701021 100644 --- a/wqflask/tests/base/test_general_object.py +++ b/wqflask/tests/base/test_general_object.py @@ -21,7 +21,21 @@ class TestGeneralObjectTests(unittest.TestCase): self.assertEqual( repr(test_obj), "value = 1\nname = test\ncontents = ['a']\n") self.assertEqual(len(test_obj), 2) - self.assertEqual(getattr(test_obj, "value"), 1) self.assertEqual(test_obj["value"], 1) test_obj["test"] = 1 self.assertEqual(test_obj["test"], 1) + + def test_get_attribute(self): + "Test that getattr works" + test_obj = GeneralObject("a", name="test", value=1) + self.assertEqual(getattr(test_obj, "value", None), 1) + self.assertEqual(getattr(test_obj, "non-existent", None), None) + + def test_object_comparisons(self): + "Test that 2 objects of the same length are equal" + test_obj1 = GeneralObject("a", name="test", value=1) + test_obj2 = GeneralObject("b", name="test2", value=2) + test_obj3 = GeneralObject("a", name="test", x=1, y=2) + self.assertTrue(test_obj1 == test_obj2 ) + self.assertFalse(test_obj1 == test_obj3 ) + -- cgit v1.2.3 From 70a8b445df32b7ed15612ffa745269959eb9159b Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Wed, 22 Jul 2020 17:22:14 +0300 Subject: Add unittests for *utility/test_numify* --- wqflask/tests/utility/test_numify.py | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 wqflask/tests/utility/test_numify.py (limited to 'wqflask/tests') diff --git a/wqflask/tests/utility/test_numify.py b/wqflask/tests/utility/test_numify.py new file mode 100644 index 00000000..9d3033d1 --- /dev/null +++ b/wqflask/tests/utility/test_numify.py @@ -0,0 +1,33 @@ +import unittest +from utility.formatting import numify, commify + + +class TestFormatting(unittest.TestCase): + """Test formatting numbers by numifying or commifying""" + + def test_numify(self): + "Test that a number is correctly converted to a English readable string" + self.assertEqual(numify(1, 'item', 'items'), + 'one item') + self.assertEqual(numify(2, 'book'), 'two') + self.assertEqual(numify(2, 'book', 'books'), 'two books') + self.assertEqual(numify(0, 'book', 'books'), 'zero books') + self.assertEqual(numify(0), 'zero') + self.assertEqual(numify(5), 'five') + self.assertEqual(numify(14, 'book', 'books'), '14 books') + self.assertEqual(numify(999, 'book', 'books'), '999 books') + self.assertEqual(numify(1000000, 'book', 'books'), '1,000,000 books') + self.assertEqual(numify(1956), '1956') + + def test_commify(self): + "Test that commas are added correctly" + self.assertEqual(commify(1), '1') + self.assertEqual(commify(123), '123') + self.assertEqual(commify(1234), '1234') + self.assertEqual(commify(12345), '12,345') + self.assertEqual(commify(1234567890), '1,234,567,890') + self.assertEqual(commify(123.0), '123.0') + self.assertEqual(commify(1234.5), '1234.5') + self.assertEqual(commify(1234.56789), '1234.56789') + self.assertEqual(commify(123456.789), '123,456.789') + self.assertEqual(commify(None), None) -- cgit v1.2.3 From bcf98cc6c1f0208cc8f9a21d36196627e1d6e6b6 Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Thu, 23 Jul 2020 02:54:59 +0300 Subject: Rename test_numify.py to test_formatting.py --- wqflask/tests/utility/test_numify.py | 33 --------------------------------- 1 file changed, 33 deletions(-) delete mode 100644 wqflask/tests/utility/test_numify.py (limited to 'wqflask/tests') diff --git a/wqflask/tests/utility/test_numify.py b/wqflask/tests/utility/test_numify.py deleted file mode 100644 index 9d3033d1..00000000 --- a/wqflask/tests/utility/test_numify.py +++ /dev/null @@ -1,33 +0,0 @@ -import unittest -from utility.formatting import numify, commify - - -class TestFormatting(unittest.TestCase): - """Test formatting numbers by numifying or commifying""" - - def test_numify(self): - "Test that a number is correctly converted to a English readable string" - self.assertEqual(numify(1, 'item', 'items'), - 'one item') - self.assertEqual(numify(2, 'book'), 'two') - self.assertEqual(numify(2, 'book', 'books'), 'two books') - self.assertEqual(numify(0, 'book', 'books'), 'zero books') - self.assertEqual(numify(0), 'zero') - self.assertEqual(numify(5), 'five') - self.assertEqual(numify(14, 'book', 'books'), '14 books') - self.assertEqual(numify(999, 'book', 'books'), '999 books') - self.assertEqual(numify(1000000, 'book', 'books'), '1,000,000 books') - self.assertEqual(numify(1956), '1956') - - def test_commify(self): - "Test that commas are added correctly" - self.assertEqual(commify(1), '1') - self.assertEqual(commify(123), '123') - self.assertEqual(commify(1234), '1234') - self.assertEqual(commify(12345), '12,345') - self.assertEqual(commify(1234567890), '1,234,567,890') - self.assertEqual(commify(123.0), '123.0') - self.assertEqual(commify(1234.5), '1234.5') - self.assertEqual(commify(1234.56789), '1234.56789') - self.assertEqual(commify(123456.789), '123,456.789') - self.assertEqual(commify(None), None) -- cgit v1.2.3 From d63e7554d6dfce4e80c2570667a0fa371235beb7 Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Mon, 27 Jul 2020 14:31:31 +0300 Subject: Apply py-lint * wqflask/tests/base/test_data_set.py: Apply pylint --- wqflask/tests/base/test_data_set.py | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/base/test_data_set.py b/wqflask/tests/base/test_data_set.py index 44a54c7e..74799e49 100644 --- a/wqflask/tests/base/test_data_set.py +++ b/wqflask/tests/base/test_data_set.py @@ -1,3 +1,5 @@ +"""Tests for wqflask/base/data_set.py""" + import unittest import mock @@ -5,8 +7,10 @@ from wqflask import app from base.data_set import DatasetType - + class TestDataSetTypes(unittest.TestCase): + """Tests for the DataSetType class""" + def setUp(self): self.app_context = app.app_context() self.app_context.push() @@ -16,10 +20,14 @@ class TestDataSetTypes(unittest.TestCase): @mock.patch('base.data_set.g') def test_data_set_type(self, db_mock): + """Test that DatasetType returns correctly if the Redis Instance is not empty + and the name variable exists in the dictionary + + """ with app.app_context(): db_mock.get = mock.Mock() - r = mock.Mock() - r.get.return_value = """ + redis_mock = mock.Mock() + redis_mock.get.return_value = """ { "AD-cases-controls-MyersGeno": "Geno", "AD-cases-controls-MyersPublish": "Publish", @@ -32,4 +40,6 @@ class TestDataSetTypes(unittest.TestCase): "B139_K_1206_R": "ProbeSet" } """ - self.assertEqual(DatasetType(r)("All Phenotypes"), "Publish") + self.assertEqual(DatasetType(redis_mock) + ("All Phenotypes"), "Publish") + -- cgit v1.2.3 From 5cad720187b3c53b6d64c64d45be4bc020eed52d Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Mon, 27 Jul 2020 14:32:26 +0300 Subject: Add test case for empty redis instance for DatasetType * wqflask/tests/base/test_data_set.py(tests): Check correct results are returned when Redis is empty * wqflask/tests/base/data.py(tests): New file. Adds json test data. --- wqflask/tests/base/data.py | 110 ++++++++++++++++++++++++++++++++++++ wqflask/tests/base/test_data_set.py | 16 +++++- 2 files changed, 125 insertions(+), 1 deletion(-) create mode 100644 wqflask/tests/base/data.py (limited to 'wqflask/tests') diff --git a/wqflask/tests/base/data.py b/wqflask/tests/base/data.py new file mode 100644 index 00000000..06a5a989 --- /dev/null +++ b/wqflask/tests/base/data.py @@ -0,0 +1,110 @@ +gen_menu_json = """ +{ + "datasets": { + "human": { + "HLC": { + "Liver mRNA": [ + [ + "320", + "HLC_0311", + "GSE9588 Human Liver Normal (Mar11) Both Sexes" + ] + ], + "Phenotypes": [ + [ + "635", + "HLCPublish", + "HLC Published Phenotypes" + ] + ] + } + }, + "mouse": { + "BXD": { + "Genotypes": [ + [ + "600", + "BXDGeno", + "BXD Genotypes" + ] + ], + "Hippocampus mRNA": [ + [ + "112", + "HC_M2_0606_P", + "Hippocampus Consortium M430v2 (Jun06) PDNN" + ] + ], + "Phenotypes": [ + [ + "602", + "BXDPublish", + "BXD Published Phenotypes" + ] + ] + } + } + }, + "groups": { + "human": [ + [ + "HLC", + "Liver: Normal Gene Expression with Genotypes (Merck)", + "Family:None" + ] + ], + "mouse": [ + [ + "BXD", + "BXD", + "Family:None" + ] + ] + }, + "species": [ + [ + "human", + "Human" + ], + [ + "mouse", + "Mouse" + ] + ], + "types": { + "human": { + "HLC": [ + [ + "Phenotypes", + "Traits and Cofactors", + "Phenotypes" + ], + [ + "Liver mRNA", + "Liver mRNA", + "Molecular Trait Datasets" + ] + ] + }, + "mouse": { + "BXD": [ + [ + "Phenotypes", + "Traits and Cofactors", + "Phenotypes" + ], + [ + "Genotypes", + "DNA Markers and SNPs", + "Genotypes" + ], + [ + "Hippocampus mRNA", + "Hippocampus mRNA", + "Molecular Trait Datasets" + ] + ] + } + } +} +""" diff --git a/wqflask/tests/base/test_data_set.py b/wqflask/tests/base/test_data_set.py index 74799e49..835d786a 100644 --- a/wqflask/tests/base/test_data_set.py +++ b/wqflask/tests/base/test_data_set.py @@ -4,7 +4,7 @@ import unittest import mock from wqflask import app - +from data import gen_menu_json from base.data_set import DatasetType @@ -43,3 +43,17 @@ class TestDataSetTypes(unittest.TestCase): self.assertEqual(DatasetType(redis_mock) ("All Phenotypes"), "Publish") + @mock.patch('base.data_set.requests.get') + def test_data_set_type_with_empty_redis(self, request_mock): + """Test that DatasetType returns correctly if the Redis Instance is empty and + the name variable exists in the dictionary + + """ + with app.app_context(): + request_mock.return_value.content = gen_menu_json + redis_mock = mock.Mock() + redis_mock.get.return_value = None + data_set = DatasetType(redis_mock) + self.assertEqual(data_set("BXDGeno"), "Geno") + self.assertEqual(data_set("BXDPublish"), "Publish") + self.assertEqual(data_set("HLC_0311"), "ProbeSet") -- cgit v1.2.3 From 957e05d33eb423df99181a99e7c25891810a21f7 Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Mon, 27 Jul 2020 15:06:02 +0300 Subject: Check that Redis is called correctly * wqflask/tests/base/test_data_set.py: assert that `set` and `get` are called correctly --- wqflask/tests/base/test_data_set.py | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'wqflask/tests') diff --git a/wqflask/tests/base/test_data_set.py b/wqflask/tests/base/test_data_set.py index 835d786a..3ac1b6d6 100644 --- a/wqflask/tests/base/test_data_set.py +++ b/wqflask/tests/base/test_data_set.py @@ -42,6 +42,7 @@ class TestDataSetTypes(unittest.TestCase): """ self.assertEqual(DatasetType(redis_mock) ("All Phenotypes"), "Publish") + redis_mock.get.assert_called_once_with("dataset_structure") @mock.patch('base.data_set.requests.get') def test_data_set_type_with_empty_redis(self, request_mock): @@ -57,3 +58,6 @@ class TestDataSetTypes(unittest.TestCase): self.assertEqual(data_set("BXDGeno"), "Geno") self.assertEqual(data_set("BXDPublish"), "Publish") self.assertEqual(data_set("HLC_0311"), "ProbeSet") + redis_mock.set.assert_called_once_with( + "dataset_structure", + '{"BXDGeno": "Geno", "BXDPublish": "Publish", "HLCPublish": "Publish", "HLC_0311": "ProbeSet", "HC_M2_0606_P": "ProbeSet"}') -- cgit v1.2.3 From 79b8cf45c1c40b9c20278762b6e8f587a2820b43 Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Mon, 27 Jul 2020 19:10:36 +0300 Subject: Test that non-existent keys in Dataset are set correctly * wqflask/tests/base/test_data_set.py: Add more tests. --- wqflask/tests/base/test_data_set.py | 103 +++++++++++++++++++++++++++++++----- 1 file changed, 90 insertions(+), 13 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/base/test_data_set.py b/wqflask/tests/base/test_data_set.py index 3ac1b6d6..94780a5d 100644 --- a/wqflask/tests/base/test_data_set.py +++ b/wqflask/tests/base/test_data_set.py @@ -12,6 +12,19 @@ class TestDataSetTypes(unittest.TestCase): """Tests for the DataSetType class""" def setUp(self): + self.test_dataset = """ + { + "AD-cases-controls-MyersGeno": "Geno", + "AD-cases-controls-MyersPublish": "Publish", + "AKXDGeno": "Geno", + "AXBXAGeno": "Geno", + "AXBXAPublish": "Publish", + "Aging-Brain-UCIPublish": "Publish", + "All Phenotypes": "Publish", + "B139_K_1206_M": "ProbeSet", + "B139_K_1206_R": "ProbeSet" + } + """ self.app_context = app.app_context() self.app_context.push() @@ -27,19 +40,7 @@ class TestDataSetTypes(unittest.TestCase): with app.app_context(): db_mock.get = mock.Mock() redis_mock = mock.Mock() - redis_mock.get.return_value = """ - { - "AD-cases-controls-MyersGeno": "Geno", - "AD-cases-controls-MyersPublish": "Publish", - "AKXDGeno": "Geno", - "AXBXAGeno": "Geno", - "AXBXAPublish": "Publish", - "Aging-Brain-UCIPublish": "Publish", - "All Phenotypes": "Publish", - "B139_K_1206_M": "ProbeSet", - "B139_K_1206_R": "ProbeSet" - } - """ + redis_mock.get.return_value = self.test_dataset self.assertEqual(DatasetType(redis_mock) ("All Phenotypes"), "Publish") redis_mock.get.assert_called_once_with("dataset_structure") @@ -61,3 +62,79 @@ class TestDataSetTypes(unittest.TestCase): redis_mock.set.assert_called_once_with( "dataset_structure", '{"BXDGeno": "Geno", "BXDPublish": "Publish", "HLCPublish": "Publish", "HLC_0311": "ProbeSet", "HC_M2_0606_P": "ProbeSet"}') + + @mock.patch('base.data_set.g') + def test_set_dataset_key_mrna(self, db_mock): + with app.app_context(): + db_mock.db.execute.return_value = [1, 2, 3] + redis_mock = mock.Mock() + redis_mock.get.return_value = self.test_dataset + data_set = DatasetType(redis_mock) + data_set.set_dataset_key("mrna_expr", "Test") + self.assertEqual(data_set("Test"), "ProbeSet") + redis_mock.set.assert_called_once_with( + "dataset_structure", + '{"Aging-Brain-UCIPublish": "Publish", "AKXDGeno": "Geno", "B139_K_1206_M": "ProbeSet", "AD-cases-controls-MyersGeno": "Geno", "AD-cases-controls-MyersPublish": "Publish", "All Phenotypes": "Publish", "Test": "ProbeSet", "AXBXAPublish": "Publish", "B139_K_1206_R": "ProbeSet", "AXBXAGeno": "Geno"}') + expected_db_call = """""" + db_mock.db.execute.assert_called_with( + ("SELECT ProbeSetFreeze.Id FROM ProbeSetFreeze " + + "WHERE ProbeSetFreeze.Name = \"Test\" ") + ) + + @mock.patch('base.data_set.g') + def test_set_dataset_key_pheno(self, db_mock): + with app.app_context(): + db_mock.db.execute.return_value = [1, 2, 3] + redis_mock = mock.Mock() + redis_mock.get.return_value = self.test_dataset + data_set = DatasetType(redis_mock) + data_set.set_dataset_key("pheno", "Test") + self.assertEqual(data_set("Test"), "Publish") + redis_mock.set.assert_called_once_with( + "dataset_structure", + '{"Aging-Brain-UCIPublish": "Publish", "AKXDGeno": "Geno", "B139_K_1206_M": "ProbeSet", "AD-cases-controls-MyersGeno": "Geno", "AD-cases-controls-MyersPublish": "Publish", "All Phenotypes": "Publish", "Test": "Publish", "AXBXAPublish": "Publish", "B139_K_1206_R": "ProbeSet", "AXBXAGeno": "Geno"}') + expected_db_call = """""" + db_mock.db.execute.assert_called_with( + ("SELECT InfoFiles.GN_AccesionId " + + "FROM InfoFiles, PublishFreeze, InbredSet " + + "WHERE InbredSet.Name = 'Test' AND " + "PublishFreeze.InbredSetId = InbredSet.Id AND " + + "InfoFiles.InfoPageName = PublishFreeze.Name") + ) + + @mock.patch('base.data_set.g') + def test_set_dataset_other_pheno(self, db_mock): + with app.app_context(): + db_mock.db.execute.return_value = [1, 2, 3] + redis_mock = mock.Mock() + redis_mock.get.return_value = self.test_dataset + data_set = DatasetType(redis_mock) + data_set.set_dataset_key("other_pheno", "Test") + self.assertEqual(data_set("Test"), "Publish") + redis_mock.set.assert_called_once_with( + "dataset_structure", + '{"Aging-Brain-UCIPublish": "Publish", "AKXDGeno": "Geno", "B139_K_1206_M": "ProbeSet", "AD-cases-controls-MyersGeno": "Geno", "AD-cases-controls-MyersPublish": "Publish", "All Phenotypes": "Publish", "Test": "Publish", "AXBXAPublish": "Publish", "B139_K_1206_R": "ProbeSet", "AXBXAGeno": "Geno"}') + expected_db_call = """""" + db_mock.db.execute.assert_called_with( + ("SELECT PublishFreeze.Name " + + "FROM PublishFreeze, InbredSet " + + "WHERE InbredSet.Name = 'Test' AND " + "PublishFreeze.InbredSetId = InbredSet.Id") + ) + + @mock.patch('base.data_set.g') + def test_set_dataset_geno(self, db_mock): + with app.app_context(): + db_mock.db.execute.return_value = [1, 2, 3] + redis_mock = mock.Mock() + redis_mock.get.return_value = self.test_dataset + data_set = DatasetType(redis_mock) + data_set.set_dataset_key("geno", "Test") + self.assertEqual(data_set("Test"), "Geno") + redis_mock.set.assert_called_once_with( + "dataset_structure", + '{"Aging-Brain-UCIPublish": "Publish", "AKXDGeno": "Geno", "B139_K_1206_M": "ProbeSet", "AD-cases-controls-MyersGeno": "Geno", "AD-cases-controls-MyersPublish": "Publish", "All Phenotypes": "Publish", "Test": "Geno", "AXBXAPublish": "Publish", "B139_K_1206_R": "ProbeSet", "AXBXAGeno": "Geno"}') + expected_db_call = """""" + db_mock.db.execute.assert_called_with( + ("SELECT GenoFreeze.Id FROM GenoFreeze WHERE GenoFreeze.Name = \"Test\" ") + ) -- cgit v1.2.3 From 7732204662bf395eb8ed55b6d26fd208998c1067 Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Mon, 27 Jul 2020 19:48:16 +0300 Subject: Add unittests for WebqtlCaseData * wqflask/tests/base/test_webqtl_case_data.py: Add it --- wqflask/tests/base/test_webqtl_case_data.py | 39 +++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 wqflask/tests/base/test_webqtl_case_data.py (limited to 'wqflask/tests') diff --git a/wqflask/tests/base/test_webqtl_case_data.py b/wqflask/tests/base/test_webqtl_case_data.py new file mode 100644 index 00000000..8e8ba482 --- /dev/null +++ b/wqflask/tests/base/test_webqtl_case_data.py @@ -0,0 +1,39 @@ +"""Tests for wqflask/base/webqtlCaseData.py""" +import unittest + +from wqflask import app # Required because of utility.tools in webqtlCaseData.py +from base.webqtlCaseData import webqtlCaseData + +class TestWebqtlCaseData(unittest.TestCase): + """Tests for WebqtlCaseData class""" + + def setUp(self): + self.w = webqtlCaseData(name="Test", + value=0, + variance=0.0, + num_cases=10, + name2="Test2") + + def test_webqtl_case_data_repr(self): + self.assertEqual( + repr(self.w), + " value=0.000 variance=0.000 ndata=10 name=Test name2=Test2" + ) + + def test_class_outlier(self): + self.assertEqual(self.w.class_outlier, "") + + def test_display_value(self): + self.assertEqual(self.w.display_value, "0.000") + self.w.value = None + self.assertEqual(self.w.display_value, "x") + + def test_display_variance(self): + self.assertEqual(self.w.display_variance, "0.000") + self.w.variance = None + self.assertEqual(self.w.display_variance, "x") + + def test_display_num_cases(self): + self.assertEqual(self.w.display_num_cases, "10") + self.w.num_cases = None + self.assertEqual(self.w.display_num_cases, "x") -- cgit v1.2.3 From b55792f2daf648affe52d78c7f3a480f6550dfc8 Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Wed, 29 Jul 2020 22:09:21 +0300 Subject: Add initial gen_menu test * wqflask/tests/api/__init__.py: Add it * wqflask/tests/api/test_gen_menu.py: Add test for get_species --- wqflask/tests/api/__init__.py | 0 wqflask/tests/api/test_gen_menu.py | 19 +++++++++++++++++++ 2 files changed, 19 insertions(+) create mode 100644 wqflask/tests/api/__init__.py create mode 100644 wqflask/tests/api/test_gen_menu.py (limited to 'wqflask/tests') diff --git a/wqflask/tests/api/__init__.py b/wqflask/tests/api/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/wqflask/tests/api/test_gen_menu.py b/wqflask/tests/api/test_gen_menu.py new file mode 100644 index 00000000..81908129 --- /dev/null +++ b/wqflask/tests/api/test_gen_menu.py @@ -0,0 +1,19 @@ +"""Test cases for wqflask.api.gen_menu""" +import unittest +import mock + +from wqflask.api.gen_menu import get_species + +class TestGenMenu(unittest.TestCase): + """Tests for the gen_menu module""" + + @mock.patch('wqflask.api.gen_menu.g') + def test_get_species(self, db_mock): + """Test that assertion is raised when dataset and dataset_name are defined""" + db_mock.db.execute.return_value.fetchall.return_value = (('human', 'Human'), + ('mouse', 'Mouse')) + self.assertEqual(get_species(), + [['human', 'Human'], ['mouse', 'Mouse']]) + db_mock.db.execute.assert_called_once_with( + "SELECT Name, MenuName FROM Species ORDER BY OrderId" + ) -- cgit v1.2.3 From 3425e7a5dbf5a6983424659c05c258e7a132edf3 Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Wed, 29 Jul 2020 22:19:13 +0300 Subject: Add test for "get_groups" * wqflask/tests/api/test_gen_menu.py: test that "get_groups" uses the correct sql query and returns the correct group data structure. --- wqflask/tests/api/test_gen_menu.py | 45 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) (limited to 'wqflask/tests') diff --git a/wqflask/tests/api/test_gen_menu.py b/wqflask/tests/api/test_gen_menu.py index 81908129..a2a93da7 100644 --- a/wqflask/tests/api/test_gen_menu.py +++ b/wqflask/tests/api/test_gen_menu.py @@ -3,10 +3,28 @@ import unittest import mock from wqflask.api.gen_menu import get_species +from wqflask.api.gen_menu import get_groups + class TestGenMenu(unittest.TestCase): """Tests for the gen_menu module""" + def setUp(self): + self.test_group = { + 'mouse': [ + ['H_T1', + 'H_T', + 'Family:DescriptionA' + ], + ['H_T2', "H_T'", 'Family:None'] + ], + 'human': [ + ['BXD', 'BXD', 'Family:None'], + ['HLC', 'Liver: Normal Gene Expression with Genotypes (Merck)', + 'Family:Test'] + ] + } + @mock.patch('wqflask.api.gen_menu.g') def test_get_species(self, db_mock): """Test that assertion is raised when dataset and dataset_name are defined""" @@ -17,3 +35,30 @@ class TestGenMenu(unittest.TestCase): db_mock.db.execute.assert_called_once_with( "SELECT Name, MenuName FROM Species ORDER BY OrderId" ) + + @mock.patch('wqflask.api.gen_menu.g') + def test_get_groups(self, db_mock): + """Test that species groups are grouped correctly""" + db_mock.db.execute.return_value.fetchall.side_effect = [ + # Mouse + (('BXD', 'BXD', None), + ('HLC', 'Liver: Normal Gene Expression with Genotypes (Merck)', 'Test')), + # Human + (('H_T1', "H_T", "DescriptionA"), + ('H_T2', "H_T'", None)) + ] + + self.assertEqual(get_groups([["human", "Human"], ["mouse", "Mouse"]]), + self.test_group) + + for name in ["mouse", "human"]: + db_mock.db.execute.assert_any_call( + ("SELECT InbredSet.Name, InbredSet.FullName, " + + "IFNULL(InbredSet.Family, 'None') " + + "FROM InbredSet, Species WHERE Species.Name " + + "= '{}' AND InbredSet.SpeciesId = Species.Id GROUP by " + + "InbredSet.Name ORDER BY IFNULL(InbredSet.FamilyOrder, " + + "InbredSet.FullName) ASC, IFNULL(InbredSet.Family, " + + "InbredSet.FullName) ASC, InbredSet.FullName ASC, " + + "InbredSet.MenuOrderId ASC").format(name) + ) -- cgit v1.2.3 From d50f72869b8d0a7078f0481aad2b04346cd56e3f Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Wed, 29 Jul 2020 22:28:38 +0300 Subject: Add tests for "phenotypes_exist" and "genotypes_exist" * wqflask/tests/api/test_gen_menu.py: Add new tests --- wqflask/tests/api/test_gen_menu.py | 49 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) (limited to 'wqflask/tests') diff --git a/wqflask/tests/api/test_gen_menu.py b/wqflask/tests/api/test_gen_menu.py index a2a93da7..be66a4c6 100644 --- a/wqflask/tests/api/test_gen_menu.py +++ b/wqflask/tests/api/test_gen_menu.py @@ -4,6 +4,8 @@ import mock from wqflask.api.gen_menu import get_species from wqflask.api.gen_menu import get_groups +from wqflask.api.gen_menu import phenotypes_exist +from wqflask.api.gen_menu import genotypes_exist class TestGenMenu(unittest.TestCase): @@ -62,3 +64,50 @@ class TestGenMenu(unittest.TestCase): "InbredSet.FullName) ASC, InbredSet.FullName ASC, " + "InbredSet.MenuOrderId ASC").format(name) ) + + @mock.patch('wqflask.api.gen_menu.g') + def test_phenotypes_exist_called_with_correct_query(self, db_mock): + """Test that phenotypes_exist is called with the correct query""" + db_mock.db.execute.return_value.fetchone.return_value = None + phenotypes_exist("test") + db_mock.db.execute.assert_called_with( + "SELECT Name FROM PublishFreeze WHERE PublishFreeze.Name = 'testPublish'" + ) + + @mock.patch('wqflask.api.gen_menu.g') + def test_phenotypes_exist_with_falsy_values(self, db_mock): + """Test that phenotype check returns correctly when given a None value""" + for x in [None, False, (), [], ""]: + db_mock.db.execute.return_value.fetchone.return_value = x + self.assertFalse(phenotypes_exist("test")) + + @mock.patch('wqflask.api.gen_menu.g') + def test_phenotypes_exist_with_truthy_value(self, db_mock): + """Test that phenotype check returns correctly when given Truthy """ + for x in ["x", ("result"), ["result"], [1]]: + db_mock.db.execute.return_value.fetchone.return_value = (x) + self.assertTrue(phenotypes_exist("test")) + + @mock.patch('wqflask.api.gen_menu.g') + def test_genotypes_exist_called_with_correct_query(self, db_mock): + """Test that genotypes_exist is called with the correct query""" + db_mock.db.execute.return_value.fetchone.return_value = None + genotypes_exist("test") + db_mock.db.execute.assert_called_with( + "SELECT Name FROM GenoFreeze WHERE GenoFreeze.Name = 'testGeno'" + ) + + @mock.patch('wqflask.api.gen_menu.g') + def test_genotypes_exist_with_falsy_values(self, db_mock): + """Test that genotype check returns correctly when given a None value""" + for x in [None, False, (), [], ""]: + db_mock.db.execute.return_value.fetchone.return_value = x + self.assertFalse(genotypes_exist("test")) + + @mock.patch('wqflask.api.gen_menu.g') + def test_genotypes_exist_with_truthy_value(self, db_mock): + """Test that genotype check returns correctly when given Truthy """ + for x in ["x", ("result"), ["result"], [1]]: + db_mock.db.execute.return_value.fetchone.return_value = (x) + self.assertTrue(phenotypes_exist("test")) + -- cgit v1.2.3 From 99fae55d98e7042e0caf29c34fb77ee17efaafa2 Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Thu, 30 Jul 2020 16:13:39 +0300 Subject: Add tests for "build_datasets" * wqflask/tests/api/test_gen_menu.py: Add new tests for "build_datasets" function --- wqflask/tests/api/test_gen_menu.py | 66 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) (limited to 'wqflask/tests') diff --git a/wqflask/tests/api/test_gen_menu.py b/wqflask/tests/api/test_gen_menu.py index be66a4c6..ec380b6f 100644 --- a/wqflask/tests/api/test_gen_menu.py +++ b/wqflask/tests/api/test_gen_menu.py @@ -6,6 +6,7 @@ from wqflask.api.gen_menu import get_species from wqflask.api.gen_menu import get_groups from wqflask.api.gen_menu import phenotypes_exist from wqflask.api.gen_menu import genotypes_exist +from wqflask.api.gen_menu import build_datasets class TestGenMenu(unittest.TestCase): @@ -111,3 +112,68 @@ class TestGenMenu(unittest.TestCase): db_mock.db.execute.return_value.fetchone.return_value = (x) self.assertTrue(phenotypes_exist("test")) + + @mock.patch('wqflask.api.gen_menu.g') + def test_build_datasets_with_type_phenotypes(self, db_mock): + """Test that correct dataset is returned for a phenotype type""" + db_mock.db.execute.return_value.fetchall.return_value = ( + (602, "BXDPublish", "BXD Published Phenotypes"), + ) + self.assertEqual(build_datasets("Mouse", "BXD", "Phenotypes"), + [['602', "BXDPublish", "BXD Published Phenotypes"]]) + db_mock.db.execute.assert_called_with( + "SELECT InfoFiles.GN_AccesionId, PublishFreeze.Name, " + + "PublishFreeze.FullName FROM InfoFiles, PublishFreeze, " + + "InbredSet WHERE InbredSet.Name = 'BXD' AND " + + "PublishFreeze.InbredSetId = InbredSet.Id AND " + + "InfoFiles.InfoPageName = PublishFreeze.Name " + + "ORDER BY PublishFreeze.CreateTime ASC" + ) + self.assertEqual(build_datasets("Mouse", "MDP", "Phenotypes"), + [['602', "BXDPublish", "Mouse Phenome Database"]]) + + db_mock.db.execute.return_value.fetchall.return_value = () + db_mock.db.execute.return_value.fetchone.return_value = ( + "BXDPublish", "Mouse Phenome Database" + ) + self.assertEqual(build_datasets("Mouse", "MDP", "Phenotypes"), + [["None", "BXDPublish", "Mouse Phenome Database"]]) + + @mock.patch('wqflask.api.gen_menu.g') + def test_build_datasets_with_type_genotypes(self, db_mock): + """Test that correct dataset is returned for a phenotype type""" + db_mock.db.execute.return_value.fetchone.return_value = ( + 635, "HLCPublish", "HLC Published Genotypes" + ) + + self.assertEqual(build_datasets("Mouse", "HLC", "Genotypes"), + [["635", "HLCGeno", "HLC Genotypes"]]) + db_mock.db.execute.assert_called_with( + "SELECT InfoFiles.GN_AccesionId FROM InfoFiles, GenoFreeze, InbredSet " + + "WHERE InbredSet.Name = 'HLC' AND GenoFreeze.InbredSetId = InbredSet.Id AND " + + "InfoFiles.InfoPageName = GenoFreeze.ShortName " + + "ORDER BY GenoFreeze.CreateTime DESC" + ) + db_mock.db.execute.return_value.fetchone.return_value = () + self.assertEqual(build_datasets("Mouse", "HLC", "Genotypes"), + [["None", "HLCGeno", "HLC Genotypes"]]) + + @mock.patch('wqflask.api.gen_menu.g') + def test_build_datasets_with_type_mrna(self, db_mock): + """Test that correct dataset is returned for a mRNA expression/ Probeset""" + db_mock.db.execute.return_value.fetchall.return_value = ( + (112, "HC_M2_0606_P", + "Hippocampus Consortium M430v2 (Jun06) PDNN"), ) + self.assertEqual(build_datasets("Mouse", "HLC", "mRNA"), [[ + "112", 'HC_M2_0606_P', "Hippocampus Consortium M430v2 (Jun06) PDNN" + ]]) + db_mock.db.execute.assert_called_once_with( + "SELECT ProbeSetFreeze.Id, ProbeSetFreeze.Name, " + + "ProbeSetFreeze.FullName FROM ProbeSetFreeze, " + + "ProbeFreeze, InbredSet, Tissue, Species WHERE " + + "Species.Name = 'Mouse' AND Species.Id = " + + "InbredSet.SpeciesId AND InbredSet.Name = 'HLC' AND " + + "ProbeSetFreeze.ProbeFreezeId = ProbeFreeze.Id and " + + "Tissue.Name = 'mRNA' AND ProbeFreeze.TissueId = " + + "Tissue.Id and ProbeFreeze.InbredSetId = InbredSet.Id " + + "ORDER BY ProbeSetFreeze.CreateTime DESC") -- cgit v1.2.3 From 61634e932f8e03f5f53a94a56ff23f50dba891d2 Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Mon, 3 Aug 2020 11:24:40 +0300 Subject: Add test for "build_types" * wqflask/tests/api/test_gen_menu.py: New test --- wqflask/tests/api/test_gen_menu.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) (limited to 'wqflask/tests') diff --git a/wqflask/tests/api/test_gen_menu.py b/wqflask/tests/api/test_gen_menu.py index ec380b6f..24899765 100644 --- a/wqflask/tests/api/test_gen_menu.py +++ b/wqflask/tests/api/test_gen_menu.py @@ -7,6 +7,7 @@ from wqflask.api.gen_menu import get_groups from wqflask.api.gen_menu import phenotypes_exist from wqflask.api.gen_menu import genotypes_exist from wqflask.api.gen_menu import build_datasets +from wqflask.api.gen_menu import build_types class TestGenMenu(unittest.TestCase): @@ -177,3 +178,29 @@ class TestGenMenu(unittest.TestCase): "Tissue.Name = 'mRNA' AND ProbeFreeze.TissueId = " + "Tissue.Id and ProbeFreeze.InbredSetId = InbredSet.Id " + "ORDER BY ProbeSetFreeze.CreateTime DESC") + + @mock.patch('wqflask.api.gen_menu.build_datasets') + @mock.patch('wqflask.api.gen_menu.g') + def test_build_types(self, db_mock, datasets_mock): + """Test that correct tissue metadata is returned""" + datasets_mock.return_value = [ + ["112", 'HC_M2_0606_P', "Hippocampus Consortium M430v2 (Jun06) PDNN"] + ] + db_mock.db.execute.return_value.fetchall.return_value = ( + ('Mouse Tissue'), ('Human Tissue'), ('Rat Tissue') + ) + self.assertEqual(build_types('mouse', 'random group'), + [['M', 'M', 'Molecular Trait Datasets'], + ['H', 'H', 'Molecular Trait Datasets'], + ['R', 'R', 'Molecular Trait Datasets']]) + db_mock.db.execute.assert_called_once_with( + "SELECT DISTINCT Tissue.Name " + + "FROM ProbeFreeze, ProbeSetFreeze, InbredSet, " + + "Tissue, Species WHERE Species.Name = 'mouse' " + + "AND Species.Id = InbredSet.SpeciesId AND " + + "InbredSet.Name = 'random group' AND " + + "ProbeFreeze.TissueId = Tissue.Id AND " + + "ProbeFreeze.InbredSetId = InbredSet.Id AND " + + "ProbeSetFreeze.ProbeFreezeId = ProbeFreeze.Id " + + "ORDER BY Tissue.Name" + ) -- cgit v1.2.3 From bde13316e67bb56eb4a00b365ebb343ab6d00274 Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Mon, 3 Aug 2020 13:10:31 +0300 Subject: Add tests for "get_types" * wqflask/tests/api/test_gen_menu.py: Add new tests --- wqflask/tests/api/test_gen_menu.py | 105 +++++++++++++++++++++++++++++++++++++ 1 file changed, 105 insertions(+) (limited to 'wqflask/tests') diff --git a/wqflask/tests/api/test_gen_menu.py b/wqflask/tests/api/test_gen_menu.py index 24899765..0379e297 100644 --- a/wqflask/tests/api/test_gen_menu.py +++ b/wqflask/tests/api/test_gen_menu.py @@ -4,6 +4,7 @@ import mock from wqflask.api.gen_menu import get_species from wqflask.api.gen_menu import get_groups +from wqflask.api.gen_menu import get_types from wqflask.api.gen_menu import phenotypes_exist from wqflask.api.gen_menu import genotypes_exist from wqflask.api.gen_menu import build_datasets @@ -204,3 +205,107 @@ class TestGenMenu(unittest.TestCase): "ProbeSetFreeze.ProbeFreezeId = ProbeFreeze.Id " + "ORDER BY Tissue.Name" ) + + @mock.patch('wqflask.api.gen_menu.build_types') + @mock.patch('wqflask.api.gen_menu.genotypes_exist') + @mock.patch('wqflask.api.gen_menu.phenotypes_exist') + def test_get_types_with_existing_genotype_and_phenotypes( + self, + phenotypes_exist_mock, + genotypes_exist_mock, + build_types_mock): + """Test that build types are constructed correctly if phenotypes and genotypes + exist + + """ + phenotypes_exist_mock.return_value = True + genotypes_exist_mock.return_value = True + + expected_result = { + 'mouse': { + 'H_T2': [('Phenotypes', + 'Traits and Cofactors', + 'Phenotypes'), + ('Genotypes', + 'DNA Markers and SNPs', + 'Genotypes'), + ['M', 'M', 'Molecular Trait Datasets']], + 'H_T1': [('Phenotypes', + 'Traits and Cofactors', + 'Phenotypes'), + ('Genotypes', + 'DNA Markers and SNPs', + 'Genotypes'), + ['M', 'M', 'Molecular Trait Datasets']] + }, + 'human': { + 'HLC': [('Phenotypes', + 'Traits and Cofactors', + 'Phenotypes'), + ('Genotypes', + 'DNA Markers and SNPs', + 'Genotypes'), + ['M', 'M', 'Molecular Trait Datasets']], + 'BXD': [('Phenotypes', + 'Traits and Cofactors', + 'Phenotypes'), + ('Genotypes', + 'DNA Markers and SNPs', + 'Genotypes'), + ['M', 'M', 'Molecular Trait Datasets']] + } + } + + build_types_mock.return_value = [ + ['M', 'M', 'Molecular Trait Datasets'] + ] + self.assertEqual(get_types(self.test_group), expected_result) + + @mock.patch('wqflask.api.gen_menu.build_types') + @mock.patch('wqflask.api.gen_menu.genotypes_exist') + @mock.patch('wqflask.api.gen_menu.phenotypes_exist') + def test_get_types_with_buildtype_and_non_existent_genotype_and_phenotypes( + self, + phenotypes_exist_mock, + genotypes_exist_mock, + build_types_mock): + """Test that build types are constructed correctly if phenotypes_exist and + genotypes_exist are false but build_type is falsy + + """ + phenotypes_exist_mock.return_value = False + genotypes_exist_mock.return_value = False + + build_types_mock.return_value = [] + self.assertEqual(get_types(self.test_group), { + 'mouse': {}, + 'human': {} + }) + + @mock.patch('wqflask.api.gen_menu.build_types') + @mock.patch('wqflask.api.gen_menu.genotypes_exist') + @mock.patch('wqflask.api.gen_menu.phenotypes_exist') + def test_get_types_with_non_existent_genotype_phenotypes_and_buildtype( + self, + phenotypes_exist_mock, + genotypes_exist_mock, + build_types_mock): + """Test that build types are constructed correctly if phenotypes_exist, + genotypes_exist and build_types are truthy + + """ + phenotypes_exist_mock.return_value = False + genotypes_exist_mock.return_value = False + + build_types_mock.return_value = [ + ['M', 'M', 'Molecular Trait Datasets'] + ] + expected_result = { + 'mouse': { + 'H_T2': [['M', 'M', 'Molecular Trait Datasets']], + 'H_T1': [['M', 'M', 'Molecular Trait Datasets']]}, + 'human': { + 'HLC': [['M', 'M', 'Molecular Trait Datasets']], + 'BXD': [['M', 'M', 'Molecular Trait Datasets']]}} + self.assertEqual(get_types(self.test_group), + expected_result) -- cgit v1.2.3 From 899cf35a1dce7ad18645d00238fb39917f8e6e4f Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Mon, 3 Aug 2020 15:55:32 +0300 Subject: Add tests for "get_datasets" * wqflask/tests/api/test_gen_menu.py: Add new tests --- wqflask/tests/api/test_gen_menu.py | 74 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) (limited to 'wqflask/tests') diff --git a/wqflask/tests/api/test_gen_menu.py b/wqflask/tests/api/test_gen_menu.py index 0379e297..a606a300 100644 --- a/wqflask/tests/api/test_gen_menu.py +++ b/wqflask/tests/api/test_gen_menu.py @@ -5,6 +5,7 @@ import mock from wqflask.api.gen_menu import get_species from wqflask.api.gen_menu import get_groups from wqflask.api.gen_menu import get_types +from wqflask.api.gen_menu import get_datasets from wqflask.api.gen_menu import phenotypes_exist from wqflask.api.gen_menu import genotypes_exist from wqflask.api.gen_menu import build_datasets @@ -30,6 +31,41 @@ class TestGenMenu(unittest.TestCase): ] } + self.test_type = { + 'mouse': { + 'H_T2': [('Phenotypes', + 'Traits and Cofactors', + 'Phenotypes'), + ('Genotypes', + 'DNA Markers and SNPs', + 'Genotypes'), + ['M', 'M', 'Molecular Trait Datasets']], + 'H_T1': [('Phenotypes', + 'Traits and Cofactors', + 'Phenotypes'), + ('Genotypes', + 'DNA Markers and SNPs', + 'Genotypes'), + ['M', 'M', 'Molecular Trait Datasets']] + }, + 'human': { + 'HLC': [('Phenotypes', + 'Traits and Cofactors', + 'Phenotypes'), + ('Genotypes', + 'DNA Markers and SNPs', + 'Genotypes'), + ['M', 'M', 'Molecular Trait Datasets']], + 'BXD': [('Phenotypes', + 'Traits and Cofactors', + 'Phenotypes'), + ('Genotypes', + 'DNA Markers and SNPs', + 'Genotypes'), + ['M', 'M', 'Molecular Trait Datasets']] + } + } + @mock.patch('wqflask.api.gen_menu.g') def test_get_species(self, db_mock): """Test that assertion is raised when dataset and dataset_name are defined""" @@ -309,3 +345,41 @@ class TestGenMenu(unittest.TestCase): 'BXD': [['M', 'M', 'Molecular Trait Datasets']]}} self.assertEqual(get_types(self.test_group), expected_result) + + @mock.patch('wqflask.api.gen_menu.build_datasets') + def test_get_datasets_with_existent_datasets(self, + build_datasets_mock): + """Test correct dataset is returned with existent build_datasets""" + build_datasets_mock.return_value = "Test" + expected_result = { + 'mouse': { + 'H_T2': {'Genotypes': 'Test', + 'M': 'Test', + 'Phenotypes': 'Test'}, + 'H_T1': {'Genotypes': 'Test', + 'M': 'Test', + 'Phenotypes': 'Test'}}, + 'human': {'HLC': {'Genotypes': 'Test', + 'M': 'Test', + 'Phenotypes': 'Test'}, + 'BXD': {'Genotypes': 'Test', + 'M': 'Test', + 'Phenotypes': 'Test'}}} + self.maxDiff = None + self.assertEqual(get_datasets(self.test_type), + expected_result) + + @mock.patch('wqflask.api.gen_menu.build_datasets') + def test_get_datasets_with_non_existent_datasets(self, + build_datasets_mock): + """Test correct dataset is returned with non-existent build_datasets""" + build_datasets_mock.return_value = None + expected_result = { + 'mouse': { + 'H_T2': {}, + 'H_T1': {}}, + 'human': {'HLC': {}, + 'BXD': {}}} + self.assertEqual(get_datasets(self.test_type), + expected_result) + -- cgit v1.2.3 From 452f5442fec13afce07997494adc46fb4bbee9d7 Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Mon, 3 Aug 2020 16:07:08 +0300 Subject: Add test for "gen_dropdown_json" * wqflask/tests/api/test_gen_menu.py: Add new test --- wqflask/tests/api/test_gen_menu.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) (limited to 'wqflask/tests') diff --git a/wqflask/tests/api/test_gen_menu.py b/wqflask/tests/api/test_gen_menu.py index a606a300..92485d38 100644 --- a/wqflask/tests/api/test_gen_menu.py +++ b/wqflask/tests/api/test_gen_menu.py @@ -2,6 +2,7 @@ import unittest import mock +from wqflask.api.gen_menu import gen_dropdown_json from wqflask.api.gen_menu import get_species from wqflask.api.gen_menu import get_groups from wqflask.api.gen_menu import get_types @@ -383,3 +384,31 @@ class TestGenMenu(unittest.TestCase): self.assertEqual(get_datasets(self.test_type), expected_result) + @mock.patch('wqflask.api.gen_menu.get_datasets') + @mock.patch('wqflask.api.gen_menu.get_types') + @mock.patch('wqflask.api.gen_menu.get_groups') + @mock.patch('wqflask.api.gen_menu.get_species') + def test_gen_dropdown_json(self, + species_mock, + groups_mock, + types_mock, + datasets_mock): + "Test that the correct dictionary is constructed properly" + species_mock.return_value = ("speciesA speciesB speciesC speciesD" + .split(" ")) + datasets_mock.return_value = ("datasetA datasetB datasetC datasetD" + .split(" ")) + groups_mock.return_value = ("groupA groupB groupC groupD" + .split(" ")) + types_mock.return_value = ("typeA typeB typeC typeD" + .split(" ")) + datasets_mock.return_value = ("datasetA datasetB datasetC datasetD" + .split(" ")) + + expected_result = { + 'datasets': ['datasetA', 'datasetB', 'datasetC', 'datasetD'], + 'types': ['typeA', 'typeB', 'typeC', 'typeD'], + 'groups': ['groupA', 'groupB', 'groupC', 'groupD'], + 'species': ['speciesA', 'speciesB', 'speciesC', 'speciesD']} + + self.assertEqual(gen_dropdown_json(), expected_result) -- cgit v1.2.3 From 30341891c22e2161c1217f808ed05748c91036e2 Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Mon, 3 Aug 2020 16:46:33 +0300 Subject: Move variable to setUp * wqflask/tests/api/test_gen_menu.py: Move variable --- wqflask/tests/api/test_gen_menu.py | 35 +---------------------------------- 1 file changed, 1 insertion(+), 34 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/api/test_gen_menu.py b/wqflask/tests/api/test_gen_menu.py index 92485d38..ca841708 100644 --- a/wqflask/tests/api/test_gen_menu.py +++ b/wqflask/tests/api/test_gen_menu.py @@ -258,40 +258,7 @@ class TestGenMenu(unittest.TestCase): phenotypes_exist_mock.return_value = True genotypes_exist_mock.return_value = True - expected_result = { - 'mouse': { - 'H_T2': [('Phenotypes', - 'Traits and Cofactors', - 'Phenotypes'), - ('Genotypes', - 'DNA Markers and SNPs', - 'Genotypes'), - ['M', 'M', 'Molecular Trait Datasets']], - 'H_T1': [('Phenotypes', - 'Traits and Cofactors', - 'Phenotypes'), - ('Genotypes', - 'DNA Markers and SNPs', - 'Genotypes'), - ['M', 'M', 'Molecular Trait Datasets']] - }, - 'human': { - 'HLC': [('Phenotypes', - 'Traits and Cofactors', - 'Phenotypes'), - ('Genotypes', - 'DNA Markers and SNPs', - 'Genotypes'), - ['M', 'M', 'Molecular Trait Datasets']], - 'BXD': [('Phenotypes', - 'Traits and Cofactors', - 'Phenotypes'), - ('Genotypes', - 'DNA Markers and SNPs', - 'Genotypes'), - ['M', 'M', 'Molecular Trait Datasets']] - } - } + expected_result = self.test_type build_types_mock.return_value = [ ['M', 'M', 'Molecular Trait Datasets'] -- cgit v1.2.3 From 77a55f3cfe70dfbe319c28380eb16a4f9516366c Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Mon, 3 Aug 2020 16:47:42 +0300 Subject: Add extra test for "build_datasets" * wqflask/tests/api/test_gen_menu.py: Add test. --- wqflask/tests/api/test_gen_menu.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) (limited to 'wqflask/tests') diff --git a/wqflask/tests/api/test_gen_menu.py b/wqflask/tests/api/test_gen_menu.py index ca841708..4a928d12 100644 --- a/wqflask/tests/api/test_gen_menu.py +++ b/wqflask/tests/api/test_gen_menu.py @@ -178,6 +178,25 @@ class TestGenMenu(unittest.TestCase): self.assertEqual(build_datasets("Mouse", "MDP", "Phenotypes"), [["None", "BXDPublish", "Mouse Phenome Database"]]) + @mock.patch('wqflask.api.gen_menu.g') + def test_build_datasets_with_type_phenotypes_and_no_results(self, db_mock): + """Test that correct dataset is returned for a phenotype type with no + results + + """ + db_mock.db.execute.return_value.fetchall.return_value = None + db_mock.db.execute.return_value.fetchone.return_value = (121, + "text value") + self.assertEqual(build_datasets("Mouse", "BXD", "Phenotypes"), + [["None", "121", "text value"]]) + db_mock.db.execute.assert_called_with( + "SELECT PublishFreeze.Name, PublishFreeze.FullName " + "FROM PublishFreeze, InbredSet " + "WHERE InbredSet.Name = 'BXD' AND " + "PublishFreeze.InbredSetId = InbredSet.Id " + "ORDER BY PublishFreeze.CreateTime ASC" + ) + @mock.patch('wqflask.api.gen_menu.g') def test_build_datasets_with_type_genotypes(self, db_mock): """Test that correct dataset is returned for a phenotype type""" -- cgit v1.2.3 From 8fa2d7cc9d3d6599d1c44a6f5e76decf932b2cbd Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Mon, 3 Aug 2020 16:54:57 +0300 Subject: Fix some errors generated by running pylint * wqflask/wqflask/api/gen_menu.py: Apply pylint. * wqflask/tests/api/test_gen_menu.py: Apply pylint. --- wqflask/tests/api/test_gen_menu.py | 33 +++++++++------ wqflask/wqflask/api/gen_menu.py | 83 +++++++++++++++++++++----------------- 2 files changed, 66 insertions(+), 50 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/api/test_gen_menu.py b/wqflask/tests/api/test_gen_menu.py index 4a928d12..79c77fec 100644 --- a/wqflask/tests/api/test_gen_menu.py +++ b/wqflask/tests/api/test_gen_menu.py @@ -69,9 +69,11 @@ class TestGenMenu(unittest.TestCase): @mock.patch('wqflask.api.gen_menu.g') def test_get_species(self, db_mock): - """Test that assertion is raised when dataset and dataset_name are defined""" - db_mock.db.execute.return_value.fetchall.return_value = (('human', 'Human'), - ('mouse', 'Mouse')) + """Test that assertion is raised when dataset and dataset_name + are defined""" + db_mock.db.execute.return_value.fetchall.return_value = ( + ('human', 'Human'), + ('mouse', 'Mouse')) self.assertEqual(get_species(), [['human', 'Human'], ['mouse', 'Mouse']]) db_mock.db.execute.assert_called_once_with( @@ -84,7 +86,8 @@ class TestGenMenu(unittest.TestCase): db_mock.db.execute.return_value.fetchall.side_effect = [ # Mouse (('BXD', 'BXD', None), - ('HLC', 'Liver: Normal Gene Expression with Genotypes (Merck)', 'Test')), + ('HLC', 'Liver: Normal Gene Expression with Genotypes (Merck)', + 'Test')), # Human (('H_T1', "H_T", "DescriptionA"), ('H_T2', "H_T'", None)) @@ -111,12 +114,14 @@ class TestGenMenu(unittest.TestCase): db_mock.db.execute.return_value.fetchone.return_value = None phenotypes_exist("test") db_mock.db.execute.assert_called_with( - "SELECT Name FROM PublishFreeze WHERE PublishFreeze.Name = 'testPublish'" + "SELECT Name FROM PublishFreeze " + "WHERE PublishFreeze.Name = 'testPublish'" ) @mock.patch('wqflask.api.gen_menu.g') def test_phenotypes_exist_with_falsy_values(self, db_mock): - """Test that phenotype check returns correctly when given a None value""" + """Test that phenotype check returns correctly when given + a None value""" for x in [None, False, (), [], ""]: db_mock.db.execute.return_value.fetchone.return_value = x self.assertFalse(phenotypes_exist("test")) @@ -139,7 +144,8 @@ class TestGenMenu(unittest.TestCase): @mock.patch('wqflask.api.gen_menu.g') def test_genotypes_exist_with_falsy_values(self, db_mock): - """Test that genotype check returns correctly when given a None value""" + """Test that genotype check returns correctly when given + a None value""" for x in [None, False, (), [], ""]: db_mock.db.execute.return_value.fetchone.return_value = x self.assertFalse(genotypes_exist("test")) @@ -151,7 +157,6 @@ class TestGenMenu(unittest.TestCase): db_mock.db.execute.return_value.fetchone.return_value = (x) self.assertTrue(phenotypes_exist("test")) - @mock.patch('wqflask.api.gen_menu.g') def test_build_datasets_with_type_phenotypes(self, db_mock): """Test that correct dataset is returned for a phenotype type""" @@ -207,8 +212,9 @@ class TestGenMenu(unittest.TestCase): self.assertEqual(build_datasets("Mouse", "HLC", "Genotypes"), [["635", "HLCGeno", "HLC Genotypes"]]) db_mock.db.execute.assert_called_with( - "SELECT InfoFiles.GN_AccesionId FROM InfoFiles, GenoFreeze, InbredSet " + - "WHERE InbredSet.Name = 'HLC' AND GenoFreeze.InbredSetId = InbredSet.Id AND " + + "SELECT InfoFiles.GN_AccesionId FROM InfoFiles, " + "GenoFreeze, InbredSet WHERE InbredSet.Name = 'HLC' AND " + "GenoFreeze.InbredSetId = InbredSet.Id AND " "InfoFiles.InfoPageName = GenoFreeze.ShortName " + "ORDER BY GenoFreeze.CreateTime DESC" ) @@ -218,7 +224,8 @@ class TestGenMenu(unittest.TestCase): @mock.patch('wqflask.api.gen_menu.g') def test_build_datasets_with_type_mrna(self, db_mock): - """Test that correct dataset is returned for a mRNA expression/ Probeset""" + """Test that correct dataset is returned for a mRNA + expression/ Probeset""" db_mock.db.execute.return_value.fetchall.return_value = ( (112, "HC_M2_0606_P", "Hippocampus Consortium M430v2 (Jun06) PDNN"), ) @@ -241,7 +248,8 @@ class TestGenMenu(unittest.TestCase): def test_build_types(self, db_mock, datasets_mock): """Test that correct tissue metadata is returned""" datasets_mock.return_value = [ - ["112", 'HC_M2_0606_P', "Hippocampus Consortium M430v2 (Jun06) PDNN"] + ["112", 'HC_M2_0606_P', + "Hippocampus Consortium M430v2 (Jun06) PDNN"] ] db_mock.db.execute.return_value.fetchall.return_value = ( ('Mouse Tissue'), ('Human Tissue'), ('Rat Tissue') @@ -352,7 +360,6 @@ class TestGenMenu(unittest.TestCase): 'BXD': {'Genotypes': 'Test', 'M': 'Test', 'Phenotypes': 'Test'}}} - self.maxDiff = None self.assertEqual(get_datasets(self.test_type), expected_result) diff --git a/wqflask/wqflask/api/gen_menu.py b/wqflask/wqflask/api/gen_menu.py index 82c5d9be..45814ed9 100644 --- a/wqflask/wqflask/api/gen_menu.py +++ b/wqflask/wqflask/api/gen_menu.py @@ -1,21 +1,12 @@ from __future__ import print_function, division -import sys - from flask import g -from utility.tools import locate, locate_ignore_error, TEMPDIR, SQL_URI -from utility.benchmark import Bench - -import MySQLdb - -import urlparse - -import utility.logger -logger = utility.logger.getLogger(__name__ ) def gen_dropdown_json(): - """Generates and outputs (as json file) the data for the main dropdown menus on the home page""" + """Generates and outputs (as json file) the data for the main dropdown menus on + the home page + """ species = get_species() groups = get_groups(species) @@ -29,9 +20,11 @@ def gen_dropdown_json(): return data + def get_species(): """Build species list""" - results = g.db.execute("SELECT Name, MenuName FROM Species ORDER BY OrderId").fetchall() + results = g.db.execute( + "SELECT Name, MenuName FROM Species ORDER BY OrderId").fetchall() species = [] for result in results: @@ -39,6 +32,7 @@ def get_species(): return species + def get_groups(species): """Build groups list""" groups = {} @@ -46,18 +40,23 @@ def get_groups(species): groups[species_name] = [] results = g.db.execute( - ("SELECT InbredSet.Name, InbredSet.FullName, IFNULL(InbredSet.Family, 'None') " + - "FROM InbredSet, Species WHERE Species.Name = '{}' AND InbredSet.SpeciesId = " + - "Species.Id GROUP by InbredSet.Name ORDER BY IFNULL(InbredSet.FamilyOrder, " + - "InbredSet.FullName) ASC, IFNULL(InbredSet.Family, InbredSet.FullName) ASC, " + - "InbredSet.FullName ASC, InbredSet.MenuOrderId ASC").format(species_name)).fetchall() + ("SELECT InbredSet.Name, InbredSet.FullName, " + "IFNULL(InbredSet.Family, 'None') " + "FROM InbredSet, Species WHERE Species.Name = '{}' " + "AND InbredSet.SpeciesId = Species.Id GROUP by InbredSet.Name " + "ORDER BY IFNULL(InbredSet.FamilyOrder, InbredSet.FullName) " + "ASC, IFNULL(InbredSet.Family, InbredSet.FullName) ASC, " + "InbredSet.FullName ASC, InbredSet.MenuOrderId ASC") + .format(species_name)).fetchall() for result in results: family_name = "Family:" + str(result[2]) - groups[species_name].append([str(result[0]), str(result[1]), family_name]) + groups[species_name].append( + [str(result[0]), str(result[1]), family_name]) return groups + def get_types(groups): """Build types list""" types = {} @@ -66,12 +65,15 @@ def get_types(groups): types[species] = {} for group_name, _group_full_name, _family_name in group_dict: if phenotypes_exist(group_name): - types[species][group_name] = [("Phenotypes", "Traits and Cofactors", "Phenotypes")] + types[species][group_name] = [ + ("Phenotypes", "Traits and Cofactors", "Phenotypes")] if genotypes_exist(group_name): if group_name in types[species]: - types[species][group_name] += [("Genotypes", "DNA Markers and SNPs", "Genotypes")] + types[species][group_name] += [ + ("Genotypes", "DNA Markers and SNPs", "Genotypes")] else: - types[species][group_name] = [("Genotypes", "DNA Markers and SNPs", "Genotypes")] + types[species][group_name] = [ + ("Genotypes", "DNA Markers and SNPs", "Genotypes")] if group_name in types[species]: types_list = build_types(species, group_name) if len(types_list) > 0: @@ -82,13 +84,17 @@ def get_types(groups): types[species][group_name] = types_list else: types[species].pop(group_name, None) - groups[species] = list(group for group in groups[species] if group[0] != group_name) + groups[species] = list( + group for group in groups[species] + if group[0] != group_name) return types + def phenotypes_exist(group_name): results = g.db.execute( - ("SELECT Name FROM PublishFreeze " + - "WHERE PublishFreeze.Name = '{}'").format(group_name+"Publish")).fetchone() + ("SELECT Name FROM PublishFreeze " + "WHERE PublishFreeze.Name = " + "'{}'").format(group_name+"Publish")).fetchone() return bool(results) @@ -118,13 +124,15 @@ def build_types(species, group): results = [] for result in g.db.execute(query).fetchall(): - if len(result): + if bool(result): these_datasets = build_datasets(species, group, result[0]) if len(these_datasets) > 0: - results.append([str(result[0]), str(result[0]), "Molecular Trait Datasets"]) + results.append([str(result[0]), str(result[0]), + "Molecular Trait Datasets"]) return results + def get_datasets(types): """Build datasets list""" datasets = {} @@ -192,17 +200,18 @@ def build_datasets(species, group, type_name): dataset_text = "%s Genotypes" % group datasets.append([dataset_id, dataset_value, dataset_text]) - else: # for mRNA expression/ProbeSet + else: # for mRNA expression/ProbeSet results = g.db.execute( - ("SELECT ProbeSetFreeze.Id, ProbeSetFreeze.Name, " + - "ProbeSetFreeze.FullName FROM ProbeSetFreeze, " + - "ProbeFreeze, InbredSet, Tissue, Species WHERE " + - "Species.Name = '{0}' AND Species.Id = " + - "InbredSet.SpeciesId AND InbredSet.Name = '{1}' " + - "AND ProbeSetFreeze.ProbeFreezeId = ProbeFreeze.Id " + - "and Tissue.Name = '{2}' AND ProbeFreeze.TissueId = " + - "Tissue.Id and ProbeFreeze.InbredSetId = InbredSet.Id " + - "ORDER BY ProbeSetFreeze.CreateTime DESC").format(species, group, type_name)).fetchall() + ("SELECT ProbeSetFreeze.Id, ProbeSetFreeze.Name, " + "ProbeSetFreeze.FullName FROM ProbeSetFreeze, " + "ProbeFreeze, InbredSet, Tissue, Species WHERE " + "Species.Name = '{0}' AND Species.Id = " + "InbredSet.SpeciesId AND InbredSet.Name = '{1}' " + "AND ProbeSetFreeze.ProbeFreezeId = ProbeFreeze.Id " + "and Tissue.Name = '{2}' AND ProbeFreeze.TissueId = " + "Tissue.Id and ProbeFreeze.InbredSetId = InbredSet.Id " + "ORDER BY ProbeSetFreeze.CreateTime " + "DESC").format(species, group, type_name)).fetchall() datasets = [] for dataset_info in results: -- cgit v1.2.3 From abbceb6cde72282b8b85e9452d45e3d6ecc41da5 Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Fri, 7 Aug 2020 15:07:52 +0300 Subject: Move wqflask/tests/api to wqflask/tests/wqflask * wqflask/tests(api): Move all the files here to tests/wqflask. The test dir should mirror the actual module structure --- wqflask/tests/api/__init__.py | 0 wqflask/tests/api/test_gen_menu.py | 407 ----------------------------- wqflask/tests/wqflask/__init__.py | 0 wqflask/tests/wqflask/api/__init__.py | 0 wqflask/tests/wqflask/api/test_gen_menu.py | 407 +++++++++++++++++++++++++++++ 5 files changed, 407 insertions(+), 407 deletions(-) delete mode 100644 wqflask/tests/api/__init__.py delete mode 100644 wqflask/tests/api/test_gen_menu.py create mode 100644 wqflask/tests/wqflask/__init__.py create mode 100644 wqflask/tests/wqflask/api/__init__.py create mode 100644 wqflask/tests/wqflask/api/test_gen_menu.py (limited to 'wqflask/tests') diff --git a/wqflask/tests/api/__init__.py b/wqflask/tests/api/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/wqflask/tests/api/test_gen_menu.py b/wqflask/tests/api/test_gen_menu.py deleted file mode 100644 index 79c77fec..00000000 --- a/wqflask/tests/api/test_gen_menu.py +++ /dev/null @@ -1,407 +0,0 @@ -"""Test cases for wqflask.api.gen_menu""" -import unittest -import mock - -from wqflask.api.gen_menu import gen_dropdown_json -from wqflask.api.gen_menu import get_species -from wqflask.api.gen_menu import get_groups -from wqflask.api.gen_menu import get_types -from wqflask.api.gen_menu import get_datasets -from wqflask.api.gen_menu import phenotypes_exist -from wqflask.api.gen_menu import genotypes_exist -from wqflask.api.gen_menu import build_datasets -from wqflask.api.gen_menu import build_types - - -class TestGenMenu(unittest.TestCase): - """Tests for the gen_menu module""" - - def setUp(self): - self.test_group = { - 'mouse': [ - ['H_T1', - 'H_T', - 'Family:DescriptionA' - ], - ['H_T2', "H_T'", 'Family:None'] - ], - 'human': [ - ['BXD', 'BXD', 'Family:None'], - ['HLC', 'Liver: Normal Gene Expression with Genotypes (Merck)', - 'Family:Test'] - ] - } - - self.test_type = { - 'mouse': { - 'H_T2': [('Phenotypes', - 'Traits and Cofactors', - 'Phenotypes'), - ('Genotypes', - 'DNA Markers and SNPs', - 'Genotypes'), - ['M', 'M', 'Molecular Trait Datasets']], - 'H_T1': [('Phenotypes', - 'Traits and Cofactors', - 'Phenotypes'), - ('Genotypes', - 'DNA Markers and SNPs', - 'Genotypes'), - ['M', 'M', 'Molecular Trait Datasets']] - }, - 'human': { - 'HLC': [('Phenotypes', - 'Traits and Cofactors', - 'Phenotypes'), - ('Genotypes', - 'DNA Markers and SNPs', - 'Genotypes'), - ['M', 'M', 'Molecular Trait Datasets']], - 'BXD': [('Phenotypes', - 'Traits and Cofactors', - 'Phenotypes'), - ('Genotypes', - 'DNA Markers and SNPs', - 'Genotypes'), - ['M', 'M', 'Molecular Trait Datasets']] - } - } - - @mock.patch('wqflask.api.gen_menu.g') - def test_get_species(self, db_mock): - """Test that assertion is raised when dataset and dataset_name - are defined""" - db_mock.db.execute.return_value.fetchall.return_value = ( - ('human', 'Human'), - ('mouse', 'Mouse')) - self.assertEqual(get_species(), - [['human', 'Human'], ['mouse', 'Mouse']]) - db_mock.db.execute.assert_called_once_with( - "SELECT Name, MenuName FROM Species ORDER BY OrderId" - ) - - @mock.patch('wqflask.api.gen_menu.g') - def test_get_groups(self, db_mock): - """Test that species groups are grouped correctly""" - db_mock.db.execute.return_value.fetchall.side_effect = [ - # Mouse - (('BXD', 'BXD', None), - ('HLC', 'Liver: Normal Gene Expression with Genotypes (Merck)', - 'Test')), - # Human - (('H_T1', "H_T", "DescriptionA"), - ('H_T2', "H_T'", None)) - ] - - self.assertEqual(get_groups([["human", "Human"], ["mouse", "Mouse"]]), - self.test_group) - - for name in ["mouse", "human"]: - db_mock.db.execute.assert_any_call( - ("SELECT InbredSet.Name, InbredSet.FullName, " + - "IFNULL(InbredSet.Family, 'None') " + - "FROM InbredSet, Species WHERE Species.Name " + - "= '{}' AND InbredSet.SpeciesId = Species.Id GROUP by " + - "InbredSet.Name ORDER BY IFNULL(InbredSet.FamilyOrder, " + - "InbredSet.FullName) ASC, IFNULL(InbredSet.Family, " + - "InbredSet.FullName) ASC, InbredSet.FullName ASC, " + - "InbredSet.MenuOrderId ASC").format(name) - ) - - @mock.patch('wqflask.api.gen_menu.g') - def test_phenotypes_exist_called_with_correct_query(self, db_mock): - """Test that phenotypes_exist is called with the correct query""" - db_mock.db.execute.return_value.fetchone.return_value = None - phenotypes_exist("test") - db_mock.db.execute.assert_called_with( - "SELECT Name FROM PublishFreeze " - "WHERE PublishFreeze.Name = 'testPublish'" - ) - - @mock.patch('wqflask.api.gen_menu.g') - def test_phenotypes_exist_with_falsy_values(self, db_mock): - """Test that phenotype check returns correctly when given - a None value""" - for x in [None, False, (), [], ""]: - db_mock.db.execute.return_value.fetchone.return_value = x - self.assertFalse(phenotypes_exist("test")) - - @mock.patch('wqflask.api.gen_menu.g') - def test_phenotypes_exist_with_truthy_value(self, db_mock): - """Test that phenotype check returns correctly when given Truthy """ - for x in ["x", ("result"), ["result"], [1]]: - db_mock.db.execute.return_value.fetchone.return_value = (x) - self.assertTrue(phenotypes_exist("test")) - - @mock.patch('wqflask.api.gen_menu.g') - def test_genotypes_exist_called_with_correct_query(self, db_mock): - """Test that genotypes_exist is called with the correct query""" - db_mock.db.execute.return_value.fetchone.return_value = None - genotypes_exist("test") - db_mock.db.execute.assert_called_with( - "SELECT Name FROM GenoFreeze WHERE GenoFreeze.Name = 'testGeno'" - ) - - @mock.patch('wqflask.api.gen_menu.g') - def test_genotypes_exist_with_falsy_values(self, db_mock): - """Test that genotype check returns correctly when given - a None value""" - for x in [None, False, (), [], ""]: - db_mock.db.execute.return_value.fetchone.return_value = x - self.assertFalse(genotypes_exist("test")) - - @mock.patch('wqflask.api.gen_menu.g') - def test_genotypes_exist_with_truthy_value(self, db_mock): - """Test that genotype check returns correctly when given Truthy """ - for x in ["x", ("result"), ["result"], [1]]: - db_mock.db.execute.return_value.fetchone.return_value = (x) - self.assertTrue(phenotypes_exist("test")) - - @mock.patch('wqflask.api.gen_menu.g') - def test_build_datasets_with_type_phenotypes(self, db_mock): - """Test that correct dataset is returned for a phenotype type""" - db_mock.db.execute.return_value.fetchall.return_value = ( - (602, "BXDPublish", "BXD Published Phenotypes"), - ) - self.assertEqual(build_datasets("Mouse", "BXD", "Phenotypes"), - [['602', "BXDPublish", "BXD Published Phenotypes"]]) - db_mock.db.execute.assert_called_with( - "SELECT InfoFiles.GN_AccesionId, PublishFreeze.Name, " + - "PublishFreeze.FullName FROM InfoFiles, PublishFreeze, " + - "InbredSet WHERE InbredSet.Name = 'BXD' AND " + - "PublishFreeze.InbredSetId = InbredSet.Id AND " + - "InfoFiles.InfoPageName = PublishFreeze.Name " + - "ORDER BY PublishFreeze.CreateTime ASC" - ) - self.assertEqual(build_datasets("Mouse", "MDP", "Phenotypes"), - [['602', "BXDPublish", "Mouse Phenome Database"]]) - - db_mock.db.execute.return_value.fetchall.return_value = () - db_mock.db.execute.return_value.fetchone.return_value = ( - "BXDPublish", "Mouse Phenome Database" - ) - self.assertEqual(build_datasets("Mouse", "MDP", "Phenotypes"), - [["None", "BXDPublish", "Mouse Phenome Database"]]) - - @mock.patch('wqflask.api.gen_menu.g') - def test_build_datasets_with_type_phenotypes_and_no_results(self, db_mock): - """Test that correct dataset is returned for a phenotype type with no - results - - """ - db_mock.db.execute.return_value.fetchall.return_value = None - db_mock.db.execute.return_value.fetchone.return_value = (121, - "text value") - self.assertEqual(build_datasets("Mouse", "BXD", "Phenotypes"), - [["None", "121", "text value"]]) - db_mock.db.execute.assert_called_with( - "SELECT PublishFreeze.Name, PublishFreeze.FullName " - "FROM PublishFreeze, InbredSet " - "WHERE InbredSet.Name = 'BXD' AND " - "PublishFreeze.InbredSetId = InbredSet.Id " - "ORDER BY PublishFreeze.CreateTime ASC" - ) - - @mock.patch('wqflask.api.gen_menu.g') - def test_build_datasets_with_type_genotypes(self, db_mock): - """Test that correct dataset is returned for a phenotype type""" - db_mock.db.execute.return_value.fetchone.return_value = ( - 635, "HLCPublish", "HLC Published Genotypes" - ) - - self.assertEqual(build_datasets("Mouse", "HLC", "Genotypes"), - [["635", "HLCGeno", "HLC Genotypes"]]) - db_mock.db.execute.assert_called_with( - "SELECT InfoFiles.GN_AccesionId FROM InfoFiles, " - "GenoFreeze, InbredSet WHERE InbredSet.Name = 'HLC' AND " - "GenoFreeze.InbredSetId = InbredSet.Id AND " - "InfoFiles.InfoPageName = GenoFreeze.ShortName " + - "ORDER BY GenoFreeze.CreateTime DESC" - ) - db_mock.db.execute.return_value.fetchone.return_value = () - self.assertEqual(build_datasets("Mouse", "HLC", "Genotypes"), - [["None", "HLCGeno", "HLC Genotypes"]]) - - @mock.patch('wqflask.api.gen_menu.g') - def test_build_datasets_with_type_mrna(self, db_mock): - """Test that correct dataset is returned for a mRNA - expression/ Probeset""" - db_mock.db.execute.return_value.fetchall.return_value = ( - (112, "HC_M2_0606_P", - "Hippocampus Consortium M430v2 (Jun06) PDNN"), ) - self.assertEqual(build_datasets("Mouse", "HLC", "mRNA"), [[ - "112", 'HC_M2_0606_P', "Hippocampus Consortium M430v2 (Jun06) PDNN" - ]]) - db_mock.db.execute.assert_called_once_with( - "SELECT ProbeSetFreeze.Id, ProbeSetFreeze.Name, " + - "ProbeSetFreeze.FullName FROM ProbeSetFreeze, " + - "ProbeFreeze, InbredSet, Tissue, Species WHERE " + - "Species.Name = 'Mouse' AND Species.Id = " + - "InbredSet.SpeciesId AND InbredSet.Name = 'HLC' AND " + - "ProbeSetFreeze.ProbeFreezeId = ProbeFreeze.Id and " + - "Tissue.Name = 'mRNA' AND ProbeFreeze.TissueId = " + - "Tissue.Id and ProbeFreeze.InbredSetId = InbredSet.Id " + - "ORDER BY ProbeSetFreeze.CreateTime DESC") - - @mock.patch('wqflask.api.gen_menu.build_datasets') - @mock.patch('wqflask.api.gen_menu.g') - def test_build_types(self, db_mock, datasets_mock): - """Test that correct tissue metadata is returned""" - datasets_mock.return_value = [ - ["112", 'HC_M2_0606_P', - "Hippocampus Consortium M430v2 (Jun06) PDNN"] - ] - db_mock.db.execute.return_value.fetchall.return_value = ( - ('Mouse Tissue'), ('Human Tissue'), ('Rat Tissue') - ) - self.assertEqual(build_types('mouse', 'random group'), - [['M', 'M', 'Molecular Trait Datasets'], - ['H', 'H', 'Molecular Trait Datasets'], - ['R', 'R', 'Molecular Trait Datasets']]) - db_mock.db.execute.assert_called_once_with( - "SELECT DISTINCT Tissue.Name " + - "FROM ProbeFreeze, ProbeSetFreeze, InbredSet, " + - "Tissue, Species WHERE Species.Name = 'mouse' " + - "AND Species.Id = InbredSet.SpeciesId AND " + - "InbredSet.Name = 'random group' AND " + - "ProbeFreeze.TissueId = Tissue.Id AND " + - "ProbeFreeze.InbredSetId = InbredSet.Id AND " + - "ProbeSetFreeze.ProbeFreezeId = ProbeFreeze.Id " + - "ORDER BY Tissue.Name" - ) - - @mock.patch('wqflask.api.gen_menu.build_types') - @mock.patch('wqflask.api.gen_menu.genotypes_exist') - @mock.patch('wqflask.api.gen_menu.phenotypes_exist') - def test_get_types_with_existing_genotype_and_phenotypes( - self, - phenotypes_exist_mock, - genotypes_exist_mock, - build_types_mock): - """Test that build types are constructed correctly if phenotypes and genotypes - exist - - """ - phenotypes_exist_mock.return_value = True - genotypes_exist_mock.return_value = True - - expected_result = self.test_type - - build_types_mock.return_value = [ - ['M', 'M', 'Molecular Trait Datasets'] - ] - self.assertEqual(get_types(self.test_group), expected_result) - - @mock.patch('wqflask.api.gen_menu.build_types') - @mock.patch('wqflask.api.gen_menu.genotypes_exist') - @mock.patch('wqflask.api.gen_menu.phenotypes_exist') - def test_get_types_with_buildtype_and_non_existent_genotype_and_phenotypes( - self, - phenotypes_exist_mock, - genotypes_exist_mock, - build_types_mock): - """Test that build types are constructed correctly if phenotypes_exist and - genotypes_exist are false but build_type is falsy - - """ - phenotypes_exist_mock.return_value = False - genotypes_exist_mock.return_value = False - - build_types_mock.return_value = [] - self.assertEqual(get_types(self.test_group), { - 'mouse': {}, - 'human': {} - }) - - @mock.patch('wqflask.api.gen_menu.build_types') - @mock.patch('wqflask.api.gen_menu.genotypes_exist') - @mock.patch('wqflask.api.gen_menu.phenotypes_exist') - def test_get_types_with_non_existent_genotype_phenotypes_and_buildtype( - self, - phenotypes_exist_mock, - genotypes_exist_mock, - build_types_mock): - """Test that build types are constructed correctly if phenotypes_exist, - genotypes_exist and build_types are truthy - - """ - phenotypes_exist_mock.return_value = False - genotypes_exist_mock.return_value = False - - build_types_mock.return_value = [ - ['M', 'M', 'Molecular Trait Datasets'] - ] - expected_result = { - 'mouse': { - 'H_T2': [['M', 'M', 'Molecular Trait Datasets']], - 'H_T1': [['M', 'M', 'Molecular Trait Datasets']]}, - 'human': { - 'HLC': [['M', 'M', 'Molecular Trait Datasets']], - 'BXD': [['M', 'M', 'Molecular Trait Datasets']]}} - self.assertEqual(get_types(self.test_group), - expected_result) - - @mock.patch('wqflask.api.gen_menu.build_datasets') - def test_get_datasets_with_existent_datasets(self, - build_datasets_mock): - """Test correct dataset is returned with existent build_datasets""" - build_datasets_mock.return_value = "Test" - expected_result = { - 'mouse': { - 'H_T2': {'Genotypes': 'Test', - 'M': 'Test', - 'Phenotypes': 'Test'}, - 'H_T1': {'Genotypes': 'Test', - 'M': 'Test', - 'Phenotypes': 'Test'}}, - 'human': {'HLC': {'Genotypes': 'Test', - 'M': 'Test', - 'Phenotypes': 'Test'}, - 'BXD': {'Genotypes': 'Test', - 'M': 'Test', - 'Phenotypes': 'Test'}}} - self.assertEqual(get_datasets(self.test_type), - expected_result) - - @mock.patch('wqflask.api.gen_menu.build_datasets') - def test_get_datasets_with_non_existent_datasets(self, - build_datasets_mock): - """Test correct dataset is returned with non-existent build_datasets""" - build_datasets_mock.return_value = None - expected_result = { - 'mouse': { - 'H_T2': {}, - 'H_T1': {}}, - 'human': {'HLC': {}, - 'BXD': {}}} - self.assertEqual(get_datasets(self.test_type), - expected_result) - - @mock.patch('wqflask.api.gen_menu.get_datasets') - @mock.patch('wqflask.api.gen_menu.get_types') - @mock.patch('wqflask.api.gen_menu.get_groups') - @mock.patch('wqflask.api.gen_menu.get_species') - def test_gen_dropdown_json(self, - species_mock, - groups_mock, - types_mock, - datasets_mock): - "Test that the correct dictionary is constructed properly" - species_mock.return_value = ("speciesA speciesB speciesC speciesD" - .split(" ")) - datasets_mock.return_value = ("datasetA datasetB datasetC datasetD" - .split(" ")) - groups_mock.return_value = ("groupA groupB groupC groupD" - .split(" ")) - types_mock.return_value = ("typeA typeB typeC typeD" - .split(" ")) - datasets_mock.return_value = ("datasetA datasetB datasetC datasetD" - .split(" ")) - - expected_result = { - 'datasets': ['datasetA', 'datasetB', 'datasetC', 'datasetD'], - 'types': ['typeA', 'typeB', 'typeC', 'typeD'], - 'groups': ['groupA', 'groupB', 'groupC', 'groupD'], - 'species': ['speciesA', 'speciesB', 'speciesC', 'speciesD']} - - self.assertEqual(gen_dropdown_json(), expected_result) diff --git a/wqflask/tests/wqflask/__init__.py b/wqflask/tests/wqflask/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/wqflask/tests/wqflask/api/__init__.py b/wqflask/tests/wqflask/api/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/wqflask/tests/wqflask/api/test_gen_menu.py b/wqflask/tests/wqflask/api/test_gen_menu.py new file mode 100644 index 00000000..79c77fec --- /dev/null +++ b/wqflask/tests/wqflask/api/test_gen_menu.py @@ -0,0 +1,407 @@ +"""Test cases for wqflask.api.gen_menu""" +import unittest +import mock + +from wqflask.api.gen_menu import gen_dropdown_json +from wqflask.api.gen_menu import get_species +from wqflask.api.gen_menu import get_groups +from wqflask.api.gen_menu import get_types +from wqflask.api.gen_menu import get_datasets +from wqflask.api.gen_menu import phenotypes_exist +from wqflask.api.gen_menu import genotypes_exist +from wqflask.api.gen_menu import build_datasets +from wqflask.api.gen_menu import build_types + + +class TestGenMenu(unittest.TestCase): + """Tests for the gen_menu module""" + + def setUp(self): + self.test_group = { + 'mouse': [ + ['H_T1', + 'H_T', + 'Family:DescriptionA' + ], + ['H_T2', "H_T'", 'Family:None'] + ], + 'human': [ + ['BXD', 'BXD', 'Family:None'], + ['HLC', 'Liver: Normal Gene Expression with Genotypes (Merck)', + 'Family:Test'] + ] + } + + self.test_type = { + 'mouse': { + 'H_T2': [('Phenotypes', + 'Traits and Cofactors', + 'Phenotypes'), + ('Genotypes', + 'DNA Markers and SNPs', + 'Genotypes'), + ['M', 'M', 'Molecular Trait Datasets']], + 'H_T1': [('Phenotypes', + 'Traits and Cofactors', + 'Phenotypes'), + ('Genotypes', + 'DNA Markers and SNPs', + 'Genotypes'), + ['M', 'M', 'Molecular Trait Datasets']] + }, + 'human': { + 'HLC': [('Phenotypes', + 'Traits and Cofactors', + 'Phenotypes'), + ('Genotypes', + 'DNA Markers and SNPs', + 'Genotypes'), + ['M', 'M', 'Molecular Trait Datasets']], + 'BXD': [('Phenotypes', + 'Traits and Cofactors', + 'Phenotypes'), + ('Genotypes', + 'DNA Markers and SNPs', + 'Genotypes'), + ['M', 'M', 'Molecular Trait Datasets']] + } + } + + @mock.patch('wqflask.api.gen_menu.g') + def test_get_species(self, db_mock): + """Test that assertion is raised when dataset and dataset_name + are defined""" + db_mock.db.execute.return_value.fetchall.return_value = ( + ('human', 'Human'), + ('mouse', 'Mouse')) + self.assertEqual(get_species(), + [['human', 'Human'], ['mouse', 'Mouse']]) + db_mock.db.execute.assert_called_once_with( + "SELECT Name, MenuName FROM Species ORDER BY OrderId" + ) + + @mock.patch('wqflask.api.gen_menu.g') + def test_get_groups(self, db_mock): + """Test that species groups are grouped correctly""" + db_mock.db.execute.return_value.fetchall.side_effect = [ + # Mouse + (('BXD', 'BXD', None), + ('HLC', 'Liver: Normal Gene Expression with Genotypes (Merck)', + 'Test')), + # Human + (('H_T1', "H_T", "DescriptionA"), + ('H_T2', "H_T'", None)) + ] + + self.assertEqual(get_groups([["human", "Human"], ["mouse", "Mouse"]]), + self.test_group) + + for name in ["mouse", "human"]: + db_mock.db.execute.assert_any_call( + ("SELECT InbredSet.Name, InbredSet.FullName, " + + "IFNULL(InbredSet.Family, 'None') " + + "FROM InbredSet, Species WHERE Species.Name " + + "= '{}' AND InbredSet.SpeciesId = Species.Id GROUP by " + + "InbredSet.Name ORDER BY IFNULL(InbredSet.FamilyOrder, " + + "InbredSet.FullName) ASC, IFNULL(InbredSet.Family, " + + "InbredSet.FullName) ASC, InbredSet.FullName ASC, " + + "InbredSet.MenuOrderId ASC").format(name) + ) + + @mock.patch('wqflask.api.gen_menu.g') + def test_phenotypes_exist_called_with_correct_query(self, db_mock): + """Test that phenotypes_exist is called with the correct query""" + db_mock.db.execute.return_value.fetchone.return_value = None + phenotypes_exist("test") + db_mock.db.execute.assert_called_with( + "SELECT Name FROM PublishFreeze " + "WHERE PublishFreeze.Name = 'testPublish'" + ) + + @mock.patch('wqflask.api.gen_menu.g') + def test_phenotypes_exist_with_falsy_values(self, db_mock): + """Test that phenotype check returns correctly when given + a None value""" + for x in [None, False, (), [], ""]: + db_mock.db.execute.return_value.fetchone.return_value = x + self.assertFalse(phenotypes_exist("test")) + + @mock.patch('wqflask.api.gen_menu.g') + def test_phenotypes_exist_with_truthy_value(self, db_mock): + """Test that phenotype check returns correctly when given Truthy """ + for x in ["x", ("result"), ["result"], [1]]: + db_mock.db.execute.return_value.fetchone.return_value = (x) + self.assertTrue(phenotypes_exist("test")) + + @mock.patch('wqflask.api.gen_menu.g') + def test_genotypes_exist_called_with_correct_query(self, db_mock): + """Test that genotypes_exist is called with the correct query""" + db_mock.db.execute.return_value.fetchone.return_value = None + genotypes_exist("test") + db_mock.db.execute.assert_called_with( + "SELECT Name FROM GenoFreeze WHERE GenoFreeze.Name = 'testGeno'" + ) + + @mock.patch('wqflask.api.gen_menu.g') + def test_genotypes_exist_with_falsy_values(self, db_mock): + """Test that genotype check returns correctly when given + a None value""" + for x in [None, False, (), [], ""]: + db_mock.db.execute.return_value.fetchone.return_value = x + self.assertFalse(genotypes_exist("test")) + + @mock.patch('wqflask.api.gen_menu.g') + def test_genotypes_exist_with_truthy_value(self, db_mock): + """Test that genotype check returns correctly when given Truthy """ + for x in ["x", ("result"), ["result"], [1]]: + db_mock.db.execute.return_value.fetchone.return_value = (x) + self.assertTrue(phenotypes_exist("test")) + + @mock.patch('wqflask.api.gen_menu.g') + def test_build_datasets_with_type_phenotypes(self, db_mock): + """Test that correct dataset is returned for a phenotype type""" + db_mock.db.execute.return_value.fetchall.return_value = ( + (602, "BXDPublish", "BXD Published Phenotypes"), + ) + self.assertEqual(build_datasets("Mouse", "BXD", "Phenotypes"), + [['602', "BXDPublish", "BXD Published Phenotypes"]]) + db_mock.db.execute.assert_called_with( + "SELECT InfoFiles.GN_AccesionId, PublishFreeze.Name, " + + "PublishFreeze.FullName FROM InfoFiles, PublishFreeze, " + + "InbredSet WHERE InbredSet.Name = 'BXD' AND " + + "PublishFreeze.InbredSetId = InbredSet.Id AND " + + "InfoFiles.InfoPageName = PublishFreeze.Name " + + "ORDER BY PublishFreeze.CreateTime ASC" + ) + self.assertEqual(build_datasets("Mouse", "MDP", "Phenotypes"), + [['602', "BXDPublish", "Mouse Phenome Database"]]) + + db_mock.db.execute.return_value.fetchall.return_value = () + db_mock.db.execute.return_value.fetchone.return_value = ( + "BXDPublish", "Mouse Phenome Database" + ) + self.assertEqual(build_datasets("Mouse", "MDP", "Phenotypes"), + [["None", "BXDPublish", "Mouse Phenome Database"]]) + + @mock.patch('wqflask.api.gen_menu.g') + def test_build_datasets_with_type_phenotypes_and_no_results(self, db_mock): + """Test that correct dataset is returned for a phenotype type with no + results + + """ + db_mock.db.execute.return_value.fetchall.return_value = None + db_mock.db.execute.return_value.fetchone.return_value = (121, + "text value") + self.assertEqual(build_datasets("Mouse", "BXD", "Phenotypes"), + [["None", "121", "text value"]]) + db_mock.db.execute.assert_called_with( + "SELECT PublishFreeze.Name, PublishFreeze.FullName " + "FROM PublishFreeze, InbredSet " + "WHERE InbredSet.Name = 'BXD' AND " + "PublishFreeze.InbredSetId = InbredSet.Id " + "ORDER BY PublishFreeze.CreateTime ASC" + ) + + @mock.patch('wqflask.api.gen_menu.g') + def test_build_datasets_with_type_genotypes(self, db_mock): + """Test that correct dataset is returned for a phenotype type""" + db_mock.db.execute.return_value.fetchone.return_value = ( + 635, "HLCPublish", "HLC Published Genotypes" + ) + + self.assertEqual(build_datasets("Mouse", "HLC", "Genotypes"), + [["635", "HLCGeno", "HLC Genotypes"]]) + db_mock.db.execute.assert_called_with( + "SELECT InfoFiles.GN_AccesionId FROM InfoFiles, " + "GenoFreeze, InbredSet WHERE InbredSet.Name = 'HLC' AND " + "GenoFreeze.InbredSetId = InbredSet.Id AND " + "InfoFiles.InfoPageName = GenoFreeze.ShortName " + + "ORDER BY GenoFreeze.CreateTime DESC" + ) + db_mock.db.execute.return_value.fetchone.return_value = () + self.assertEqual(build_datasets("Mouse", "HLC", "Genotypes"), + [["None", "HLCGeno", "HLC Genotypes"]]) + + @mock.patch('wqflask.api.gen_menu.g') + def test_build_datasets_with_type_mrna(self, db_mock): + """Test that correct dataset is returned for a mRNA + expression/ Probeset""" + db_mock.db.execute.return_value.fetchall.return_value = ( + (112, "HC_M2_0606_P", + "Hippocampus Consortium M430v2 (Jun06) PDNN"), ) + self.assertEqual(build_datasets("Mouse", "HLC", "mRNA"), [[ + "112", 'HC_M2_0606_P', "Hippocampus Consortium M430v2 (Jun06) PDNN" + ]]) + db_mock.db.execute.assert_called_once_with( + "SELECT ProbeSetFreeze.Id, ProbeSetFreeze.Name, " + + "ProbeSetFreeze.FullName FROM ProbeSetFreeze, " + + "ProbeFreeze, InbredSet, Tissue, Species WHERE " + + "Species.Name = 'Mouse' AND Species.Id = " + + "InbredSet.SpeciesId AND InbredSet.Name = 'HLC' AND " + + "ProbeSetFreeze.ProbeFreezeId = ProbeFreeze.Id and " + + "Tissue.Name = 'mRNA' AND ProbeFreeze.TissueId = " + + "Tissue.Id and ProbeFreeze.InbredSetId = InbredSet.Id " + + "ORDER BY ProbeSetFreeze.CreateTime DESC") + + @mock.patch('wqflask.api.gen_menu.build_datasets') + @mock.patch('wqflask.api.gen_menu.g') + def test_build_types(self, db_mock, datasets_mock): + """Test that correct tissue metadata is returned""" + datasets_mock.return_value = [ + ["112", 'HC_M2_0606_P', + "Hippocampus Consortium M430v2 (Jun06) PDNN"] + ] + db_mock.db.execute.return_value.fetchall.return_value = ( + ('Mouse Tissue'), ('Human Tissue'), ('Rat Tissue') + ) + self.assertEqual(build_types('mouse', 'random group'), + [['M', 'M', 'Molecular Trait Datasets'], + ['H', 'H', 'Molecular Trait Datasets'], + ['R', 'R', 'Molecular Trait Datasets']]) + db_mock.db.execute.assert_called_once_with( + "SELECT DISTINCT Tissue.Name " + + "FROM ProbeFreeze, ProbeSetFreeze, InbredSet, " + + "Tissue, Species WHERE Species.Name = 'mouse' " + + "AND Species.Id = InbredSet.SpeciesId AND " + + "InbredSet.Name = 'random group' AND " + + "ProbeFreeze.TissueId = Tissue.Id AND " + + "ProbeFreeze.InbredSetId = InbredSet.Id AND " + + "ProbeSetFreeze.ProbeFreezeId = ProbeFreeze.Id " + + "ORDER BY Tissue.Name" + ) + + @mock.patch('wqflask.api.gen_menu.build_types') + @mock.patch('wqflask.api.gen_menu.genotypes_exist') + @mock.patch('wqflask.api.gen_menu.phenotypes_exist') + def test_get_types_with_existing_genotype_and_phenotypes( + self, + phenotypes_exist_mock, + genotypes_exist_mock, + build_types_mock): + """Test that build types are constructed correctly if phenotypes and genotypes + exist + + """ + phenotypes_exist_mock.return_value = True + genotypes_exist_mock.return_value = True + + expected_result = self.test_type + + build_types_mock.return_value = [ + ['M', 'M', 'Molecular Trait Datasets'] + ] + self.assertEqual(get_types(self.test_group), expected_result) + + @mock.patch('wqflask.api.gen_menu.build_types') + @mock.patch('wqflask.api.gen_menu.genotypes_exist') + @mock.patch('wqflask.api.gen_menu.phenotypes_exist') + def test_get_types_with_buildtype_and_non_existent_genotype_and_phenotypes( + self, + phenotypes_exist_mock, + genotypes_exist_mock, + build_types_mock): + """Test that build types are constructed correctly if phenotypes_exist and + genotypes_exist are false but build_type is falsy + + """ + phenotypes_exist_mock.return_value = False + genotypes_exist_mock.return_value = False + + build_types_mock.return_value = [] + self.assertEqual(get_types(self.test_group), { + 'mouse': {}, + 'human': {} + }) + + @mock.patch('wqflask.api.gen_menu.build_types') + @mock.patch('wqflask.api.gen_menu.genotypes_exist') + @mock.patch('wqflask.api.gen_menu.phenotypes_exist') + def test_get_types_with_non_existent_genotype_phenotypes_and_buildtype( + self, + phenotypes_exist_mock, + genotypes_exist_mock, + build_types_mock): + """Test that build types are constructed correctly if phenotypes_exist, + genotypes_exist and build_types are truthy + + """ + phenotypes_exist_mock.return_value = False + genotypes_exist_mock.return_value = False + + build_types_mock.return_value = [ + ['M', 'M', 'Molecular Trait Datasets'] + ] + expected_result = { + 'mouse': { + 'H_T2': [['M', 'M', 'Molecular Trait Datasets']], + 'H_T1': [['M', 'M', 'Molecular Trait Datasets']]}, + 'human': { + 'HLC': [['M', 'M', 'Molecular Trait Datasets']], + 'BXD': [['M', 'M', 'Molecular Trait Datasets']]}} + self.assertEqual(get_types(self.test_group), + expected_result) + + @mock.patch('wqflask.api.gen_menu.build_datasets') + def test_get_datasets_with_existent_datasets(self, + build_datasets_mock): + """Test correct dataset is returned with existent build_datasets""" + build_datasets_mock.return_value = "Test" + expected_result = { + 'mouse': { + 'H_T2': {'Genotypes': 'Test', + 'M': 'Test', + 'Phenotypes': 'Test'}, + 'H_T1': {'Genotypes': 'Test', + 'M': 'Test', + 'Phenotypes': 'Test'}}, + 'human': {'HLC': {'Genotypes': 'Test', + 'M': 'Test', + 'Phenotypes': 'Test'}, + 'BXD': {'Genotypes': 'Test', + 'M': 'Test', + 'Phenotypes': 'Test'}}} + self.assertEqual(get_datasets(self.test_type), + expected_result) + + @mock.patch('wqflask.api.gen_menu.build_datasets') + def test_get_datasets_with_non_existent_datasets(self, + build_datasets_mock): + """Test correct dataset is returned with non-existent build_datasets""" + build_datasets_mock.return_value = None + expected_result = { + 'mouse': { + 'H_T2': {}, + 'H_T1': {}}, + 'human': {'HLC': {}, + 'BXD': {}}} + self.assertEqual(get_datasets(self.test_type), + expected_result) + + @mock.patch('wqflask.api.gen_menu.get_datasets') + @mock.patch('wqflask.api.gen_menu.get_types') + @mock.patch('wqflask.api.gen_menu.get_groups') + @mock.patch('wqflask.api.gen_menu.get_species') + def test_gen_dropdown_json(self, + species_mock, + groups_mock, + types_mock, + datasets_mock): + "Test that the correct dictionary is constructed properly" + species_mock.return_value = ("speciesA speciesB speciesC speciesD" + .split(" ")) + datasets_mock.return_value = ("datasetA datasetB datasetC datasetD" + .split(" ")) + groups_mock.return_value = ("groupA groupB groupC groupD" + .split(" ")) + types_mock.return_value = ("typeA typeB typeC typeD" + .split(" ")) + datasets_mock.return_value = ("datasetA datasetB datasetC datasetD" + .split(" ")) + + expected_result = { + 'datasets': ['datasetA', 'datasetB', 'datasetC', 'datasetD'], + 'types': ['typeA', 'typeB', 'typeC', 'typeD'], + 'groups': ['groupA', 'groupB', 'groupC', 'groupD'], + 'species': ['speciesA', 'speciesB', 'speciesC', 'speciesD']} + + self.assertEqual(gen_dropdown_json(), expected_result) -- cgit v1.2.3 From 3a8409757e2e095cd18c483de07af1eed8719c02 Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Sat, 8 Aug 2020 03:36:31 +0300 Subject: Add a basic test for test_display_marking_results.py * wqflask/tests/wqflask/marker_regression/__init__.py: Add it * wqflask/tests/wqflask/marker_regression/test_display_marking_results.py: Check that PIL colors are being used instead of the deprecated Piddle colors. --- wqflask/tests/wqflask/marker_regression/__init__.py | 0 .../wqflask/marker_regression/test_display_marking_results.py | 9 +++++++++ 2 files changed, 9 insertions(+) create mode 100644 wqflask/tests/wqflask/marker_regression/__init__.py create mode 100644 wqflask/tests/wqflask/marker_regression/test_display_marking_results.py (limited to 'wqflask/tests') diff --git a/wqflask/tests/wqflask/marker_regression/__init__.py b/wqflask/tests/wqflask/marker_regression/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/wqflask/tests/wqflask/marker_regression/test_display_marking_results.py b/wqflask/tests/wqflask/marker_regression/test_display_marking_results.py new file mode 100644 index 00000000..67da508b --- /dev/null +++ b/wqflask/tests/wqflask/marker_regression/test_display_marking_results.py @@ -0,0 +1,9 @@ +import unittest + +from wqflask.marker_regression.display_mapping_results import DisplayMappingResults + +class TestDisplayMappingResults(unittest.TestCase): + def test_pil_colors(self): + """Test that colors use PILLOW color format""" + self.assertEqual(DisplayMappingResults.CLICKABLE_WEBQTL_REGION_COLOR, + (245, 211, 211)) -- cgit v1.2.3 From d8ba3a6fb10127506a3edd4b572797bb846da37c Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Sun, 23 Aug 2020 22:30:16 +0300 Subject: Fix failing test * wqflask/tests/wqflask/api/test_gen_menu.py: Update assertion. Result data introduced in 092212df Signed-off-by: BonfaceKilz --- wqflask/tests/wqflask/api/test_gen_menu.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/wqflask/api/test_gen_menu.py b/wqflask/tests/wqflask/api/test_gen_menu.py index 79c77fec..239484aa 100644 --- a/wqflask/tests/wqflask/api/test_gen_menu.py +++ b/wqflask/tests/wqflask/api/test_gen_menu.py @@ -255,9 +255,9 @@ class TestGenMenu(unittest.TestCase): ('Mouse Tissue'), ('Human Tissue'), ('Rat Tissue') ) self.assertEqual(build_types('mouse', 'random group'), - [['M', 'M', 'Molecular Trait Datasets'], - ['H', 'H', 'Molecular Trait Datasets'], - ['R', 'R', 'Molecular Trait Datasets']]) + [['M', 'M', 'Molecular Traits'], + ['H', 'H', 'Molecular Traits'], + ['R', 'R', 'Molecular Traits']]) db_mock.db.execute.assert_called_once_with( "SELECT DISTINCT Tissue.Name " + "FROM ProbeFreeze, ProbeSetFreeze, InbredSet, " + -- cgit v1.2.3 From cbc44ad7661b2da1bd434e186127fa8fab166a93 Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Sun, 23 Aug 2020 23:53:37 +0300 Subject: Rename file * wqflask/tests/wqflask/marker_regression/test_display_mapping_results.py: Rename test_display_marking_results.py to test_display_mapping_results.py --- .../wqflask/marker_regression/test_display_mapping_results.py | 9 +++++++++ .../wqflask/marker_regression/test_display_marking_results.py | 9 --------- 2 files changed, 9 insertions(+), 9 deletions(-) create mode 100644 wqflask/tests/wqflask/marker_regression/test_display_mapping_results.py delete mode 100644 wqflask/tests/wqflask/marker_regression/test_display_marking_results.py (limited to 'wqflask/tests') diff --git a/wqflask/tests/wqflask/marker_regression/test_display_mapping_results.py b/wqflask/tests/wqflask/marker_regression/test_display_mapping_results.py new file mode 100644 index 00000000..67da508b --- /dev/null +++ b/wqflask/tests/wqflask/marker_regression/test_display_mapping_results.py @@ -0,0 +1,9 @@ +import unittest + +from wqflask.marker_regression.display_mapping_results import DisplayMappingResults + +class TestDisplayMappingResults(unittest.TestCase): + def test_pil_colors(self): + """Test that colors use PILLOW color format""" + self.assertEqual(DisplayMappingResults.CLICKABLE_WEBQTL_REGION_COLOR, + (245, 211, 211)) diff --git a/wqflask/tests/wqflask/marker_regression/test_display_marking_results.py b/wqflask/tests/wqflask/marker_regression/test_display_marking_results.py deleted file mode 100644 index 67da508b..00000000 --- a/wqflask/tests/wqflask/marker_regression/test_display_marking_results.py +++ /dev/null @@ -1,9 +0,0 @@ -import unittest - -from wqflask.marker_regression.display_mapping_results import DisplayMappingResults - -class TestDisplayMappingResults(unittest.TestCase): - def test_pil_colors(self): - """Test that colors use PILLOW color format""" - self.assertEqual(DisplayMappingResults.CLICKABLE_WEBQTL_REGION_COLOR, - (245, 211, 211)) -- cgit v1.2.3 From 7cafbbc2f13240c56ad31d47a7b429c9832c6df0 Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Mon, 24 Aug 2020 18:11:11 +0300 Subject: Add tests for the HtmlGenWrapper class * wqflask/tests/wqflask/marker_regression/test_display_mapping_results.py: Add new tests --- .../test_display_mapping_results.py | 144 ++++++++++++++++++++- 1 file changed, 143 insertions(+), 1 deletion(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/wqflask/marker_regression/test_display_mapping_results.py b/wqflask/tests/wqflask/marker_regression/test_display_mapping_results.py index 67da508b..6f791df1 100644 --- a/wqflask/tests/wqflask/marker_regression/test_display_mapping_results.py +++ b/wqflask/tests/wqflask/marker_regression/test_display_mapping_results.py @@ -1,9 +1,151 @@ import unittest -from wqflask.marker_regression.display_mapping_results import DisplayMappingResults +from htmlgen import HTMLgen2 as HT +from wqflask.marker_regression.display_mapping_results import ( + DisplayMappingResults, + HtmlGenWrapper +) + class TestDisplayMappingResults(unittest.TestCase): + """Basic Methods to test Mapping Results""" def test_pil_colors(self): """Test that colors use PILLOW color format""" self.assertEqual(DisplayMappingResults.CLICKABLE_WEBQTL_REGION_COLOR, (245, 211, 211)) + + +class TestHtmlGenWrapper(unittest.TestCase): + """Test Wrapper around HTMLGen""" + def test_create_image(self): + """Test HT.Image method""" + self.assertEqual( + str(HtmlGenWrapper.create_image_tag(src="test.png", + alt="random", + border="0", + width="10", + height="13", + usemap="#webqtlmap")), + ("""""") + ) + + def test_create_form(self): + """Test HT.Form method""" + test_form = HtmlGenWrapper.create_form_tag( + cgi="/testing/", + enctype='multipart/form-data', + name="formName", + submit=HT.Input(type='hidden') + ) + test_image = HtmlGenWrapper.create_image_tag( + src="test.png", + alt="random", + border="0", + width="10", + height="13", + usemap="#webqtlmap" + ) + self.assertEqual( + str(test_form).replace("\n", ""), + ("""
""")) + hddn = { + 'FormID': 'showDatabase', + 'ProbeSetID': '_', + 'database': "TestGeno", + 'CellID': '_', + 'RISet': "Test", + 'incparentsf1': 'ON' + } + for key in hddn.keys(): + test_form.append(HT.Input(name=key, value=hddn[key], + type='hidden')) + test_form.append(test_image) + self.assertEqual(str(test_form).replace("\n", ""), ( + """
""" + """""" + """""" + """""" + """""" + """""" + """""" + """random""" + """
""")) + + def test_create_paragraph(self): + """Test HT.Paragraph method""" + test_p_element = HtmlGenWrapper.create_p_tag(id="smallSize") + par_text = ( + "Mapping using genotype data as " + "a trait will result in infinity LRS at one locus. " + "In order to display the result properly, all LRSs " + "higher than 100 are capped at 100." + ) + self.assertEqual( + str(test_p_element), + """

""" + ) + test_p_element.append(HT.BR()) + test_p_element.append(par_text) + self.assertEqual( + str(test_p_element), + """


{}

""".format(par_text) + ) + + def test_create_br_tag(self): + """Test HT.BR() method""" + self.assertEqual(str(HtmlGenWrapper.create_br_tag()), + "
") + + def test_create_input_tag(self): + """Test HT.Input method""" + self.assertEqual( + str(HtmlGenWrapper.create_input_tag( + type="hidden", + name="name", + value="key", + Class="trait trait_")).replace("\n", ""), + ("""""")) + + def test_create_map_tag(self): + """Test HT.Map method""" + self.assertEqual(str(HtmlGenWrapper.create_map_tag( + name="WebqTLImageMap")).replace("\n", ""), + """""") + gifmap = HtmlGenWrapper.create_map_tag(areas=[]) + gifmap.areas.append(HT.Area(shape="rect", + coords='1 2 3', href='#area1')) + gifmap.areas.append(HT.Area(shape="rect", + coords='1 2 3', href='#area2')) + self.assertEqual( + str(gifmap).replace("\n", ""), + ("""""" + """""" + """""" + """""")) + + def test_create_area_tag(self): + """Test HT.Area method""" + self.assertEqual( + str(HtmlGenWrapper.create_area_tag( + shape="rect", + coords="1 2", + href="http://test.com", + title="Some Title")).replace("\n", ""), + ("""""")) + + def test_create_link_tag(self): + """Test HT.HREF method""" + self.assertEqual( + str(HtmlGenWrapper.create_link_tag( + "www.test.com", "test", target="_blank")).replace("\n", ""), + """test""") -- cgit v1.2.3 From 6486bc57651f074245ae0bf786f9e92460d73fef Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Wed, 26 Aug 2020 17:31:17 +0300 Subject: Fix failing tests that use python2-htmlgen * wqflask/tests/wqflask/marker_regression/test_display_mapping_results.py: Fix tests. --- .../test_display_mapping_results.py | 91 ++++++++++++---------- 1 file changed, 48 insertions(+), 43 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/wqflask/marker_regression/test_display_mapping_results.py b/wqflask/tests/wqflask/marker_regression/test_display_mapping_results.py index 6f791df1..8ae0f09f 100644 --- a/wqflask/tests/wqflask/marker_regression/test_display_mapping_results.py +++ b/wqflask/tests/wqflask/marker_regression/test_display_mapping_results.py @@ -1,6 +1,6 @@ import unittest -from htmlgen import HTMLgen2 as HT +import htmlgen as HT from wqflask.marker_regression.display_mapping_results import ( DisplayMappingResults, HtmlGenWrapper @@ -26,9 +26,9 @@ class TestHtmlGenWrapper(unittest.TestCase): width="10", height="13", usemap="#webqtlmap")), - ("""""") + ("""random""") ) def test_create_form(self): @@ -37,7 +37,7 @@ class TestHtmlGenWrapper(unittest.TestCase): cgi="/testing/", enctype='multipart/form-data', name="formName", - submit=HT.Input(type='hidden') + submit=HtmlGenWrapper.create_input_tag(type_='hidden', name='Default_Name') ) test_image = HtmlGenWrapper.create_image_tag( src="test.png", @@ -49,10 +49,10 @@ class TestHtmlGenWrapper(unittest.TestCase): ) self.assertEqual( str(test_form).replace("\n", ""), - ("""
""")) + ("""
""")) hddn = { 'FormID': 'showDatabase', 'ProbeSetID': '_', @@ -62,21 +62,26 @@ class TestHtmlGenWrapper(unittest.TestCase): 'incparentsf1': 'ON' } for key in hddn.keys(): - test_form.append(HT.Input(name=key, value=hddn[key], - type='hidden')) + test_form.append( + HtmlGenWrapper.create_input_tag( + name=key, + value=hddn[key], + type_='hidden')) test_form.append(test_image) + self.assertEqual(str(test_form).replace("\n", ""), ( - """
""" - """""" - """""" - """""" - """""" - """""" - """""" - """random""" - """
""")) + """
""" + """""" + """""" + """""" + """""" + """""" + """""" + """""" + """random""" + """
""")) def test_create_paragraph(self): """Test HT.Paragraph method""" @@ -89,48 +94,48 @@ class TestHtmlGenWrapper(unittest.TestCase): ) self.assertEqual( str(test_p_element), - """

""" + """

""" ) - test_p_element.append(HT.BR()) + test_p_element.append(HtmlGenWrapper.create_br_tag()) test_p_element.append(par_text) self.assertEqual( str(test_p_element), - """


{}

""".format(par_text) + """


{}

""".format(par_text) ) def test_create_br_tag(self): """Test HT.BR() method""" self.assertEqual(str(HtmlGenWrapper.create_br_tag()), - "
") + "
") def test_create_input_tag(self): """Test HT.Input method""" self.assertEqual( str(HtmlGenWrapper.create_input_tag( - type="hidden", + type_="hidden", name="name", value="key", Class="trait trait_")).replace("\n", ""), - ("""""")) + ("""""")) def test_create_map_tag(self): """Test HT.Map method""" self.assertEqual(str(HtmlGenWrapper.create_map_tag( name="WebqTLImageMap")).replace("\n", ""), - """""") - gifmap = HtmlGenWrapper.create_map_tag(areas=[]) - gifmap.areas.append(HT.Area(shape="rect", - coords='1 2 3', href='#area1')) - gifmap.areas.append(HT.Area(shape="rect", - coords='1 2 3', href='#area2')) + """""") + gifmap = HtmlGenWrapper.create_map_tag(name="test") + gifmap.append(HtmlGenWrapper.create_area_tag(shape="rect", + coords='1 2 3', href='#area1')) + gifmap.append(HtmlGenWrapper.create_area_tag(shape="rect", + coords='1 2 3', href='#area2')) self.assertEqual( str(gifmap).replace("\n", ""), - ("""""" - """""" - """""" - """""")) + ("""""" + """""" + """""" + """""")) def test_create_area_tag(self): """Test HT.Area method""" @@ -140,12 +145,12 @@ class TestHtmlGenWrapper(unittest.TestCase): coords="1 2", href="http://test.com", title="Some Title")).replace("\n", ""), - ("""""")) + ("""""")) def test_create_link_tag(self): """Test HT.HREF method""" self.assertEqual( str(HtmlGenWrapper.create_link_tag( "www.test.com", "test", target="_blank")).replace("\n", ""), - """test""") + """test""") -- cgit v1.2.3 From 869da13b92e70fa0769cd1a49e15b03e2c9d0550 Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Thu, 27 Aug 2020 01:31:33 +0300 Subject: Fix failing tests --- wqflask/tests/base/test_data_set.py | 71 +++++++++++++++++++++++------- wqflask/tests/base/test_general_object.py | 9 ++-- wqflask/tests/wqflask/api/test_gen_menu.py | 6 +++ 3 files changed, 66 insertions(+), 20 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/base/test_data_set.py b/wqflask/tests/base/test_data_set.py index 94780a5d..e6000e56 100644 --- a/wqflask/tests/base/test_data_set.py +++ b/wqflask/tests/base/test_data_set.py @@ -4,7 +4,7 @@ import unittest import mock from wqflask import app -from data import gen_menu_json +from .data import gen_menu_json from base.data_set import DatasetType @@ -59,9 +59,14 @@ class TestDataSetTypes(unittest.TestCase): self.assertEqual(data_set("BXDGeno"), "Geno") self.assertEqual(data_set("BXDPublish"), "Publish") self.assertEqual(data_set("HLC_0311"), "ProbeSet") + redis_mock.set.assert_called_once_with( "dataset_structure", - '{"BXDGeno": "Geno", "BXDPublish": "Publish", "HLCPublish": "Publish", "HLC_0311": "ProbeSet", "HC_M2_0606_P": "ProbeSet"}') + ('{"HLC_0311": "ProbeSet", ' + '"HLCPublish": "Publish", ' + '"BXDGeno": "Geno", ' + '"HC_M2_0606_P": "ProbeSet", ' + '"BXDPublish": "Publish"}')) @mock.patch('base.data_set.g') def test_set_dataset_key_mrna(self, db_mock): @@ -74,8 +79,17 @@ class TestDataSetTypes(unittest.TestCase): self.assertEqual(data_set("Test"), "ProbeSet") redis_mock.set.assert_called_once_with( "dataset_structure", - '{"Aging-Brain-UCIPublish": "Publish", "AKXDGeno": "Geno", "B139_K_1206_M": "ProbeSet", "AD-cases-controls-MyersGeno": "Geno", "AD-cases-controls-MyersPublish": "Publish", "All Phenotypes": "Publish", "Test": "ProbeSet", "AXBXAPublish": "Publish", "B139_K_1206_R": "ProbeSet", "AXBXAGeno": "Geno"}') - expected_db_call = """""" + ('{"AD-cases-controls-MyersGeno": "Geno", ' + '"AD-cases-controls-MyersPublish": "Publish", ' + '"AKXDGeno": "Geno", ' + '"AXBXAGeno": "Geno", ' + '"AXBXAPublish": "Publish", ' + '"Aging-Brain-UCIPublish": "Publish", ' + '"All Phenotypes": "Publish", ' + '"B139_K_1206_M": "ProbeSet", ' + '"B139_K_1206_R": "ProbeSet", ' + '"Test": "ProbeSet"}')) + db_mock.db.execute.assert_called_with( ("SELECT ProbeSetFreeze.Id FROM ProbeSetFreeze " + "WHERE ProbeSetFreeze.Name = \"Test\" ") @@ -92,13 +106,21 @@ class TestDataSetTypes(unittest.TestCase): self.assertEqual(data_set("Test"), "Publish") redis_mock.set.assert_called_once_with( "dataset_structure", - '{"Aging-Brain-UCIPublish": "Publish", "AKXDGeno": "Geno", "B139_K_1206_M": "ProbeSet", "AD-cases-controls-MyersGeno": "Geno", "AD-cases-controls-MyersPublish": "Publish", "All Phenotypes": "Publish", "Test": "Publish", "AXBXAPublish": "Publish", "B139_K_1206_R": "ProbeSet", "AXBXAGeno": "Geno"}') - expected_db_call = """""" + ('{"AD-cases-controls-MyersGeno": "Geno", ' + '"AD-cases-controls-MyersPublish": "Publish", ' + '"AKXDGeno": "Geno", ' + '"AXBXAGeno": "Geno", ' + '"AXBXAPublish": "Publish", ' + '"Aging-Brain-UCIPublish": "Publish", ' + '"All Phenotypes": "Publish", ' + '"B139_K_1206_M": "ProbeSet", ' + '"B139_K_1206_R": "ProbeSet", ' + '"Test": "Publish"}')) db_mock.db.execute.assert_called_with( - ("SELECT InfoFiles.GN_AccesionId " + - "FROM InfoFiles, PublishFreeze, InbredSet " + + ("SELECT InfoFiles.GN_AccesionId " + "FROM InfoFiles, PublishFreeze, InbredSet " "WHERE InbredSet.Name = 'Test' AND " - "PublishFreeze.InbredSetId = InbredSet.Id AND " + + "PublishFreeze.InbredSetId = InbredSet.Id AND " "InfoFiles.InfoPageName = PublishFreeze.Name") ) @@ -111,10 +133,20 @@ class TestDataSetTypes(unittest.TestCase): data_set = DatasetType(redis_mock) data_set.set_dataset_key("other_pheno", "Test") self.assertEqual(data_set("Test"), "Publish") + redis_mock.set.assert_called_once_with( "dataset_structure", - '{"Aging-Brain-UCIPublish": "Publish", "AKXDGeno": "Geno", "B139_K_1206_M": "ProbeSet", "AD-cases-controls-MyersGeno": "Geno", "AD-cases-controls-MyersPublish": "Publish", "All Phenotypes": "Publish", "Test": "Publish", "AXBXAPublish": "Publish", "B139_K_1206_R": "ProbeSet", "AXBXAGeno": "Geno"}') - expected_db_call = """""" + ('{"AD-cases-controls-MyersGeno": "Geno", ' + '"AD-cases-controls-MyersPublish": "Publish", ' + '"AKXDGeno": "Geno", ' + '"AXBXAGeno": "Geno", ' + '"AXBXAPublish": "Publish", ' + '"Aging-Brain-UCIPublish": "Publish", ' + '"All Phenotypes": "Publish", ' + '"B139_K_1206_M": "ProbeSet", ' + '"B139_K_1206_R": "ProbeSet", ' + '"Test": "Publish"}')) + db_mock.db.execute.assert_called_with( ("SELECT PublishFreeze.Name " + "FROM PublishFreeze, InbredSet " + @@ -133,8 +165,17 @@ class TestDataSetTypes(unittest.TestCase): self.assertEqual(data_set("Test"), "Geno") redis_mock.set.assert_called_once_with( "dataset_structure", - '{"Aging-Brain-UCIPublish": "Publish", "AKXDGeno": "Geno", "B139_K_1206_M": "ProbeSet", "AD-cases-controls-MyersGeno": "Geno", "AD-cases-controls-MyersPublish": "Publish", "All Phenotypes": "Publish", "Test": "Geno", "AXBXAPublish": "Publish", "B139_K_1206_R": "ProbeSet", "AXBXAGeno": "Geno"}') - expected_db_call = """""" + ('{"AD-cases-controls-MyersGeno": "Geno", ' + '"AD-cases-controls-MyersPublish": "Publish", ' + '"AKXDGeno": "Geno", ' + '"AXBXAGeno": "Geno", ' + '"AXBXAPublish": "Publish", ' + '"Aging-Brain-UCIPublish": "Publish", ' + '"All Phenotypes": "Publish", ' + '"B139_K_1206_M": "ProbeSet", ' + '"B139_K_1206_R": "ProbeSet", ' + '"Test": "Geno"}')) + db_mock.db.execute.assert_called_with( - ("SELECT GenoFreeze.Id FROM GenoFreeze WHERE GenoFreeze.Name = \"Test\" ") - ) + ("SELECT GenoFreeze.Id FROM " + "GenoFreeze WHERE GenoFreeze.Name = \"Test\" ")) diff --git a/wqflask/tests/base/test_general_object.py b/wqflask/tests/base/test_general_object.py index c7701021..00fd3c72 100644 --- a/wqflask/tests/base/test_general_object.py +++ b/wqflask/tests/base/test_general_object.py @@ -17,9 +17,9 @@ class TestGeneralObjectTests(unittest.TestCase): def test_object_dict(self): """Test whether the base class is printed properly""" test_obj = GeneralObject("a", name="test", value=1) - self.assertEqual(str(test_obj), "value = 1\nname = test\n") + self.assertEqual(str(test_obj), "name = test\nvalue = 1\n") self.assertEqual( - repr(test_obj), "value = 1\nname = test\ncontents = ['a']\n") + repr(test_obj), "contents = ['a']\nname = test\nvalue = 1\n") self.assertEqual(len(test_obj), 2) self.assertEqual(test_obj["value"], 1) test_obj["test"] = 1 @@ -36,6 +36,5 @@ class TestGeneralObjectTests(unittest.TestCase): test_obj1 = GeneralObject("a", name="test", value=1) test_obj2 = GeneralObject("b", name="test2", value=2) test_obj3 = GeneralObject("a", name="test", x=1, y=2) - self.assertTrue(test_obj1 == test_obj2 ) - self.assertFalse(test_obj1 == test_obj3 ) - + self.assertTrue(test_obj1 == test_obj2) + self.assertFalse(test_obj1 == test_obj3) diff --git a/wqflask/tests/wqflask/api/test_gen_menu.py b/wqflask/tests/wqflask/api/test_gen_menu.py index 239484aa..bf41054d 100644 --- a/wqflask/tests/wqflask/api/test_gen_menu.py +++ b/wqflask/tests/wqflask/api/test_gen_menu.py @@ -2,6 +2,7 @@ import unittest import mock +from wqflask import app from wqflask.api.gen_menu import gen_dropdown_json from wqflask.api.gen_menu import get_species from wqflask.api.gen_menu import get_groups @@ -17,6 +18,8 @@ class TestGenMenu(unittest.TestCase): """Tests for the gen_menu module""" def setUp(self): + self.app_context = app.app_context() + self.app_context.push() self.test_group = { 'mouse': [ ['H_T1', @@ -67,6 +70,9 @@ class TestGenMenu(unittest.TestCase): } } + def tearDown(self): + self.app_context.pop() + @mock.patch('wqflask.api.gen_menu.g') def test_get_species(self, db_mock): """Test that assertion is raised when dataset and dataset_name -- cgit v1.2.3 From 77d026e042a3eac9e3de4177ee374a37f2e24127 Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Tue, 15 Sep 2020 20:53:11 +0300 Subject: Fix failing tests * wqflask/tests/base/test_data_set.py: Update failing tests introduced by the change in 301bdd2f4. --- wqflask/tests/base/test_data_set.py | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/base/test_data_set.py b/wqflask/tests/base/test_data_set.py index 94780a5d..dd7f5051 100644 --- a/wqflask/tests/base/test_data_set.py +++ b/wqflask/tests/base/test_data_set.py @@ -66,7 +66,7 @@ class TestDataSetTypes(unittest.TestCase): @mock.patch('base.data_set.g') def test_set_dataset_key_mrna(self, db_mock): with app.app_context(): - db_mock.db.execute.return_value = [1, 2, 3] + db_mock.db.execute.return_value.fetchone.return_value = [1, 2, 3] redis_mock = mock.Mock() redis_mock.get.return_value = self.test_dataset data_set = DatasetType(redis_mock) @@ -84,7 +84,7 @@ class TestDataSetTypes(unittest.TestCase): @mock.patch('base.data_set.g') def test_set_dataset_key_pheno(self, db_mock): with app.app_context(): - db_mock.db.execute.return_value = [1, 2, 3] + db_mock.db.execute.return_value.fetchone.return_value = [1, 2, 3] redis_mock = mock.Mock() redis_mock.get.return_value = self.test_dataset data_set = DatasetType(redis_mock) @@ -93,7 +93,6 @@ class TestDataSetTypes(unittest.TestCase): redis_mock.set.assert_called_once_with( "dataset_structure", '{"Aging-Brain-UCIPublish": "Publish", "AKXDGeno": "Geno", "B139_K_1206_M": "ProbeSet", "AD-cases-controls-MyersGeno": "Geno", "AD-cases-controls-MyersPublish": "Publish", "All Phenotypes": "Publish", "Test": "Publish", "AXBXAPublish": "Publish", "B139_K_1206_R": "ProbeSet", "AXBXAGeno": "Geno"}') - expected_db_call = """""" db_mock.db.execute.assert_called_with( ("SELECT InfoFiles.GN_AccesionId " + "FROM InfoFiles, PublishFreeze, InbredSet " + @@ -105,7 +104,7 @@ class TestDataSetTypes(unittest.TestCase): @mock.patch('base.data_set.g') def test_set_dataset_other_pheno(self, db_mock): with app.app_context(): - db_mock.db.execute.return_value = [1, 2, 3] + db_mock.db.execute.return_value.fetchone.return_value = [1, 2, 3] redis_mock = mock.Mock() redis_mock.get.return_value = self.test_dataset data_set = DatasetType(redis_mock) @@ -114,7 +113,6 @@ class TestDataSetTypes(unittest.TestCase): redis_mock.set.assert_called_once_with( "dataset_structure", '{"Aging-Brain-UCIPublish": "Publish", "AKXDGeno": "Geno", "B139_K_1206_M": "ProbeSet", "AD-cases-controls-MyersGeno": "Geno", "AD-cases-controls-MyersPublish": "Publish", "All Phenotypes": "Publish", "Test": "Publish", "AXBXAPublish": "Publish", "B139_K_1206_R": "ProbeSet", "AXBXAGeno": "Geno"}') - expected_db_call = """""" db_mock.db.execute.assert_called_with( ("SELECT PublishFreeze.Name " + "FROM PublishFreeze, InbredSet " + @@ -125,7 +123,7 @@ class TestDataSetTypes(unittest.TestCase): @mock.patch('base.data_set.g') def test_set_dataset_geno(self, db_mock): with app.app_context(): - db_mock.db.execute.return_value = [1, 2, 3] + db_mock.db.execute.return_value.fetchone.return_value = [1, 2, 3] redis_mock = mock.Mock() redis_mock.get.return_value = self.test_dataset data_set = DatasetType(redis_mock) -- cgit v1.2.3 From 6e776e94bdc2cea9923d70ff836ce1c02a1e1af9 Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Tue, 15 Sep 2020 23:19:30 +0300 Subject: Add tests for authentication tools Catches bugs in: - https://github.com/genenetwork/genenetwork2/pull/422/commits/70dbeeb5832711ed5271434e482c18bc7ea095b8 * wqflask/tests/utility/test_authentication_tools.py: New file. Add tests for "check_resource_availability". --- wqflask/tests/utility/test_authentication_tools.py | 113 +++++++++++++++++++++ 1 file changed, 113 insertions(+) create mode 100644 wqflask/tests/utility/test_authentication_tools.py (limited to 'wqflask/tests') diff --git a/wqflask/tests/utility/test_authentication_tools.py b/wqflask/tests/utility/test_authentication_tools.py new file mode 100644 index 00000000..59c53879 --- /dev/null +++ b/wqflask/tests/utility/test_authentication_tools.py @@ -0,0 +1,113 @@ +"""Tests for authentication tools""" +import unittest +import mock + +from utility.authentication_tools import check_resource_availability + + +class TestResponse: + """Mock Test Response after a request""" + @property + def content(self): + """Mock the content from Requests.get(params).content""" + return '["foo"]' + + +class TestUser: + """Mock user""" + @property + def user_id(self): + """Mockes user id. Used in Flask.g.user_session.user_id""" + return "Jane" + + +class TestUserSession: + """Mock user session""" + @property + def user_session(self): + """Mock user session. Mocks Flask.g.user_session object""" + return TestUser() + + +class TestCheckResourceAvailability(unittest.TestCase): + """Test methods related to checking the resource availability""" + @mock.patch('utility.authentication_tools.add_new_resource') + @mock.patch('utility.authentication_tools.Redis') + @mock.patch('utility.authentication_tools.g') + @mock.patch('utility.authentication_tools.get_resource_id') + def test_check_resource_availability_default_mask( + self, + resource_id_mock, + g_mock, + redis_mock, + add_new_resource_mock): + """Test the resource availability with default mask""" + resource_id_mock.return_value = 1 + g_mock.return_value = mock.Mock() + redis_mock.smembers.return_value = [] + test_dataset = mock.MagicMock() + type(test_dataset).type = mock.PropertyMock(return_value="Test") + add_new_resource_mock.return_value = {"default_mask": 2} + self.assertEqual(check_resource_availability(test_dataset), 2) + + @mock.patch('utility.authentication_tools.requests.get') + @mock.patch('utility.authentication_tools.add_new_resource') + @mock.patch('utility.authentication_tools.Redis') + @mock.patch('utility.authentication_tools.g') + @mock.patch('utility.authentication_tools.get_resource_id') + def test_check_resource_availability_non_default_mask( + self, + resource_id_mock, + g_mock, + redis_mock, + add_new_resource_mock, + requests_mock): + """Test the resource availability with default mask""" + resource_id_mock.return_value = 1 + g_mock.return_value = mock.Mock() + redis_mock.smembers.return_value = [] + add_new_resource_mock.return_value = {"default_mask": 2} + requests_mock.return_value = TestResponse() + test_dataset = mock.MagicMock() + type(test_dataset).type = mock.PropertyMock(return_value="Test") + self.assertEqual(check_resource_availability(test_dataset), + ['foo']) + + @mock.patch('utility.authentication_tools.webqtlConfig.SUPER_PRIVILEGES', + "SUPERUSER") + @mock.patch('utility.authentication_tools.requests.get') + @mock.patch('utility.authentication_tools.add_new_resource') + @mock.patch('utility.authentication_tools.Redis') + @mock.patch('utility.authentication_tools.g', TestUserSession()) + @mock.patch('utility.authentication_tools.get_resource_id') + def test_check_resource_availability_of_super_user( + self, + resource_id_mock, + redis_mock, + add_new_resource_mock, + requests_mock): + """Test the resource availability if the user is the super user""" + resource_id_mock.return_value = 1 + redis_mock.smembers.return_value = ["Jane"] + add_new_resource_mock.return_value = {"default_mask": 2} + requests_mock.return_value = TestResponse() + test_dataset = mock.MagicMock() + type(test_dataset).type = mock.PropertyMock(return_value="Test") + self.assertEqual(check_resource_availability(test_dataset), + "SUPERUSER") + + @mock.patch('utility.authentication_tools.webqtlConfig.DEFAULT_PRIVILEGES', + "John Doe") + def test_check_resource_availability_string_dataset(self): + """Test the resource availability if the dataset is a string""" + self.assertEqual(check_resource_availability("Test"), + "John Doe") + + @mock.patch('utility.authentication_tools.webqtlConfig.DEFAULT_PRIVILEGES', + "John Doe") + def test_check_resource_availability_temp(self): + """Test the resource availability if the dataset is a string""" + test_dataset = mock.MagicMock() + type(test_dataset).type = mock.PropertyMock(return_value="Temp") + self.assertEqual(check_resource_availability(test_dataset), + "John Doe") -- cgit v1.2.3 From cad9d0e4c913eba5ae3c74912b59051885833f90 Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Wed, 16 Sep 2020 00:03:28 +0300 Subject: Add tests for "add_new_resource" method * wqflask/tests/utility/test_authentication_tools.py: Add them. --- wqflask/tests/utility/test_authentication_tools.py | 80 ++++++++++++++++++++++ 1 file changed, 80 insertions(+) (limited to 'wqflask/tests') diff --git a/wqflask/tests/utility/test_authentication_tools.py b/wqflask/tests/utility/test_authentication_tools.py index 59c53879..99c74245 100644 --- a/wqflask/tests/utility/test_authentication_tools.py +++ b/wqflask/tests/utility/test_authentication_tools.py @@ -3,6 +3,7 @@ import unittest import mock from utility.authentication_tools import check_resource_availability +from utility.authentication_tools import add_new_resource class TestResponse: @@ -29,6 +30,10 @@ class TestUserSession: return TestUser() +def mock_add_resource(resource_ob, update=False): + return resource_ob + + class TestCheckResourceAvailability(unittest.TestCase): """Test methods related to checking the resource availability""" @mock.patch('utility.authentication_tools.add_new_resource') @@ -111,3 +116,78 @@ class TestCheckResourceAvailability(unittest.TestCase): type(test_dataset).type = mock.PropertyMock(return_value="Temp") self.assertEqual(check_resource_availability(test_dataset), "John Doe") + + +class TestAddNewResource(unittest.TestCase): + """Test cases for add_new_resource method""" + @mock.patch('utility.authentication_tools.webqtlConfig.DEFAULT_PRIVILEGES', + "John Doe") + @mock.patch('utility.authentication_tools.add_resource', mock_add_resource) + @mock.patch('utility.authentication_tools.get_group_code') + def test_add_new_resource_if_publish_datatype(self, group_code_mock): + """Test add_new_resource if dataset type is 'publish'""" + group_code_mock.return_value = "Test" + test_dataset = mock.MagicMock() + type(test_dataset).type = mock.PropertyMock(return_value="Publish") + type(test_dataset).id = mock.PropertyMock(return_value=10) + expected_value = { + "owner_id": "none", + "default_mask": "John Doe", + "group_masks": {}, + "name": "Test_None", + "data": { + "dataset": 10, + "trait": None + }, + "type": "dataset-publish" + } + self.assertEqual(add_new_resource(test_dataset), + expected_value) + + @mock.patch('utility.authentication_tools.webqtlConfig.DEFAULT_PRIVILEGES', + "John Doe") + @mock.patch('utility.authentication_tools.add_resource', mock_add_resource) + @mock.patch('utility.authentication_tools.get_group_code') + def test_add_new_resource_if_geno_datatype(self, group_code_mock): + """Test add_new_resource if dataset type is 'geno'""" + group_code_mock.return_value = "Test" + test_dataset = mock.MagicMock() + type(test_dataset).name = mock.PropertyMock(return_value="Geno") + type(test_dataset).type = mock.PropertyMock(return_value="Geno") + type(test_dataset).id = mock.PropertyMock(return_value=20) + expected_value = { + "owner_id": "none", + "default_mask": "John Doe", + "group_masks": {}, + "name": "Geno", + "data": { + "dataset": 20, + }, + "type": "dataset-geno" + } + self.assertEqual(add_new_resource(test_dataset), + expected_value) + + @mock.patch('utility.authentication_tools.webqtlConfig.DEFAULT_PRIVILEGES', + "John Doe") + @mock.patch('utility.authentication_tools.add_resource', mock_add_resource) + @mock.patch('utility.authentication_tools.get_group_code') + def test_add_new_resource_if_other_datatype(self, group_code_mock): + """Test add_new_resource if dataset type is not 'geno' or 'publish'""" + group_code_mock.return_value = "Test" + test_dataset = mock.MagicMock() + type(test_dataset).name = mock.PropertyMock(return_value="Geno") + type(test_dataset).type = mock.PropertyMock(return_value="other") + type(test_dataset).id = mock.PropertyMock(return_value=20) + expected_value = { + "owner_id": "none", + "default_mask": "John Doe", + "group_masks": {}, + "name": "Geno", + "data": { + "dataset": 20, + }, + "type": "dataset-probeset" + } + self.assertEqual(add_new_resource(test_dataset), + expected_value) -- cgit v1.2.3 From 32f434e9f49583b731f1393328a3ff645c2f9af7 Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Wed, 16 Sep 2020 03:11:01 +0300 Subject: Add new tests for "base/trait.py" * wqflask/tests/base/test_trait.py: New tests. --- wqflask/tests/base/test_trait.py | 101 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 101 insertions(+) create mode 100644 wqflask/tests/base/test_trait.py (limited to 'wqflask/tests') diff --git a/wqflask/tests/base/test_trait.py b/wqflask/tests/base/test_trait.py new file mode 100644 index 00000000..53b0d440 --- /dev/null +++ b/wqflask/tests/base/test_trait.py @@ -0,0 +1,101 @@ +# -*- coding: utf-8 -*- +"""Tests wqflask/base/trait.py""" +import unittest +import mock + +from base.trait import GeneralTrait +from base.trait import retrieve_trait_info + + +class TestResponse: + """Mock Test Response after a request""" + @property + def content(self): + """Mock the content from Requests.get(params).content""" + return "[1, 2, 3, 4]" + + +class TestNilResponse: + """Mock Test Response after a request""" + @property + def content(self): + """Mock the content from Requests.get(params).content""" + return "{}" + + +class MockTrait(GeneralTrait): + @property + def wikidata_alias_fmt(self): + return "Mock alias" + + +class TestRetrieveTraitInfo(unittest.TestCase): + """Tests for 'retrieve_trait_info'""" + def test_retrieve_trait_info_with_empty_dataset(self): + """Test that an exception is raised when dataset is empty""" + with self.assertRaises(AssertionError): + retrieve_trait_info(trait=mock.MagicMock(), + dataset={}) + + @mock.patch('base.trait.requests.get') + @mock.patch('base.trait.g') + def test_retrieve_trait_info_with_empty_trait_info(self, + g_mock, + requests_mock): + """Empty trait info""" + requests_mock.return_value = TestNilResponse() + with self.assertRaises(KeyError): + retrieve_trait_info(trait=mock.MagicMock(), + dataset=mock.MagicMock()) + + @mock.patch('base.trait.requests.get') + @mock.patch('base.trait.g') + def test_retrieve_trait_info_with_non_empty_trait_info(self, + g_mock, + requests_mock): + """Test that attributes are set""" + mock_dataset = mock.MagicMock() + requests_mock.return_value = TestResponse() + type(mock_dataset).display_fields = mock.PropertyMock( + return_value=["a", "b", "c", "d"]) + test_trait = retrieve_trait_info(trait=MockTrait(dataset=mock_dataset), + dataset=mock_dataset) + self.assertEqual(test_trait.a, 1) + self.assertEqual(test_trait.b, 2) + self.assertEqual(test_trait.c, 3) + self.assertEqual(test_trait.d, 4) + + @mock.patch('base.trait.requests.get') + @mock.patch('base.trait.g') + def test_retrieve_trait_info_utf8_parsing(self, + g_mock, + requests_mock): + """Test that utf-8 strings are parsed correctly""" + utf_8_string = "test_string" + mock_dataset = mock.MagicMock() + requests_mock.return_value = TestResponse() + type(mock_dataset).display_fields = mock.PropertyMock( + return_value=["a", "b", "c", "d"]) + type(mock_dataset).type = 'Publish' + + mock_trait = MockTrait( + dataset=mock_dataset, + pre_publication_description=utf_8_string + ) + trait_attrs = { + "group_code": "test_code", + "pre_publication_description": "test_pre_pub", + "pre_publication_abbreviation": "ファイルを画面毎に見て行くには、次のコマンドを使います。", + "post_publication_description": None, + "pubmed_id": None, + 'year': "2020", + "authors": "Jane Doe かいと", + } + for key, val in list(trait_attrs.items()): + setattr(mock_trait, key, val) + test_trait = retrieve_trait_info(trait=mock_trait, + dataset=mock_dataset) + self.assertEqual(test_trait.abbreviation, + "ファイルを画面毎に見て行くには、次のコマンドを使います。") + self.assertEqual(test_trait.authors, + "Jane Doe かいと") -- cgit v1.2.3 From b13ca26da67855f9d32f3209176af052ed46617f Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Thu, 17 Sep 2020 15:55:05 +0300 Subject: Add tests for hmac utility * wqflask/tests/utility/test_hmac.py: New tests. --- wqflask/tests/utility/test_hmac.py | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 wqflask/tests/utility/test_hmac.py (limited to 'wqflask/tests') diff --git a/wqflask/tests/utility/test_hmac.py b/wqflask/tests/utility/test_hmac.py new file mode 100644 index 00000000..c7927685 --- /dev/null +++ b/wqflask/tests/utility/test_hmac.py @@ -0,0 +1,35 @@ +# -*- coding: utf-8 -*- +"""Test hmac utility functions""" + +import unittest +import mock + +from utility.hmac import data_hmac +from utility.hmac import url_for_hmac +from utility.hmac import hmac_creation + + +class TestHmacUtil(unittest.TestCase): + """Test Utility method for hmac creation""" + + def test_hmac_creation(self): + """Test hmac creation with a utf-8 string""" + self.assertEqual(hmac_creation("ファイ"), "21fa1d935bbbb07a7875") + + def test_data_hmac(self): + """Test data_hmac fn with a utf-8 string""" + self.assertEqual(data_hmac("ファイ"), "ファイ:21fa1d935bbbb07a7875") + + @mock.patch("utility.hmac.url_for") + def test_url_for_hmac_with_plain_url(self, mock_url): + """Test url_for_hmac without params""" + mock_url.return_value = "https://mock_url.com/ファイ/" + self.assertEqual(url_for_hmac("ファイ"), + "https://mock_url.com/ファイ/?hm=a62896a50d9ffcff7deb") + + @mock.patch("utility.hmac.url_for") + def test_url_for_hmac_with_param_in_url(self, mock_url): + """Test url_for_hmac with params""" + mock_url.return_value = "https://mock_url.com/?ファイ=1" + self.assertEqual(url_for_hmac("ファイ"), + "https://mock_url.com/?ファイ=1&hm=b2128fb28bc32da3b5b7") -- cgit v1.2.3 From 16faa26e52b1f0191595e16550d553907d2f9d67 Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Thu, 17 Sep 2020 17:21:30 +0300 Subject: Fix errors in tests * wqflask/tests/utility/test_authentication_tools.py test_check_resource_availability_non_default_mask): Mock flask's global 'g' variable properly. * wqflask/tests/base/test_trait.py: Ditto. * wqflask/tests/utility/test_authentication_tools.py: Ditto. --- wqflask/tests/base/test_trait.py | 9 +++------ wqflask/tests/utility/test_authentication_tools.py | 8 ++------ 2 files changed, 5 insertions(+), 12 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/base/test_trait.py b/wqflask/tests/base/test_trait.py index 53b0d440..d333458a 100644 --- a/wqflask/tests/base/test_trait.py +++ b/wqflask/tests/base/test_trait.py @@ -38,9 +38,8 @@ class TestRetrieveTraitInfo(unittest.TestCase): dataset={}) @mock.patch('base.trait.requests.get') - @mock.patch('base.trait.g') + @mock.patch('base.trait.g', mock.Mock()) def test_retrieve_trait_info_with_empty_trait_info(self, - g_mock, requests_mock): """Empty trait info""" requests_mock.return_value = TestNilResponse() @@ -49,9 +48,8 @@ class TestRetrieveTraitInfo(unittest.TestCase): dataset=mock.MagicMock()) @mock.patch('base.trait.requests.get') - @mock.patch('base.trait.g') + @mock.patch('base.trait.g', mock.Mock()) def test_retrieve_trait_info_with_non_empty_trait_info(self, - g_mock, requests_mock): """Test that attributes are set""" mock_dataset = mock.MagicMock() @@ -66,9 +64,8 @@ class TestRetrieveTraitInfo(unittest.TestCase): self.assertEqual(test_trait.d, 4) @mock.patch('base.trait.requests.get') - @mock.patch('base.trait.g') + @mock.patch('base.trait.g', mock.Mock()) def test_retrieve_trait_info_utf8_parsing(self, - g_mock, requests_mock): """Test that utf-8 strings are parsed correctly""" utf_8_string = "test_string" diff --git a/wqflask/tests/utility/test_authentication_tools.py b/wqflask/tests/utility/test_authentication_tools.py index 99c74245..ef94eabc 100644 --- a/wqflask/tests/utility/test_authentication_tools.py +++ b/wqflask/tests/utility/test_authentication_tools.py @@ -38,17 +38,15 @@ class TestCheckResourceAvailability(unittest.TestCase): """Test methods related to checking the resource availability""" @mock.patch('utility.authentication_tools.add_new_resource') @mock.patch('utility.authentication_tools.Redis') - @mock.patch('utility.authentication_tools.g') + @mock.patch('utility.authentication_tools.g', mock.Mock()) @mock.patch('utility.authentication_tools.get_resource_id') def test_check_resource_availability_default_mask( self, resource_id_mock, - g_mock, redis_mock, add_new_resource_mock): """Test the resource availability with default mask""" resource_id_mock.return_value = 1 - g_mock.return_value = mock.Mock() redis_mock.smembers.return_value = [] test_dataset = mock.MagicMock() type(test_dataset).type = mock.PropertyMock(return_value="Test") @@ -58,18 +56,16 @@ class TestCheckResourceAvailability(unittest.TestCase): @mock.patch('utility.authentication_tools.requests.get') @mock.patch('utility.authentication_tools.add_new_resource') @mock.patch('utility.authentication_tools.Redis') - @mock.patch('utility.authentication_tools.g') + @mock.patch('utility.authentication_tools.g', TestUserSession()) @mock.patch('utility.authentication_tools.get_resource_id') def test_check_resource_availability_non_default_mask( self, resource_id_mock, - g_mock, redis_mock, add_new_resource_mock, requests_mock): """Test the resource availability with default mask""" resource_id_mock.return_value = 1 - g_mock.return_value = mock.Mock() redis_mock.smembers.return_value = [] add_new_resource_mock.return_value = {"default_mask": 2} requests_mock.return_value = TestResponse() -- cgit v1.2.3 From 0fd23995fa21c32c2a6005b2fd70b0bd99d13214 Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Thu, 17 Sep 2020 18:05:54 +0300 Subject: Mock "SECRET_HMAC_CODE" * wqflask/tests/utility/test_hmac.py: Mock app.config's "SECRET_HMAC_CODE" value. --- wqflask/tests/utility/test_hmac.py | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/utility/test_hmac.py b/wqflask/tests/utility/test_hmac.py index c7927685..16b50771 100644 --- a/wqflask/tests/utility/test_hmac.py +++ b/wqflask/tests/utility/test_hmac.py @@ -12,24 +12,28 @@ from utility.hmac import hmac_creation class TestHmacUtil(unittest.TestCase): """Test Utility method for hmac creation""" + @mock.patch("utility.hmac.app.config", {'SECRET_HMAC_CODE': "secret"}) def test_hmac_creation(self): """Test hmac creation with a utf-8 string""" - self.assertEqual(hmac_creation("ファイ"), "21fa1d935bbbb07a7875") + self.assertEqual(hmac_creation("ファイ"), "7410466338cfe109e946") + @mock.patch("utility.hmac.app.config", {'SECRET_HMAC_CODE': "secret"}) def test_data_hmac(self): """Test data_hmac fn with a utf-8 string""" - self.assertEqual(data_hmac("ファイ"), "ファイ:21fa1d935bbbb07a7875") + self.assertEqual(data_hmac("ファイ"), "ファイ:7410466338cfe109e946") + @mock.patch("utility.hmac.app.config", {'SECRET_HMAC_CODE': "secret"}) @mock.patch("utility.hmac.url_for") def test_url_for_hmac_with_plain_url(self, mock_url): """Test url_for_hmac without params""" mock_url.return_value = "https://mock_url.com/ファイ/" self.assertEqual(url_for_hmac("ファイ"), - "https://mock_url.com/ファイ/?hm=a62896a50d9ffcff7deb") + "https://mock_url.com/ファイ/?hm=05bc39e659b1948f41e7") + @mock.patch("utility.hmac.app.config", {'SECRET_HMAC_CODE': "secret"}) @mock.patch("utility.hmac.url_for") def test_url_for_hmac_with_param_in_url(self, mock_url): """Test url_for_hmac with params""" mock_url.return_value = "https://mock_url.com/?ファイ=1" self.assertEqual(url_for_hmac("ファイ"), - "https://mock_url.com/?ファイ=1&hm=b2128fb28bc32da3b5b7") + "https://mock_url.com/?ファイ=1&hm=4709c1708270644aed79") -- cgit v1.2.3 From fd151ade1d9f12157bc0ae25570e982122be0c7d Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Wed, 23 Sep 2020 02:23:02 +0300 Subject: Fix failing tests * wqflask/tests/base/test_trait.py: In python2 it's necessary to decode the utf-8 string. --- wqflask/tests/base/test_trait.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/base/test_trait.py b/wqflask/tests/base/test_trait.py index 53b0d440..960f2c81 100644 --- a/wqflask/tests/base/test_trait.py +++ b/wqflask/tests/base/test_trait.py @@ -96,6 +96,6 @@ class TestRetrieveTraitInfo(unittest.TestCase): test_trait = retrieve_trait_info(trait=mock_trait, dataset=mock_dataset) self.assertEqual(test_trait.abbreviation, - "ファイルを画面毎に見て行くには、次のコマンドを使います。") + "ファイルを画面毎に見て行くには、次のコマンドを使います。".decode('utf-8')) self.assertEqual(test_trait.authors, - "Jane Doe かいと") + "Jane Doe かいと".decode('utf-8')) -- cgit v1.2.3 From f67b0c92af93e3153fe9375e98a139386a4f2fb0 Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Sat, 26 Sep 2020 01:21:10 +0300 Subject: Fix failing tests * wqflask/tests/base/test_trait.py: Remove decode function call which is no longer supported in python3. --- wqflask/tests/base/test_trait.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/base/test_trait.py b/wqflask/tests/base/test_trait.py index 9c3154f3..d333458a 100644 --- a/wqflask/tests/base/test_trait.py +++ b/wqflask/tests/base/test_trait.py @@ -93,6 +93,6 @@ class TestRetrieveTraitInfo(unittest.TestCase): test_trait = retrieve_trait_info(trait=mock_trait, dataset=mock_dataset) self.assertEqual(test_trait.abbreviation, - "ファイルを画面毎に見て行くには、次のコマンドを使います。".decode('utf-8')) + "ファイルを画面毎に見て行くには、次のコマンドを使います。") self.assertEqual(test_trait.authors, - "Jane Doe かいと".decode('utf-8')) + "Jane Doe かいと") -- cgit v1.2.3 From bbcecf8e7d8389b8466fe51dde6538387fdce6b5 Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Sat, 26 Sep 2020 01:33:52 +0300 Subject: Fix failing tests by replacing mock with unittest.mock * wqflask/tests/base/test_data_set.py (imports): Run: `find . -type f -name "*py" -print0 | xargs -0 sed -i \ "s|import mock|from unittest import mock|g"` * wqflask/tests/base/test_trait.py(imports): Ditto. * wqflask/tests/utility/test_authentication_tools.py(imports): Ditto. * wqflask/tests/utility/test_hmac.py(imports). Ditto. * wqflask/tests/wqflask/api/test_gen_menu.py: Ditto --- wqflask/tests/base/test_data_set.py | 2 +- wqflask/tests/base/test_trait.py | 2 +- wqflask/tests/utility/test_authentication_tools.py | 2 +- wqflask/tests/utility/test_hmac.py | 2 +- wqflask/tests/wqflask/api/test_gen_menu.py | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/base/test_data_set.py b/wqflask/tests/base/test_data_set.py index b1de4932..96563a16 100644 --- a/wqflask/tests/base/test_data_set.py +++ b/wqflask/tests/base/test_data_set.py @@ -1,7 +1,7 @@ """Tests for wqflask/base/data_set.py""" import unittest -import mock +from unittest import mock from wqflask import app from .data import gen_menu_json diff --git a/wqflask/tests/base/test_trait.py b/wqflask/tests/base/test_trait.py index d333458a..bf4e88e0 100644 --- a/wqflask/tests/base/test_trait.py +++ b/wqflask/tests/base/test_trait.py @@ -1,7 +1,7 @@ # -*- coding: utf-8 -*- """Tests wqflask/base/trait.py""" import unittest -import mock +from unittest import mock from base.trait import GeneralTrait from base.trait import retrieve_trait_info diff --git a/wqflask/tests/utility/test_authentication_tools.py b/wqflask/tests/utility/test_authentication_tools.py index ef94eabc..5c391be5 100644 --- a/wqflask/tests/utility/test_authentication_tools.py +++ b/wqflask/tests/utility/test_authentication_tools.py @@ -1,6 +1,6 @@ """Tests for authentication tools""" import unittest -import mock +from unittest import mock from utility.authentication_tools import check_resource_availability from utility.authentication_tools import add_new_resource diff --git a/wqflask/tests/utility/test_hmac.py b/wqflask/tests/utility/test_hmac.py index 16b50771..7c61c0a6 100644 --- a/wqflask/tests/utility/test_hmac.py +++ b/wqflask/tests/utility/test_hmac.py @@ -2,7 +2,7 @@ """Test hmac utility functions""" import unittest -import mock +from unittest import mock from utility.hmac import data_hmac from utility.hmac import url_for_hmac diff --git a/wqflask/tests/wqflask/api/test_gen_menu.py b/wqflask/tests/wqflask/api/test_gen_menu.py index bf41054d..84898bd1 100644 --- a/wqflask/tests/wqflask/api/test_gen_menu.py +++ b/wqflask/tests/wqflask/api/test_gen_menu.py @@ -1,6 +1,6 @@ """Test cases for wqflask.api.gen_menu""" import unittest -import mock +from unittest import mock from wqflask import app from wqflask.api.gen_menu import gen_dropdown_json -- cgit v1.2.3 From e247f43bf9bc31164948760694ff796bb469ae4c Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Mon, 28 Sep 2020 02:25:58 +0300 Subject: Update trait tests * wqflask/tests/base/test_trait.py (test_retrieve_trait_info_with_non_empty_lrs): Check trait.LRS_score_repr is set correctly if trait.lrs is None. (test_retrieve_trait_info_with_empty_lrs_field): Check trait.LRS_score_repr and test_trait.LRS_location_repr is set correctly if trait.lrs is None. (test_retrieve_trait_info_with_empty_chr_field): Check test_trait.LRS_score_repr and test_trait.LRS_location_repr is set correctly if trait.locus is None. --- wqflask/tests/base/test_trait.py | 134 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 134 insertions(+) (limited to 'wqflask/tests') diff --git a/wqflask/tests/base/test_trait.py b/wqflask/tests/base/test_trait.py index 960f2c81..1a3820f2 100644 --- a/wqflask/tests/base/test_trait.py +++ b/wqflask/tests/base/test_trait.py @@ -99,3 +99,137 @@ class TestRetrieveTraitInfo(unittest.TestCase): "ファイルを画面毎に見て行くには、次のコマンドを使います。".decode('utf-8')) self.assertEqual(test_trait.authors, "Jane Doe かいと".decode('utf-8')) + + @mock.patch('base.trait.requests.get') + @mock.patch('base.trait.g') + @mock.patch('base.trait.get_resource_id') + def test_retrieve_trait_info_with_non_empty_lrs(self, + resource_id_mock, + g_mock, + requests_mock): + """Test """ + resource_id_mock.return_value = 1 + g_mock.db.execute.return_value.fetchone = mock.Mock() + g_mock.db.execute.return_value.fetchone.side_effect = [ + [1, 2, 3, 4], # trait_info = g.db.execute(query).fetchone() + [1, 2.37, 3, 4, 5], # trait_qtl = g.db.execute(query).fetchone() + [2.7333, 2.1204] # trait_info = g.db.execute(query).fetchone() + ] + requests_mock.return_value = None + + mock_dataset = mock.MagicMock() + type(mock_dataset).display_fields = mock.PropertyMock( + return_value=["a", "b", "c", "d"]) + type(mock_dataset).type = "ProbeSet" + type(mock_dataset).name = "RandomName" + + mock_trait = MockTrait( + dataset=mock_dataset, + pre_publication_description="test_string" + ) + trait_attrs = { + "description": "some description", + "probe_target_description": "some description", + "cellid": False, + "chr": 2.733, + "mb": 2.1204 + } + + for key, val in list(trait_attrs.items()): + setattr(mock_trait, key, val) + test_trait = retrieve_trait_info(trait=mock_trait, + dataset=mock_dataset, + get_qtl_info=True) + self.assertEqual(test_trait.LRS_score_repr, + "2.4") + + @mock.patch('base.trait.requests.get') + @mock.patch('base.trait.g') + @mock.patch('base.trait.get_resource_id') + def test_retrieve_trait_info_with_empty_lrs_field(self, + resource_id_mock, + g_mock, + requests_mock): + """Test retrieve trait info with empty lrs field""" + resource_id_mock.return_value = 1 + g_mock.db.execute.return_value.fetchone = mock.Mock() + g_mock.db.execute.return_value.fetchone.side_effect = [ + [1, 2, 3, 4], # trait_info = g.db.execute(query).fetchone() + [1, None, 3, 4, 5], # trait_qtl = g.db.execute(query).fetchone() + [2, 3] # trait_info = g.db.execute(query).fetchone() + ] + requests_mock.return_value = None + + mock_dataset = mock.MagicMock() + type(mock_dataset).display_fields = mock.PropertyMock( + return_value=["a", "b", "c", "d"]) + type(mock_dataset).type = "ProbeSet" + type(mock_dataset).name = "RandomName" + + mock_trait = MockTrait( + dataset=mock_dataset, + pre_publication_description="test_string" + ) + trait_attrs = { + "description": "some description", + "probe_target_description": "some description", + "cellid": False, + "chr": 2.733, + "mb": 2.1204 + } + + for key, val in list(trait_attrs.items()): + setattr(mock_trait, key, val) + test_trait = retrieve_trait_info(trait=mock_trait, + dataset=mock_dataset, + get_qtl_info=True) + self.assertEqual(test_trait.LRS_score_repr, + "N/A") + self.assertEqual(test_trait.LRS_location_repr, + "Chr2: 3.000000") + + @mock.patch('base.trait.requests.get') + @mock.patch('base.trait.g') + @mock.patch('base.trait.get_resource_id') + def test_retrieve_trait_info_with_empty_chr_field(self, + resource_id_mock, + g_mock, + requests_mock): + """Test retrieve trait info with empty chr field""" + resource_id_mock.return_value = 1 + g_mock.db.execute.return_value.fetchone = mock.Mock() + g_mock.db.execute.return_value.fetchone.side_effect = [ + [1, 2, 3, 4], # trait_info = g.db.execute(query).fetchone() + [1, 2, 3, 4, 5], # trait_qtl = g.db.execute(query).fetchone() + [None, 3] # trait_info = g.db.execute(query).fetchone() + ] + + requests_mock.return_value = None + + mock_dataset = mock.MagicMock() + type(mock_dataset).display_fields = mock.PropertyMock( + return_value=["a", "b", "c", "d"]) + type(mock_dataset).type = "ProbeSet" + type(mock_dataset).name = "RandomName" + + mock_trait = MockTrait( + dataset=mock_dataset, + pre_publication_description="test_string" + ) + trait_attrs = { + "description": "some description", + "probe_target_description": "some description", + "cellid": False, + "chr": 2.733, + "mb": 2.1204 + } + + for key, val in list(trait_attrs.items()): + setattr(mock_trait, key, val) + test_trait = retrieve_trait_info(trait=mock_trait, + dataset=mock_dataset, + get_qtl_info=True) + self.assertEqual(test_trait.LRS_score_repr, + "N/A") + self.assertEqual(test_trait.LRS_location_repr, + "N/A") -- cgit v1.2.3 From 21ec6863d7f8380d66c39f1ed3b8d9cc0dc86e49 Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Mon, 28 Sep 2020 18:34:53 +0300 Subject: Fix failing test * wqflask/tests/base/test_trait.py: Add app_context to test class, otherwise an error related to working outside the app_context is generated. Adding the app_context is required when mocking "Flask.g". --- wqflask/tests/base/test_trait.py | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/base/test_trait.py b/wqflask/tests/base/test_trait.py index 60ebaee0..826ccefd 100644 --- a/wqflask/tests/base/test_trait.py +++ b/wqflask/tests/base/test_trait.py @@ -3,6 +3,7 @@ import unittest from unittest import mock +from wqflask import app from base.trait import GeneralTrait from base.trait import retrieve_trait_info @@ -31,6 +32,14 @@ class MockTrait(GeneralTrait): class TestRetrieveTraitInfo(unittest.TestCase): """Tests for 'retrieve_trait_info'""" + + def setUp(self): + self.app_context = app.app_context() + self.app_context.push() + + def tearDown(self): + self.app_context.pop() + def test_retrieve_trait_info_with_empty_dataset(self): """Test that an exception is raised when dataset is empty""" with self.assertRaises(AssertionError): @@ -104,7 +113,7 @@ class TestRetrieveTraitInfo(unittest.TestCase): resource_id_mock, g_mock, requests_mock): - """Test """ + """Test retrieve trait info when lrs has a value""" resource_id_mock.return_value = 1 g_mock.db.execute.return_value.fetchone = mock.Mock() g_mock.db.execute.return_value.fetchone.side_effect = [ -- cgit v1.2.3 From ce728fa92e02725202bca486e8336b2e1158f4ef Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Tue, 29 Sep 2020 15:57:01 +0300 Subject: Add test for process_traits from collections.py * wqflask/tests/wqflask/test_collect.py: Add it. --- wqflask/tests/wqflask/test_collect.py | 73 +++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 wqflask/tests/wqflask/test_collect.py (limited to 'wqflask/tests') diff --git a/wqflask/tests/wqflask/test_collect.py b/wqflask/tests/wqflask/test_collect.py new file mode 100644 index 00000000..06609b4c --- /dev/null +++ b/wqflask/tests/wqflask/test_collect.py @@ -0,0 +1,73 @@ +"""Test cases for some methods in collect.py""" + +import unittest +import mock + +from flask import Flask +from wqflask.collect import process_traits + +app = Flask(__name__) + + +class MockSession: + """Helper class for mocking wqflask.collect.g.user_session.logged_in""" + def __init__(self, is_logged_in=False): + self.is_logged_in = is_logged_in + + @property + def logged_in(self): + return self.is_logged_in + + +class MockFlaskG: + """Helper class for mocking wqflask.collect.g.user_session""" + def __init__(self, is_logged_in=False): + self.is_logged_in = is_logged_in + + @property + def user_session(self): + if self.is_logged_in: + return MockSession(is_logged_in=True) + return MockSession() + + +class TestCollect(unittest.TestCase): + + def setUp(self): + self.app_context = app.app_context() + self.app_context.push() + + def tearDown(self): + self.app_context.pop() + + @mock.patch("wqflask.collect.g", MockFlaskG()) + def test_process_traits_with_bytestring(self): + """ + Test that the correct traits are returned when the user is logged + out and bytes are used. + """ + self.assertEqual(process_traits( + b'1452452_at:HC_M2_0606_P:163d04f7db7c9e110de6,' + b'1452447_at:HC_M2_0606_P:eeece8fceb67072debea,' + b'1451401_a_at:HC_M2_0606_P:a043d23b3b3906d8318e,' + b'1429252_at:HC_M2_0606_P:6fa378b349bc9180e8f5'), + set(['1429252_at:HC_M2_0606_P', + '1451401_a_at:HC_M2_0606_P', + '1452447_at:HC_M2_0606_P', + '1452452_at:HC_M2_0606_P'])) + + @mock.patch("wqflask.collect.g", MockFlaskG()) + def test_process_traits_with_normal_string(self): + """ + Test that the correct traits are returned when the user is logged + out and a normal string is used. + """ + self.assertEqual(process_traits( + '1452452_at:HC_M2_0606_P:163d04f7db7c9e110de6,' + '1452447_at:HC_M2_0606_P:eeece8fceb67072debea,' + '1451401_a_at:HC_M2_0606_P:a043d23b3b3906d8318e,' + '1429252_at:HC_M2_0606_P:6fa378b349bc9180e8f5'), + set(['1429252_at:HC_M2_0606_P', + '1451401_a_at:HC_M2_0606_P', + '1452447_at:HC_M2_0606_P', + '1452452_at:HC_M2_0606_P'])) -- cgit v1.2.3 From 475b6e333e6356103592b0983d5efb8e84eb73e7 Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Wed, 30 Sep 2020 02:09:27 +0300 Subject: Fix import in tests --- wqflask/tests/wqflask/test_collect.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/wqflask/test_collect.py b/wqflask/tests/wqflask/test_collect.py index 06609b4c..9a36132d 100644 --- a/wqflask/tests/wqflask/test_collect.py +++ b/wqflask/tests/wqflask/test_collect.py @@ -1,7 +1,7 @@ """Test cases for some methods in collect.py""" import unittest -import mock +from unittest import mock from flask import Flask from wqflask.collect import process_traits -- cgit v1.2.3 From 4d16656304b9702c124721e82ea0dcda3c40ae44 Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Tue, 29 Sep 2020 15:57:01 +0300 Subject: Add test for process_traits from collections.py * wqflask/tests/wqflask/test_collect.py: Add it. --- wqflask/tests/wqflask/test_collect.py | 57 +++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 wqflask/tests/wqflask/test_collect.py (limited to 'wqflask/tests') diff --git a/wqflask/tests/wqflask/test_collect.py b/wqflask/tests/wqflask/test_collect.py new file mode 100644 index 00000000..6b8d7931 --- /dev/null +++ b/wqflask/tests/wqflask/test_collect.py @@ -0,0 +1,57 @@ +"""Test cases for some methods in collect.py""" + +import unittest +import mock + +from flask import Flask +from wqflask.collect import process_traits + +app = Flask(__name__) + + +class MockSession: + """Helper class for mocking wqflask.collect.g.user_session.logged_in""" + def __init__(self, is_logged_in=False): + self.is_logged_in = is_logged_in + + @property + def logged_in(self): + return self.is_logged_in + + +class MockFlaskG: + """Helper class for mocking wqflask.collect.g.user_session""" + def __init__(self, is_logged_in=False): + self.is_logged_in = is_logged_in + + @property + def user_session(self): + if self.is_logged_in: + return MockSession(is_logged_in=True) + return MockSession() + + +class TestCollect(unittest.TestCase): + + def setUp(self): + self.app_context = app.app_context() + self.app_context.push() + + def tearDown(self): + self.app_context.pop() + + @mock.patch("wqflask.collect.g", MockFlaskG()) + def test_process_traits_when_user_is_logged_out(self): + """ + Test that the correct traits are returned when the user is logged + out + """ + self.assertEqual(process_traits( + b'1452452_at:HC_M2_0606_P:163d04f7db7c9e110de6,' + b'1452447_at:HC_M2_0606_P:eeece8fceb67072debea,' + b'1451401_a_at:HC_M2_0606_P:a043d23b3b3906d8318e,' + b'1429252_at:HC_M2_0606_P:6fa378b349bc9180e8f5'), + set(['1429252_at:HC_M2_0606_P', + '1451401_a_at:HC_M2_0606_P', + '1452447_at:HC_M2_0606_P', + '1452452_at:HC_M2_0606_P'])) -- cgit v1.2.3 From b2b7bacdbc8dc28dd062ebdb94698fca88f9b0cb Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Tue, 20 Oct 2020 22:19:56 +0300 Subject: Add pbkdf2 tests * wqflask/tests/wqflask/test_pbkdf2.py: New tests. --- wqflask/tests/wqflask/test_pbkdf2.py | 61 ++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 wqflask/tests/wqflask/test_pbkdf2.py (limited to 'wqflask/tests') diff --git a/wqflask/tests/wqflask/test_pbkdf2.py b/wqflask/tests/wqflask/test_pbkdf2.py new file mode 100644 index 00000000..a33fbd4f --- /dev/null +++ b/wqflask/tests/wqflask/test_pbkdf2.py @@ -0,0 +1,61 @@ +"""Test cases pbkdf2""" + +import unittest +from wqflask.pbkdf2 import pbkdf2_hex + + +class TestPbkdf2(unittest.TestCase): + def test_pbkdf2_hex(self): + """ + Test pbkdf2_hex function + """ + + for password, salt, iterations, keylen, expected_value in [ + ('password', 'salt', 1, 20, + '0c60c80f961f0e71f3a9b524af6012062fe037a6'), + ('password', 'salt', 2, 20, + 'ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957'), + ('password', 'salt', 4096, 20, + '4b007901b765489abead49d926f721d065a429c1'), + ('passwordPASSWORDpassword', + 'saltSALTsaltSALTsaltSALTsaltSALTsalt', + 4096, 25, + '3d2eec4fe41c849b80c8d83662c0e44a8b291a964cf2f07038'), + ('pass\x00word', 'sa\x00lt', 4096, 16, + '56fa6aa75548099dcc37d7f03425e0c3'), + ('password', 'ATHENA.MIT.EDUraeburn', 1, 16, + 'cdedb5281bb2f801565a1122b2563515'), + ('password', 'ATHENA.MIT.EDUraeburn', 1, 32, + ('cdedb5281bb2f80' + '1565a1122b256351' + '50ad1f7a04bb9f3a33' + '3ecc0e2e1f70837')), + ('password', 'ATHENA.MIT.EDUraeburn', 2, 16, + '01dbee7f4a9e243e988b62c73cda935d'), + ('password', 'ATHENA.MIT.EDUraeburn', 2, 32, + ('01dbee7f4a9e243e9' + '88b62c73cda935da05' + '378b93244ec8f48a99' + 'e61ad799d86')), + ('password', 'ATHENA.MIT.EDUraeburn', 1200, 32, + ('5c08eb61fdf71e' + '4e4ec3cf6ba1f55' + '12ba7e52ddbc5e51' + '42f708a31e2e62b1e13')), + ('X' * 64, 'pass phrase equals block size', 1200, 32, + ('139c30c0966bc32ba' + '55fdbf212530ac9c5' + 'ec59f1a452f5cc9ad' + '940fea0598ed1')), + ('X' * 65, 'pass phrase exceeds block size', 1200, 32, + ('9ccad6d468770cd' + '51b10e6a68721be6' + '11a8b4d282601db3' + 'b36be9246915ec82a')) + ]: + self.assertEqual( + pbkdf2_hex(data=password, + salt=salt, + iterations=iterations, + keylen=keylen), + expected_value) -- cgit v1.2.3 From 5d06524c8465064248cc3605c69dd32687ea7565 Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Tue, 20 Oct 2020 22:55:19 +0300 Subject: Add tests for encoding password * wqflask/tests/wqflask/test_user_login.py: New tests. --- wqflask/tests/wqflask/test_user_login.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 wqflask/tests/wqflask/test_user_login.py (limited to 'wqflask/tests') diff --git a/wqflask/tests/wqflask/test_user_login.py b/wqflask/tests/wqflask/test_user_login.py new file mode 100644 index 00000000..61cd9ab9 --- /dev/null +++ b/wqflask/tests/wqflask/test_user_login.py @@ -0,0 +1,21 @@ +"""Test cases for some methods in login.py""" + +import unittest +from wqflask.user_login import encode_password + + +class TestUserLogin(unittest.TestCase): + def test_encode_password(self): + """ + Test encode password + """ + pass_gen_fields = { + "salt": "salt", + "hashfunc": "sha1", + "iterations": 4096, + "keylength": 20, + } + self.assertEqual( + encode_password(pass_gen_fields, + "password").get("password"), + '4b007901b765489abead49d926f721d065a429c1') -- cgit v1.2.3 From 76f425b1e76debe90f723c99594236853b05b979 Mon Sep 17 00:00:00 2001 From: Alexanderlacuna Date: Mon, 26 Oct 2020 21:50:56 +0300 Subject: modified test file --- wqflask/tests/wqflask/show_trait/__init__.py | 0 .../wqflask/show_trait/test_export_trait_data.py | 103 +++++++++++++++++++++ 2 files changed, 103 insertions(+) create mode 100644 wqflask/tests/wqflask/show_trait/__init__.py create mode 100644 wqflask/tests/wqflask/show_trait/test_export_trait_data.py (limited to 'wqflask/tests') diff --git a/wqflask/tests/wqflask/show_trait/__init__.py b/wqflask/tests/wqflask/show_trait/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/wqflask/tests/wqflask/show_trait/test_export_trait_data.py b/wqflask/tests/wqflask/show_trait/test_export_trait_data.py new file mode 100644 index 00000000..f77f11c9 --- /dev/null +++ b/wqflask/tests/wqflask/show_trait/test_export_trait_data.py @@ -0,0 +1,103 @@ +import unittest +from wqflask.show_trait.export_trait_data import dict_to_sorted_list,cmp_samples +class TestDictionaryList(unittest.TestCase): + def setUp(self): + self.sample1={ + "other":"exp1", + "name":"exp2" + } + self.sample2={ + 'se':1, + 'num_cases':4, + 'value':6, + "name":3 + + } + self.reversed={ + "name":3, + 'value':6, + 'num_cases':4, + 'se':1 + } + self.oneItem={ + 'item1':"one" + } + def test_dict_to_sortedlist(self): + '''Test for converting dict to sorted list''' + + self.assertEqual(['exp2','exp1'],dict_to_sorted_list(self.sample1)) + self.assertEqual([3, 6, 1, 4],dict_to_sorted_list(self.sample2)) + self.assertEqual([3, 6, 1, 4],dict_to_sorted_list(self.reversed)) + self.assertEqual(["one"],dict_to_sorted_list(self.oneItem)) + '''test that the func returns the values not the keys''' + self.assertFalse(['other','name']==['exp2','exp1']) + + + +class TestComparison(unittest.TestCase): + def setUp(self): + self.sampleA=[ + [ + ('value','other'), + ('name','test_name') + ] + ] + self.sampleB=[ + [ + ('value','other'), + ('unknown','test_name') + ] + ] + self.sampleC=[ + [('other',"value"), + ('name','value') + ], + [ + ('name',"value"), + ('value',"name") + ], + [ + ('other',"value"), + ('name','value' + )], + [ + ('name',"name1"), + ('se',"valuex") + ], + [( + 'value',"name1"), + ('se',"valuex") + ], + [( + 'other',"name1"), + ('se',"valuex" + ) + ], + [( + 'name',"name_val"), + ('num_cases',"num_val") + ], + [( + "other_a","val_a"), + ('other_b',"val" + ) + ]] + + + + + + def test_cmp_samples(self): + '''Test for func that does sample comparisons''' + + results=[cmp_samples(val[0],val[1]) for val in self.sampleA] + resultB=[cmp_samples(val[0],val[1]) for val in self.sampleB] + resultC=[cmp_samples(val[0],val[1]) for val in self.sampleC] + self.assertEqual(1,*results) + self.assertEqual(-1,*resultB) + self.assertEqual([1, -1, 1, -1, -1, 1, -1, -1],resultC) + + + + + -- cgit v1.2.3 From 09bae9afdde636b84c8e42140f21ba3f60903d9b Mon Sep 17 00:00:00 2001 From: Alexanderlacuna Date: Tue, 27 Oct 2020 12:37:02 +0300 Subject: modified to use pep8 standards --- .../wqflask/show_trait/test_export_trait_data.py | 59 +++++++++++----------- 1 file changed, 30 insertions(+), 29 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/wqflask/show_trait/test_export_trait_data.py b/wqflask/tests/wqflask/show_trait/test_export_trait_data.py index f77f11c9..c64196ff 100644 --- a/wqflask/tests/wqflask/show_trait/test_export_trait_data.py +++ b/wqflask/tests/wqflask/show_trait/test_export_trait_data.py @@ -1,54 +1,56 @@ import unittest -from wqflask.show_trait.export_trait_data import dict_to_sorted_list,cmp_samples -class TestDictionaryList(unittest.TestCase): - def setUp(self): - self.sample1={ +from wqflask.show_trait.export_trait_data import dict_to_sorted_list +from wqflask.show_trait.export_trait_data import cmp_samples + +class TestExportTraits(unittest.TestCase): + def test_dict_to_sortedlist(self): + '''Test for conversion of dict to sorted list''' + sample1={ "other":"exp1", "name":"exp2" } - self.sample2={ + sample2={ 'se':1, 'num_cases':4, 'value':6, "name":3 } - self.reversed={ + rever={ "name":3, 'value':6, 'num_cases':4, 'se':1 } - self.oneItem={ + oneItem={ 'item1':"one" } - def test_dict_to_sortedlist(self): - '''Test for converting dict to sorted list''' - - self.assertEqual(['exp2','exp1'],dict_to_sorted_list(self.sample1)) - self.assertEqual([3, 6, 1, 4],dict_to_sorted_list(self.sample2)) - self.assertEqual([3, 6, 1, 4],dict_to_sorted_list(self.reversed)) - self.assertEqual(["one"],dict_to_sorted_list(self.oneItem)) + + + self.assertEqual(['exp2','exp1'],dict_to_sorted_list(sample1)) + self.assertEqual([3, 6, 1, 4],dict_to_sorted_list(sample2)) + self.assertEqual([3, 6, 1, 4],dict_to_sorted_list(rever)) + self.assertEqual(["one"],dict_to_sorted_list(oneItem)) '''test that the func returns the values not the keys''' - self.assertFalse(['other','name']==['exp2','exp1']) + self.assertFalse(['other','name']==dict_to_sorted_list(sample1)) + def test_cmp_samples(self): + '''test for function that does comparisons of samples''' -class TestComparison(unittest.TestCase): - def setUp(self): - self.sampleA=[ + sampleA=[ [ ('value','other'), ('name','test_name') ] ] - self.sampleB=[ + sampleB=[ [ ('value','other'), ('unknown','test_name') ] ] - self.sampleC=[ + sampleC=[ [('other',"value"), ('name','value') ], @@ -82,20 +84,19 @@ class TestComparison(unittest.TestCase): ('other_b',"val" ) ]] + results=[cmp_samples(val[0],val[1]) for val in sampleA] + resultB=[cmp_samples(val[0],val[1]) for val in sampleB] + resultC=[cmp_samples(val[0],val[1]) for val in sampleC] + self.assertEqual(1,*results) + self.assertEqual(-1,*resultB) + self.assertEqual([1, -1, 1, -1, -1, 1, -1, -1],resultC) + + - def test_cmp_samples(self): - '''Test for func that does sample comparisons''' - - results=[cmp_samples(val[0],val[1]) for val in self.sampleA] - resultB=[cmp_samples(val[0],val[1]) for val in self.sampleB] - resultC=[cmp_samples(val[0],val[1]) for val in self.sampleC] - self.assertEqual(1,*results) - self.assertEqual(-1,*resultB) - self.assertEqual([1, -1, 1, -1, -1, 1, -1, -1],resultC) -- cgit v1.2.3 From cf4a7154bd7243aa1cf25e04d03d89cb8b43c7c5 Mon Sep 17 00:00:00 2001 From: Alexanderlacuna Date: Tue, 27 Oct 2020 13:19:27 +0300 Subject: added changes to file --- .../wqflask/show_trait/test_export_trait_data.py | 186 ++++++++++----------- 1 file changed, 87 insertions(+), 99 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/wqflask/show_trait/test_export_trait_data.py b/wqflask/tests/wqflask/show_trait/test_export_trait_data.py index c64196ff..2f95d219 100644 --- a/wqflask/tests/wqflask/show_trait/test_export_trait_data.py +++ b/wqflask/tests/wqflask/show_trait/test_export_trait_data.py @@ -2,103 +2,91 @@ import unittest from wqflask.show_trait.export_trait_data import dict_to_sorted_list from wqflask.show_trait.export_trait_data import cmp_samples -class TestExportTraits(unittest.TestCase): - def test_dict_to_sortedlist(self): - '''Test for conversion of dict to sorted list''' - sample1={ - "other":"exp1", - "name":"exp2" - } - sample2={ - 'se':1, - 'num_cases':4, - 'value':6, - "name":3 - - } - rever={ - "name":3, - 'value':6, - 'num_cases':4, - 'se':1 - } - oneItem={ - 'item1':"one" - } - - - self.assertEqual(['exp2','exp1'],dict_to_sorted_list(sample1)) - self.assertEqual([3, 6, 1, 4],dict_to_sorted_list(sample2)) - self.assertEqual([3, 6, 1, 4],dict_to_sorted_list(rever)) - self.assertEqual(["one"],dict_to_sorted_list(oneItem)) - '''test that the func returns the values not the keys''' - self.assertFalse(['other','name']==dict_to_sorted_list(sample1)) - - def test_cmp_samples(self): - '''test for function that does comparisons of samples''' - - - sampleA=[ - [ - ('value','other'), - ('name','test_name') - ] - ] - sampleB=[ - [ - ('value','other'), - ('unknown','test_name') - ] - ] - sampleC=[ - [('other',"value"), - ('name','value') - ], - [ - ('name',"value"), - ('value',"name") - ], - [ - ('other',"value"), - ('name','value' - )], - [ - ('name',"name1"), - ('se',"valuex") - ], - [( - 'value',"name1"), - ('se',"valuex") - ], - [( - 'other',"name1"), - ('se',"valuex" - ) - ], - [( - 'name',"name_val"), - ('num_cases',"num_val") - ], - [( - "other_a","val_a"), - ('other_b',"val" - ) - ]] - results=[cmp_samples(val[0],val[1]) for val in sampleA] - resultB=[cmp_samples(val[0],val[1]) for val in sampleB] - resultC=[cmp_samples(val[0],val[1]) for val in sampleC] - self.assertEqual(1,*results) - self.assertEqual(-1,*resultB) - self.assertEqual([1, -1, 1, -1, -1, 1, -1, -1],resultC) - - - - - - - - - - - +class TestExportTraits(unittest.TestCase): + """Test methods related converting dict to sortedlist""" + def test_dict_to_sortedlist(self): + '''Test for conversion of dict to sorted list''' + sample1 = { + "other": "exp1", + "name": "exp2" + } + sample2 = { + "se": 1, + "num_cases": 4, + "value": 6, + "name": 3 + + } + rever = { + "name": 3, + "value": 6, + "num_cases": 4, + "se": 1 + } + oneItem = { + "item1": "one" + } + + self.assertEqual(["exp2", "exp1"], dict_to_sorted_list(sample1)) + self.assertEqual([3, 6, 1, 4], dict_to_sorted_list(sample2)) + self.assertEqual([3, 6, 1, 4], dict_to_sorted_list(rever)) + self.assertEqual(["one"], dict_to_sorted_list(oneItem)) + '''test that the func returns the values not the keys''' + self.assertFalse(["other", "name"] == dict_to_sorted_list(sample1)) + + def test_cmp_samples(self): + '''test for function that does comparisons of samples''' + + sampleA = [ + [ + ("value", "other"), + ("name", "test_name") + ] + ] + sampleB = [ + [ + ("value", "other"), + ("unknown", "test_name") + ] + ] + sampleC = [ + [("other", "value"), + ("name", "value") + ], + [ + ("name", "value"), + ("value", "name") + ], + [ + ("other", "value"), + ("name", "value" + )], + [ + ("name", "name1"), + ("se", "valuex") + ], + [( + "value", "name1"), + ("se", "valuex") + ], + [( + "other", "name1"), + ("se", "valuex" + ) + ], + [( + "name", "name_val"), + ("num_cases", "num_val") + ], + [( + "other_a", "val_a"), + ("other_b", "val" + ) + ]] + results = [cmp_samples(val[0], val[1]) for val in sampleA] + resultB = [cmp_samples(val[0], val[1]) for val in sampleB] + resultC = [cmp_samples(val[0], val[1]) for val in sampleC] + self.assertEqual(1, *results) + self.assertEqual(-1, *resultB) + self.assertEqual([1, -1, 1, -1, -1, 1, -1, -1], resultC) -- cgit v1.2.3 From 1cf15edbcc3833cd2ec0938d5c6591d7a2e219b7 Mon Sep 17 00:00:00 2001 From: Alexanderlacuna Date: Tue, 27 Oct 2020 14:07:49 +0300 Subject: address failures --- wqflask/tests/wqflask/show_trait/test_export_trait_data.py | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/wqflask/show_trait/test_export_trait_data.py b/wqflask/tests/wqflask/show_trait/test_export_trait_data.py index 2f95d219..bc45a213 100644 --- a/wqflask/tests/wqflask/show_trait/test_export_trait_data.py +++ b/wqflask/tests/wqflask/show_trait/test_export_trait_data.py @@ -4,9 +4,10 @@ from wqflask.show_trait.export_trait_data import cmp_samples class TestExportTraits(unittest.TestCase): - """Test methods related converting dict to sortedlist""" + """Test methods related to converting dict to sortedlist""" + def test_dict_to_sortedlist(self): - '''Test for conversion of dict to sorted list''' + '''test for conversion of dict to sorted list''' sample1 = { "other": "exp1", "name": "exp2" @@ -36,8 +37,7 @@ class TestExportTraits(unittest.TestCase): self.assertFalse(["other", "name"] == dict_to_sorted_list(sample1)) def test_cmp_samples(self): - '''test for function that does comparisons of samples''' - + '''test for comparing samples function''' sampleA = [ [ ("value", "other"), @@ -83,10 +83,12 @@ class TestExportTraits(unittest.TestCase): "other_a", "val_a"), ("other_b", "val" ) - ]] + ] + ] results = [cmp_samples(val[0], val[1]) for val in sampleA] resultB = [cmp_samples(val[0], val[1]) for val in sampleB] resultC = [cmp_samples(val[0], val[1]) for val in sampleC] + self.assertEqual(1, *results) self.assertEqual(-1, *resultB) self.assertEqual([1, -1, 1, -1, -1, 1, -1, -1], resultC) -- cgit v1.2.3 From abf3758d86c1ee37e458d79e62be69e4c23e515c Mon Sep 17 00:00:00 2001 From: Alexanderlacuna Date: Tue, 27 Oct 2020 14:26:06 +0300 Subject: switch from single quote to double quote --- wqflask/tests/wqflask/show_trait/test_export_trait_data.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/wqflask/show_trait/test_export_trait_data.py b/wqflask/tests/wqflask/show_trait/test_export_trait_data.py index bc45a213..98d599b1 100644 --- a/wqflask/tests/wqflask/show_trait/test_export_trait_data.py +++ b/wqflask/tests/wqflask/show_trait/test_export_trait_data.py @@ -7,7 +7,7 @@ class TestExportTraits(unittest.TestCase): """Test methods related to converting dict to sortedlist""" def test_dict_to_sortedlist(self): - '''test for conversion of dict to sorted list''' + """test for conversion of dict to sorted list""" sample1 = { "other": "exp1", "name": "exp2" @@ -33,11 +33,11 @@ class TestExportTraits(unittest.TestCase): self.assertEqual([3, 6, 1, 4], dict_to_sorted_list(sample2)) self.assertEqual([3, 6, 1, 4], dict_to_sorted_list(rever)) self.assertEqual(["one"], dict_to_sorted_list(oneItem)) - '''test that the func returns the values not the keys''' + """test that the func returns the values not the keys""" self.assertFalse(["other", "name"] == dict_to_sorted_list(sample1)) def test_cmp_samples(self): - '''test for comparing samples function''' + """test for comparing samples function""" sampleA = [ [ ("value", "other"), -- cgit v1.2.3 From 629553ec992c59500ef64b04b8fc9fb0500bcaee Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Wed, 28 Oct 2020 23:11:59 +0300 Subject: Add tests for cookie verification --- wqflask/tests/wqflask/test_user_session.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 wqflask/tests/wqflask/test_user_session.py (limited to 'wqflask/tests') diff --git a/wqflask/tests/wqflask/test_user_session.py b/wqflask/tests/wqflask/test_user_session.py new file mode 100644 index 00000000..ebb0334a --- /dev/null +++ b/wqflask/tests/wqflask/test_user_session.py @@ -0,0 +1,15 @@ +"""Test cases for some methods in user_session.py""" + +import unittest +from wqflask.user_session import verify_cookie + + +class TestUserSession(unittest.TestCase): + def test_verify_cookie(self): + """ + Test cookie verification + """ + self.assertEqual( + "3f4c1dbf-5b56-4260-87d6-f35445bda37e", + verify_cookie(("3f4c1dbf-5b56-4260-87d6-" + "f35445bda37e:af4fcf5eace9e7c864ce"))) -- cgit v1.2.3 From 2120392705c6aa652bab280e98c84b9c33bc5902 Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Wed, 28 Oct 2020 23:12:49 +0300 Subject: Add new test for hmac_creation with latin-1 secret * wqflask/tests/utility/test_hmac.py (test_hmac_creation_with_cookie): New test. For this test, use a secret that behaves differently when encoded to either utf-8 or latin-1. --- wqflask/tests/utility/test_hmac.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) (limited to 'wqflask/tests') diff --git a/wqflask/tests/utility/test_hmac.py b/wqflask/tests/utility/test_hmac.py index 7c61c0a6..4e3652f8 100644 --- a/wqflask/tests/utility/test_hmac.py +++ b/wqflask/tests/utility/test_hmac.py @@ -17,6 +17,19 @@ class TestHmacUtil(unittest.TestCase): """Test hmac creation with a utf-8 string""" self.assertEqual(hmac_creation("ファイ"), "7410466338cfe109e946") + @mock.patch("utility.hmac.app.config", + {'SECRET_HMAC_CODE': ('\x08\xdf\xfa\x93N\x80' + '\xd9\\H@\\\x9f`\x98d^' + '\xb4a;\xc6OM\x946a\xbc' + '\xfc\x80:*\xebc')}) + def test_hmac_creation_with_cookie(self): + """Test hmac creation with a cookie""" + cookie = "3f4c1dbf-5b56-4260-87d6-f35445bda37e:af4fcf5eace9e7c864ce" + uuid_, _, signature = cookie.partition(":") + self.assertEqual( + hmac_creation(uuid_), + "af4fcf5eace9e7c864ce") + @mock.patch("utility.hmac.app.config", {'SECRET_HMAC_CODE': "secret"}) def test_data_hmac(self): """Test data_hmac fn with a utf-8 string""" -- cgit v1.2.3 From f745117da48e9d46e6a07fb7f930f208c489336a Mon Sep 17 00:00:00 2001 From: Alexanderlacuna Date: Thu, 29 Oct 2020 14:58:00 +0300 Subject: add test for show_trait/export_trait_data --- .../wqflask/show_trait/test_export_trait_data.py | 49 +++++++++++++++++++++- 1 file changed, 48 insertions(+), 1 deletion(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/wqflask/show_trait/test_export_trait_data.py b/wqflask/tests/wqflask/show_trait/test_export_trait_data.py index 98d599b1..0c280315 100644 --- a/wqflask/tests/wqflask/show_trait/test_export_trait_data.py +++ b/wqflask/tests/wqflask/show_trait/test_export_trait_data.py @@ -1,10 +1,57 @@ import unittest +from unittest import mock from wqflask.show_trait.export_trait_data import dict_to_sorted_list from wqflask.show_trait.export_trait_data import cmp_samples - +from wqflask.show_trait.export_trait_data import export_sample_table class TestExportTraits(unittest.TestCase): """Test methods related to converting dict to sortedlist""" + @mock.patch("wqflask.show_trait.export_trait_data.dict_to_sorted_list") + @mock.patch("wqflask.show_trait.export_trait_data.get_export_metadata") + def test_export_sample_table(self, exp_metadata, dict_list): + """test for exporting sample table""" + targs_obj = { + "export_data": """{ + "primary_samples": [ + { + "other": "germanotta", + "name": "Sauroniops" + } + ], + "other_samples": [ + { + "se": 1, + "num_cases": 4, + "value": 6, + "name": 3 + } + ] + }""", + "trait_display_name": "Hair_color", + "trait_id": "23177fdc-312e-4084-ad0c-f3eae785fff5", + "dataset": { + } + } + exp_metadata.return_value = [["Phenotype ID:0a2be192-57f5-400b-bbbd-0cf50135995f"], ['Group:gp1'], ["Phenotype:p1"], [ + "Authors:N/A"], ["Title:research1"], ["Journal:N/A"], ["Dataset Link: http://gn1.genenetwork.org/webqtl/main.py?FormID=sharinginfo&InfoPageName=name1"], []] + expected = ('Hair_color', + [['Phenotype ID:0a2be192-57f5-400b-bbbd-0cf50135995f'], + ['Group:gp1'], + ['Phenotype:p1'], + ['Authors:N/A'], + ['Title:research1'], + ['Journal:N/A'], + ['Dataset Link: ' + 'http://gn1.genenetwork.org/webqtl/main.py?FormID=sharinginfo&InfoPageName=name1'], + [], + ['Sauroniops', 'germanotta'], + [3, 6, 1, 4]]) + + dict_list.side_effect = [['Sauroniops', 'germanotta'], [3, 6, 1, 4]] + + self.assertEqual(export_sample_table(targs_obj), expected) + exp_metadata.assert_called_with("23177fdc-312e-4084-ad0c-f3eae785fff5", {}) + self.assertEqual(dict_list.call_count, 2) def test_dict_to_sortedlist(self): """test for conversion of dict to sorted list""" -- cgit v1.2.3 From a7c4affd6b50b00ab8801b6daa96b07e88034209 Mon Sep 17 00:00:00 2001 From: Alexanderlacuna Date: Thu, 29 Oct 2020 15:02:09 +0300 Subject: format file --- wqflask/tests/wqflask/show_trait/test_export_trait_data.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/wqflask/show_trait/test_export_trait_data.py b/wqflask/tests/wqflask/show_trait/test_export_trait_data.py index 0c280315..adecbf36 100644 --- a/wqflask/tests/wqflask/show_trait/test_export_trait_data.py +++ b/wqflask/tests/wqflask/show_trait/test_export_trait_data.py @@ -4,6 +4,7 @@ from wqflask.show_trait.export_trait_data import dict_to_sorted_list from wqflask.show_trait.export_trait_data import cmp_samples from wqflask.show_trait.export_trait_data import export_sample_table + class TestExportTraits(unittest.TestCase): """Test methods related to converting dict to sortedlist""" @mock.patch("wqflask.show_trait.export_trait_data.dict_to_sorted_list") @@ -50,7 +51,8 @@ class TestExportTraits(unittest.TestCase): dict_list.side_effect = [['Sauroniops', 'germanotta'], [3, 6, 1, 4]] self.assertEqual(export_sample_table(targs_obj), expected) - exp_metadata.assert_called_with("23177fdc-312e-4084-ad0c-f3eae785fff5", {}) + exp_metadata.assert_called_with( + "23177fdc-312e-4084-ad0c-f3eae785fff5", {}) self.assertEqual(dict_list.call_count, 2) def test_dict_to_sortedlist(self): -- cgit v1.2.3 From 242c334dbaa84c93a0c45bc80a050cd0e240d81b Mon Sep 17 00:00:00 2001 From: Alexanderlacuna Date: Thu, 29 Oct 2020 17:23:46 +0300 Subject: add test for show_trait --- .../wqflask/show_trait/test_export_trait_data.py | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/wqflask/show_trait/test_export_trait_data.py b/wqflask/tests/wqflask/show_trait/test_export_trait_data.py index adecbf36..488c9d63 100644 --- a/wqflask/tests/wqflask/show_trait/test_export_trait_data.py +++ b/wqflask/tests/wqflask/show_trait/test_export_trait_data.py @@ -16,7 +16,14 @@ class TestExportTraits(unittest.TestCase): "primary_samples": [ { "other": "germanotta", - "name": "Sauroniops" + "name": "Sauroniops", + "se":{ + "name":"S2" + }, + "num_cases":{ + "k1":"value" + + } } ], "other_samples": [ @@ -33,8 +40,13 @@ class TestExportTraits(unittest.TestCase): "dataset": { } } - exp_metadata.return_value = [["Phenotype ID:0a2be192-57f5-400b-bbbd-0cf50135995f"], ['Group:gp1'], ["Phenotype:p1"], [ - "Authors:N/A"], ["Title:research1"], ["Journal:N/A"], ["Dataset Link: http://gn1.genenetwork.org/webqtl/main.py?FormID=sharinginfo&InfoPageName=name1"], []] + exp_metadata.return_value = [ + ["Phenotype ID:0a2be192-57f5-400b-bbbd-0cf50135995f"], ['Group:gp1'], + ["Phenotype:p1"], [ + "Authors:N/A"], + ["Title:research1"], + ["Journal:N/A"], + ["Dataset Link: http://gn1.genenetwork.org/webqtl/main.py?FormID=sharinginfo&InfoPageName=name1"], []] expected = ('Hair_color', [['Phenotype ID:0a2be192-57f5-400b-bbbd-0cf50135995f'], ['Group:gp1'], @@ -45,6 +57,7 @@ class TestExportTraits(unittest.TestCase): ['Dataset Link: ' 'http://gn1.genenetwork.org/webqtl/main.py?FormID=sharinginfo&InfoPageName=name1'], [], + ['Name', 'Value', 'SE', 'N'], ['Sauroniops', 'germanotta'], [3, 6, 1, 4]]) -- cgit v1.2.3 From fb9ff600a3cb420303632c8c8d690999a09846d0 Mon Sep 17 00:00:00 2001 From: Alexanderlacuna Date: Fri, 30 Oct 2020 12:38:30 +0300 Subject: add test for get_export_metadata --- .../wqflask/show_trait/test_export_trait_data.py | 62 ++++++++++++++++++++++ 1 file changed, 62 insertions(+) (limited to 'wqflask/tests') diff --git a/wqflask/tests/wqflask/show_trait/test_export_trait_data.py b/wqflask/tests/wqflask/show_trait/test_export_trait_data.py index 488c9d63..5d0655ce 100644 --- a/wqflask/tests/wqflask/show_trait/test_export_trait_data.py +++ b/wqflask/tests/wqflask/show_trait/test_export_trait_data.py @@ -3,10 +3,72 @@ from unittest import mock from wqflask.show_trait.export_trait_data import dict_to_sorted_list from wqflask.show_trait.export_trait_data import cmp_samples from wqflask.show_trait.export_trait_data import export_sample_table +from wqflask.show_trait.export_trait_data import get_export_metadata + + +class MockGeneral(object): + def __init__(self, obj): + for key, value in obj.items(): + setattr(self, key, value) + + +class MockChild(object): + pass class TestExportTraits(unittest.TestCase): """Test methods related to converting dict to sortedlist""" + @mock.patch("wqflask.show_trait.export_trait_data.create_trait") + @mock.patch("wqflask.show_trait.export_trait_data.data_set") + def test_get_export_metadata_no_publish(self, mock_dataset, mock_trait): + """test for exporting metadata with no publish""" + mock_data_instance = MockGeneral( + {"type": "no_publish", "dataset_name": "Temp", "name": "Temp"}) + + group_obj = MockChild() + group_obj.name = "name" + mock_data_instance.group = group_obj + mock_dataset.create_dataset.return_value = mock_data_instance + mock_trait.return_value = MockGeneral({"symbol": "", "description_display": "Description", + "title": "research1", "journal": "", "authors": ""}) + + results = get_export_metadata("random_id", "Temp") + expected = [["Record ID: random_id"], + ["Trait URL: http://genenetwork.org/show_trait?trait_id=random_id&dataset=Temp"], + ["Dataset: Temp"], + ["Group: name"], []] + + mock_dataset.create_dataset.assert_called_with("Temp") + mock_trait.assert_called_with( + dataset=mock_data_instance, name="random_id", cellid=None, get_qtl_info=False) + self.assertEqual(results, expected) + + @mock.patch("wqflask.show_trait.export_trait_data.create_trait") + @mock.patch("wqflask.show_trait.export_trait_data.data_set") + def test_get_export_metadata_with_publish(self, data_mock, trait_mock): + """test for exporting metadata with dataset.type=Publish""" + mock_instance = MockGeneral({"type": "Publish", "dataset_name": "Temp", + "name": "Temp", "description_display": "Description goes here"}) + + group_obj = MockChild() + group_obj.name = "name" + mock_instance.group = group_obj + data_mock.create_dataset.return_value = mock_instance + trait_instance = MockGeneral({"symbol": "", "description_display": "Description", + "title": "research1", "journal": "", "authors": ""}) + trait_mock.return_value = trait_instance + + results = get_export_metadata( + "29ae0615-0d77-4814-97c7-c9e91f6bfd7b", "Temp") + + expected = [['Phenotype ID: 29ae0615-0d77-4814-97c7-c9e91f6bfd7b'], + ['Phenotype URL: http://genenetwork.org/show_trait?trait_id=29ae0615-0d77-4814-97c7-c9e91f6bfd7b&dataset=Temp'], [ + 'Group: name'], ['Phenotype: Description'], + ['Authors: N/A'], ['Title: research1'], + ['Journal: N/A'], ['Dataset Link: http://gn1.genenetwork.org/webqtl/main.py?FormID=sharinginfo&InfoPageName=Temp'], []] + + self.assertEqual(results, expected) + @mock.patch("wqflask.show_trait.export_trait_data.dict_to_sorted_list") @mock.patch("wqflask.show_trait.export_trait_data.get_export_metadata") def test_export_sample_table(self, exp_metadata, dict_list): -- cgit v1.2.3 From 7ba5eb8afcb251d271d24c4f8314cafd82d546bb Mon Sep 17 00:00:00 2001 From: Alexanderlacuna Date: Sat, 31 Oct 2020 15:06:04 +0300 Subject: Use more descriptive variable and class names --- .../wqflask/show_trait/test_export_trait_data.py | 38 +++++++++++----------- 1 file changed, 19 insertions(+), 19 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/wqflask/show_trait/test_export_trait_data.py b/wqflask/tests/wqflask/show_trait/test_export_trait_data.py index 5d0655ce..085c6a30 100644 --- a/wqflask/tests/wqflask/show_trait/test_export_trait_data.py +++ b/wqflask/tests/wqflask/show_trait/test_export_trait_data.py @@ -6,13 +6,13 @@ from wqflask.show_trait.export_trait_data import export_sample_table from wqflask.show_trait.export_trait_data import get_export_metadata -class MockGeneral(object): +class AttributesSetterClass: def __init__(self, obj): for key, value in obj.items(): setattr(self, key, value) -class MockChild(object): +class HelperClass: pass @@ -22,15 +22,15 @@ class TestExportTraits(unittest.TestCase): @mock.patch("wqflask.show_trait.export_trait_data.data_set") def test_get_export_metadata_no_publish(self, mock_dataset, mock_trait): """test for exporting metadata with no publish""" - mock_data_instance = MockGeneral( + mock_dataset_attributes = AttributesSetterClass( {"type": "no_publish", "dataset_name": "Temp", "name": "Temp"}) - group_obj = MockChild() - group_obj.name = "name" - mock_data_instance.group = group_obj - mock_dataset.create_dataset.return_value = mock_data_instance - mock_trait.return_value = MockGeneral({"symbol": "", "description_display": "Description", - "title": "research1", "journal": "", "authors": ""}) + mock_nested_attributes = HelperClass() + mock_nested_attributes.name = "name" + mock_dataset_attributes.group = mock_nested_attributes + mock_dataset.create_dataset.return_value = mock_dataset_attributes + mock_trait.return_value = AttributesSetterClass({"symbol": "", "description_display": "Description", + "title": "research1", "journal": "", "authors": ""}) results = get_export_metadata("random_id", "Temp") expected = [["Record ID: random_id"], @@ -40,22 +40,22 @@ class TestExportTraits(unittest.TestCase): mock_dataset.create_dataset.assert_called_with("Temp") mock_trait.assert_called_with( - dataset=mock_data_instance, name="random_id", cellid=None, get_qtl_info=False) + dataset=mock_dataset_attributes, name="random_id", cellid=None, get_qtl_info=False) self.assertEqual(results, expected) @mock.patch("wqflask.show_trait.export_trait_data.create_trait") @mock.patch("wqflask.show_trait.export_trait_data.data_set") def test_get_export_metadata_with_publish(self, data_mock, trait_mock): """test for exporting metadata with dataset.type=Publish""" - mock_instance = MockGeneral({"type": "Publish", "dataset_name": "Temp", - "name": "Temp", "description_display": "Description goes here"}) - - group_obj = MockChild() - group_obj.name = "name" - mock_instance.group = group_obj - data_mock.create_dataset.return_value = mock_instance - trait_instance = MockGeneral({"symbol": "", "description_display": "Description", - "title": "research1", "journal": "", "authors": ""}) + mock_dataset_attributes = AttributesSetterClass({"type": "Publish", "dataset_name": "Temp", + "name": "Temp", "description_display": "Description goes here"}) + + mock_nested_attributes = HelperClass() + mock_nested_attributes.name = "name" + mock_dataset_attributes.group = mock_nested_attributes + data_mock.create_dataset.return_value = mock_dataset_attributes + trait_instance = AttributesSetterClass({"symbol": "", "description_display": "Description", + "title": "research1", "journal": "", "authors": ""}) trait_mock.return_value = trait_instance results = get_export_metadata( -- cgit v1.2.3 From 544f24cb020136532689e3649be1902413f570c8 Mon Sep 17 00:00:00 2001 From: Alexanderlacuna Date: Sat, 31 Oct 2020 15:17:12 +0300 Subject: use descriptive variable names --- wqflask/tests/wqflask/show_trait/test_export_trait_data.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/wqflask/show_trait/test_export_trait_data.py b/wqflask/tests/wqflask/show_trait/test_export_trait_data.py index 085c6a30..bd2f7dac 100644 --- a/wqflask/tests/wqflask/show_trait/test_export_trait_data.py +++ b/wqflask/tests/wqflask/show_trait/test_export_trait_data.py @@ -6,7 +6,7 @@ from wqflask.show_trait.export_trait_data import export_sample_table from wqflask.show_trait.export_trait_data import get_export_metadata -class AttributesSetterClass: +class AttributesSetter: def __init__(self, obj): for key, value in obj.items(): setattr(self, key, value) @@ -22,14 +22,14 @@ class TestExportTraits(unittest.TestCase): @mock.patch("wqflask.show_trait.export_trait_data.data_set") def test_get_export_metadata_no_publish(self, mock_dataset, mock_trait): """test for exporting metadata with no publish""" - mock_dataset_attributes = AttributesSetterClass( + mock_dataset_attributes = AttributesSetter( {"type": "no_publish", "dataset_name": "Temp", "name": "Temp"}) mock_nested_attributes = HelperClass() mock_nested_attributes.name = "name" mock_dataset_attributes.group = mock_nested_attributes mock_dataset.create_dataset.return_value = mock_dataset_attributes - mock_trait.return_value = AttributesSetterClass({"symbol": "", "description_display": "Description", + mock_trait.return_value = AttributesSetter({"symbol": "", "description_display": "Description", "title": "research1", "journal": "", "authors": ""}) results = get_export_metadata("random_id", "Temp") @@ -47,14 +47,14 @@ class TestExportTraits(unittest.TestCase): @mock.patch("wqflask.show_trait.export_trait_data.data_set") def test_get_export_metadata_with_publish(self, data_mock, trait_mock): """test for exporting metadata with dataset.type=Publish""" - mock_dataset_attributes = AttributesSetterClass({"type": "Publish", "dataset_name": "Temp", - "name": "Temp", "description_display": "Description goes here"}) + mock_dataset_attributes = AttributesSetter({"type": "Publish", "dataset_name": "Temp", + "name": "Temp", "description_display": "Description goes here"}) mock_nested_attributes = HelperClass() mock_nested_attributes.name = "name" mock_dataset_attributes.group = mock_nested_attributes data_mock.create_dataset.return_value = mock_dataset_attributes - trait_instance = AttributesSetterClass({"symbol": "", "description_display": "Description", + trait_instance = AttributesSetter({"symbol": "", "description_display": "Description", "title": "research1", "journal": "", "authors": ""}) trait_mock.return_value = trait_instance -- cgit v1.2.3 From 0b962eef391db6aae100a3283e89ee0ac0101f6b Mon Sep 17 00:00:00 2001 From: Alexanderlacuna Date: Sat, 31 Oct 2020 15:23:45 +0300 Subject: remove redundant classes --- .../tests/wqflask/show_trait/test_export_trait_data.py | 16 +++++----------- 1 file changed, 5 insertions(+), 11 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/wqflask/show_trait/test_export_trait_data.py b/wqflask/tests/wqflask/show_trait/test_export_trait_data.py index bd2f7dac..41761944 100644 --- a/wqflask/tests/wqflask/show_trait/test_export_trait_data.py +++ b/wqflask/tests/wqflask/show_trait/test_export_trait_data.py @@ -12,10 +12,6 @@ class AttributesSetter: setattr(self, key, value) -class HelperClass: - pass - - class TestExportTraits(unittest.TestCase): """Test methods related to converting dict to sortedlist""" @mock.patch("wqflask.show_trait.export_trait_data.create_trait") @@ -25,12 +21,11 @@ class TestExportTraits(unittest.TestCase): mock_dataset_attributes = AttributesSetter( {"type": "no_publish", "dataset_name": "Temp", "name": "Temp"}) - mock_nested_attributes = HelperClass() - mock_nested_attributes.name = "name" + mock_nested_attributes = AttributesSetter({"name": "name"}) mock_dataset_attributes.group = mock_nested_attributes mock_dataset.create_dataset.return_value = mock_dataset_attributes mock_trait.return_value = AttributesSetter({"symbol": "", "description_display": "Description", - "title": "research1", "journal": "", "authors": ""}) + "title": "research1", "journal": "", "authors": ""}) results = get_export_metadata("random_id", "Temp") expected = [["Record ID: random_id"], @@ -48,14 +43,13 @@ class TestExportTraits(unittest.TestCase): def test_get_export_metadata_with_publish(self, data_mock, trait_mock): """test for exporting metadata with dataset.type=Publish""" mock_dataset_attributes = AttributesSetter({"type": "Publish", "dataset_name": "Temp", - "name": "Temp", "description_display": "Description goes here"}) + "name": "Temp", "description_display": "Description goes here"}) - mock_nested_attributes = HelperClass() - mock_nested_attributes.name = "name" + mock_nested_attributes = AttributesSetter({"name": "name"}) mock_dataset_attributes.group = mock_nested_attributes data_mock.create_dataset.return_value = mock_dataset_attributes trait_instance = AttributesSetter({"symbol": "", "description_display": "Description", - "title": "research1", "journal": "", "authors": ""}) + "title": "research1", "journal": "", "authors": ""}) trait_mock.return_value = trait_instance results = get_export_metadata( -- cgit v1.2.3 From 6d2d648126b112ca1455c6e1f2d344a4d8d27c1d Mon Sep 17 00:00:00 2001 From: Alexanderlacuna Date: Mon, 2 Nov 2020 11:06:36 +0300 Subject: add tests for show trait module --- .../tests/wqflask/show_trait/test_show_trait.py | 267 +++++++++++++++++++++ 1 file changed, 267 insertions(+) create mode 100644 wqflask/tests/wqflask/show_trait/test_show_trait.py (limited to 'wqflask/tests') diff --git a/wqflask/tests/wqflask/show_trait/test_show_trait.py b/wqflask/tests/wqflask/show_trait/test_show_trait.py new file mode 100644 index 00000000..37eae06e --- /dev/null +++ b/wqflask/tests/wqflask/show_trait/test_show_trait.py @@ -0,0 +1,267 @@ +"""test for wqflask/show_trait/test_show_trait.py""" + + +import unittest +from unittest import mock +from wqflask import app +from wqflask.show_trait.show_trait import check_if_attr_exists +from wqflask.show_trait.show_trait import requests + +from wqflask.show_trait.show_trait import get_ncbi_summary + +from wqflask.show_trait.show_trait import has_num_cases + +from wqflask.show_trait.show_trait import get_table_widths + +from wqflask.show_trait.show_trait import get_categorical_variables +from wqflask.show_trait.show_trait import get_trait_units + +from wqflask.show_trait.show_trait import get_nearest_marker + +from wqflask.show_trait.show_trait import get_genotype_scales + +class TraitObject: + def __init__(self, obj): + for key, value in obj.items(): + setattr(self, key, value) + + +class TestTraits(unittest.TestCase): + def setUp(self): + self.app_context = app.app_context() + self.app_context.push() + + def tearDown(self): + self.app_context.pop() + + def test_check_if_attr_exists_truthy(self): + """"test if attributes exists with true return""" + trait_obj = TraitObject({"id_type": "id"}) + trait_obj2 = TraitObject({"sample_name": ['samp1']}) + results = check_if_attr_exists(trait_obj, "id_type") + result2 = check_if_attr_exists(trait_obj2, "sample_name") + self.assertIsInstance(trait_obj, TraitObject) + self.assertEqual(results, True) + self.assertEqual(result2, True) + + def test_check_if_attr_exists_empty_attr(self): + """test if attributes exists with empty attributes""" + trait_obj = TraitObject({"sample": ""}) + trait_obj2 = TraitObject({"group": None}) + result = check_if_attr_exists(trait_obj, "sample") + result2 = check_if_attr_exists(trait_obj, "group") + self.assertEqual(result, False) + self.assertEqual(result2, False) + + def test_check_if_attr_exists_falsey(self): + """check if attribute exists with empty attributes""" + trait_obj = TraitObject({}) + results = check_if_attr_exists(trait_obj, "any") + self.assertEqual(results, False) + + @mock.patch("wqflask.show_trait.show_trait.requests.get") + @mock.patch("wqflask.show_trait.show_trait.check_if_attr_exists") + def test_get_ncbi_summary_request_success(self, mock_exists, mock_get): + """test for getting ncbi summary with + successful request""" + trait = TraitObject({"geneid": "id"}) + mock_exists.return_value = True + content_json_string = """{ + "result":{ + "id":{ + "summary":"this is a summary of the geneid" + } + } + } + """ + + get_return_obj = TraitObject({"content": content_json_string}) + + mock_get.return_value = get_return_obj + + results = get_ncbi_summary(trait) + mock_exists.assert_called_once() + mock_get.assert_called_once_with(f"http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=gene&id={trait.geneid}&retmode=json") + + self.assertEqual(results, "this is a summary of the geneid") + + @mock.patch("wqflask.show_trait.show_trait.requests.get") + @mock.patch("wqflask.show_trait.show_trait.check_if_attr_exists") + def test_get_ncbi_summary_request_fail(self, mock_exists, mock_get_fail): + """test for getting ncbi summary with request fail""" + trait = TraitObject({"geneid": "id"}) + mock_exists.return_value = True + mock_get_fail.side_effect = Exception("an error occurred") + content_json_string = """{ + "result":{ + "id":{ + "summary":"this is a summary of the geneid" + } + } + } + """ + + results = get_ncbi_summary(trait) + self.assertEqual(results, None) + + def test_hash_num_cases_is_probeset(self): + """test for hash num_cases with dataset.type set to Probeset""" + create_dataset = TraitObject({"type": "ProbeSet"}) + create_trait = TraitObject({"dataset": create_dataset}) + + self.assertEqual(has_num_cases(create_trait), False) + + def test_hash_num_cases_no_probeset(self): + """test for hash num cases with dataset.type not Probeset""" + create_dataset = TraitObject({"type": "Temp"}) + + construct_data = { + "nm1": TraitObject({"num_cases": False}), + "nm2": TraitObject({"num_cases": True}), + "nm3": TraitObject({"num_cases": False}) + } + construct_data2 = { + "nm1": TraitObject({"num_cases": False}), + "nm2": TraitObject({"num_cases": False}), + "nm3": TraitObject({"num_cases": False}) + + + } + + create_trait = TraitObject( + {"dataset": create_dataset, "data": construct_data}) + create_trait2 = TraitObject( + {"dataset": create_dataset, "data": construct_data2}) + + results = has_num_cases(create_trait) + + self.assertEqual(has_num_cases(create_trait), True) + self.assertEqual(has_num_cases(create_trait2), False) + + def test_get_table_widths(self): + """test for getting table widths""" + sample_groups = [TraitObject({'se_exists': True, "attributes": ["attr1", "attr2", "attr3"]} + ), TraitObject( + {"se_exists": False, "attributes": ["at1", "at2"] + })] + + results_with_numcase = get_table_widths(sample_groups, True) + result_no_numcase = get_table_widths(sample_groups, False) + + results_one_sample = get_table_widths( + [TraitObject({"se_exists": True, "attributes": []})], True) + expected_with_numcase = (450, "750px") + expected_no_numcase = (450, "670px") + expected_one_sample = (250, "540px") + + self.assertEqual(results_with_numcase, expected_with_numcase) + self.assertEqual(result_no_numcase, expected_no_numcase) + self.assertEqual(results_one_sample, + expected_one_sample) + + def test_get_categorical_variables_no_sample_attributes(self): + """test for getting categorical variable names with no samples""" + trait = TraitObject({}) + sample_list = TraitObject({"se_exists": True, "attributes": []}) + + self.assertEqual(get_categorical_variables(trait, sample_list), []) + + def test_get_categorical_variables_with_sample_attributes(self): + pass + + def test_get_trait_units(self): + """test for gettting trait units""" + trait = TraitObject( + {"description_fmt": "[this is a description] another test [N/A]"}) + + trait_no_unit_type = TraitObject({"description_fmt": ""}) + + results = get_trait_units(trait) + results_no_unit = get_trait_units(trait_no_unit_type) + self.assertEqual(results, "this is a descriptionN/A") + self.assertEqual(results_no_unit, "Value") + + @mock.patch("wqflask.show_trait.show_trait.g") + def test_get_nearest_marker(self, mock_db): + """test for getting nearest marker with non-empty db""" + + mock_db.db.execute.return_value.fetchall.return_value = [ + ["Geno1", "Geno2"], ["Geno3"]] + + trait = TraitObject({"locus_chr": "test_chr", "locus_mb": "test_mb"}) + + group_name = TraitObject({"name": "group_name"}) + + this_db = TraitObject({"group": group_name}) + + results_with_item_db = get_nearest_marker(trait, this_db) + + called_with_value = """SELECT Geno.Name + FROM Geno, GenoXRef, GenoFreeze + WHERE Geno.Chr = 'test_chr' AND + GenoXRef.GenoId = Geno.Id AND + GenoFreeze.Id = GenoXRef.GenoFreezeId AND + GenoFreeze.Name = 'group_nameGeno' + ORDER BY ABS( Geno.Mb - test_mb) LIMIT 1""" + + mock_db.db.execute.assert_called_with(called_with_value) + + self.assertEqual(results_with_item_db, "Geno1") + + @mock.patch("wqflask.show_trait.show_trait.g") + def test_get_nearest_marker_empty_db(self, mock_db): + """test for getting nearest marker with empty db""" + mock_db.db.execute.return_value.fetchall.return_value = [] + + trait = TraitObject({"locus_chr": "test_chr", "locus_mb": "test_mb"}) + group_name = TraitObject({"name": "group_name"}) + this_db = TraitObject({"group": group_name}) + + results_empty_db = get_nearest_marker(trait, this_db) + mock_db.db.execute.assert_called_once() + self.assertEqual(results_empty_db, "") + + + @mock.patch("wqflask.show_trait.show_trait.get_scales_from_genofile") + def test_get_genotype_scales_with_genofile_is_list(self,mock_get_scales): + """test for getting genotype scales with genofile as list """ + #where genofile is instance of list + genofiles_list = [{"filename":"file1","location":"~/data/files/f1"},{"filename":"file2","location":"~/data/files/f2"},{"filename":"file3","location":"~/data/files/f3"}] + + mock_get_scales.side_effect = [[["morgan", "cM"]],[["morgan", "cM"]],[["physic", "Mb"]]] + + results = get_genotype_scales(genofiles_list) + + expected_results = { + "~/data/files/f1":[["morgan","cM"]], + "~/data/files/f2":[["morgan","cM"]], + "~/data/files/f3":[["physic","Mb"]] + } + + multiple_calls = [mock.call('~/data/files/f1'),mock.call('~/data/files/f2'), + mock.call('~/data/files/f3')] + + + mock_get_scales.assert_has_calls(multiple_calls) + self.assertEqual(results,expected_results) + + + @mock.patch("wqflask.show_trait.show_trait.get_scales_from_genofile") + def test_genotype_scales_with_genofile_other(self,mock_get_scales): + """test for getting genotype scales with genofile as a strig""" + file_location = "~/another_file_location" + mock_get_scales.return_value = [["physic","Mb"]] + + expected_results = {f"{file_location}":[["physic","Mb"]]} + + + self.assertEqual(get_genotype_scales(file_location),expected_results) + mock_get_scales.assert_called_once_with(file_location) + + + + + + + + -- cgit v1.2.3 From 62996d6b521379576992172fdee99468cb0260c9 Mon Sep 17 00:00:00 2001 From: Alexanderlacuna Date: Mon, 2 Nov 2020 13:35:59 +0300 Subject: add function docstring --- wqflask/tests/wqflask/show_trait/test_show_trait.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/wqflask/show_trait/test_show_trait.py b/wqflask/tests/wqflask/show_trait/test_show_trait.py index 37eae06e..1b5d2265 100644 --- a/wqflask/tests/wqflask/show_trait/test_show_trait.py +++ b/wqflask/tests/wqflask/show_trait/test_show_trait.py @@ -45,7 +45,7 @@ class TestTraits(unittest.TestCase): self.assertEqual(result2, True) def test_check_if_attr_exists_empty_attr(self): - """test if attributes exists with empty attributes""" + """test if attributes exists with false return""" trait_obj = TraitObject({"sample": ""}) trait_obj2 = TraitObject({"group": None}) result = check_if_attr_exists(trait_obj, "sample") @@ -248,7 +248,7 @@ class TestTraits(unittest.TestCase): @mock.patch("wqflask.show_trait.show_trait.get_scales_from_genofile") def test_genotype_scales_with_genofile_other(self,mock_get_scales): - """test for getting genotype scales with genofile as a strig""" + """test for getting genotype scales with genofile as a string""" file_location = "~/another_file_location" mock_get_scales.return_value = [["physic","Mb"]] -- cgit v1.2.3 From 2883f17236081bc11faf4c4202393998bde0924d Mon Sep 17 00:00:00 2001 From: Alexanderlacuna Date: Mon, 2 Nov 2020 13:50:25 +0300 Subject: add better formatting --- .../tests/wqflask/show_trait/test_show_trait.py | 47 +++++++++------------- 1 file changed, 20 insertions(+), 27 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/wqflask/show_trait/test_show_trait.py b/wqflask/tests/wqflask/show_trait/test_show_trait.py index 1b5d2265..408797b9 100644 --- a/wqflask/tests/wqflask/show_trait/test_show_trait.py +++ b/wqflask/tests/wqflask/show_trait/test_show_trait.py @@ -20,6 +20,7 @@ from wqflask.show_trait.show_trait import get_nearest_marker from wqflask.show_trait.show_trait import get_genotype_scales + class TraitObject: def __init__(self, obj): for key, value in obj.items(): @@ -141,7 +142,7 @@ class TestTraits(unittest.TestCase): def test_get_table_widths(self): """test for getting table widths""" sample_groups = [TraitObject({'se_exists': True, "attributes": ["attr1", "attr2", "attr3"]} - ), TraitObject( + ), TraitObject( {"se_exists": False, "attributes": ["at1", "at2"] })] @@ -221,47 +222,39 @@ class TestTraits(unittest.TestCase): mock_db.db.execute.assert_called_once() self.assertEqual(results_empty_db, "") - @mock.patch("wqflask.show_trait.show_trait.get_scales_from_genofile") - def test_get_genotype_scales_with_genofile_is_list(self,mock_get_scales): + def test_get_genotype_scales_with_genofile_is_list(self, mock_get_scales): """test for getting genotype scales with genofile as list """ - #where genofile is instance of list - genofiles_list = [{"filename":"file1","location":"~/data/files/f1"},{"filename":"file2","location":"~/data/files/f2"},{"filename":"file3","location":"~/data/files/f3"}] + # where genofile is instance of list + genofiles_list = [{"filename": "file1", "location": "~/data/files/f1"}, + {"filename": "file2", "location": "~/data/files/f2"}, + {"filename": "file3", "location": "~/data/files/f3"}] - mock_get_scales.side_effect = [[["morgan", "cM"]],[["morgan", "cM"]],[["physic", "Mb"]]] + mock_get_scales.side_effect = [[["morgan", "cM"]], + [["morgan", "cM"]], + [["physic", "Mb"]]] results = get_genotype_scales(genofiles_list) expected_results = { - "~/data/files/f1":[["morgan","cM"]], - "~/data/files/f2":[["morgan","cM"]], - "~/data/files/f3":[["physic","Mb"]] + "~/data/files/f1": [["morgan", "cM"]], + "~/data/files/f2": [["morgan", "cM"]], + "~/data/files/f3": [["physic", "Mb"]] } - multiple_calls = [mock.call('~/data/files/f1'),mock.call('~/data/files/f2'), - mock.call('~/data/files/f3')] - + multiple_calls = [mock.call('~/data/files/f1'), mock.call('~/data/files/f2'), + mock.call('~/data/files/f3')] mock_get_scales.assert_has_calls(multiple_calls) - self.assertEqual(results,expected_results) - + self.assertEqual(results, expected_results) @mock.patch("wqflask.show_trait.show_trait.get_scales_from_genofile") - def test_genotype_scales_with_genofile_other(self,mock_get_scales): + def test_genotype_scales_with_genofile_other(self, mock_get_scales): """test for getting genotype scales with genofile as a string""" file_location = "~/another_file_location" - mock_get_scales.return_value = [["physic","Mb"]] + mock_get_scales.return_value = [["physic", "Mb"]] - expected_results = {f"{file_location}":[["physic","Mb"]]} + expected_results = {f"{file_location}": [["physic", "Mb"]]} - - self.assertEqual(get_genotype_scales(file_location),expected_results) + self.assertEqual(get_genotype_scales(file_location), expected_results) mock_get_scales.assert_called_once_with(file_location) - - - - - - - - -- cgit v1.2.3 From 251113ee34819afdc3e2abc63d59a01bd6a560cb Mon Sep 17 00:00:00 2001 From: Alexanderlacuna Date: Tue, 3 Nov 2020 10:32:36 +0300 Subject: use assertTrue and assertFalse in while testing boolean --- .../tests/wqflask/show_trait/test_show_trait.py | 38 ++++++++-------------- 1 file changed, 13 insertions(+), 25 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/wqflask/show_trait/test_show_trait.py b/wqflask/tests/wqflask/show_trait/test_show_trait.py index 408797b9..a2ef71dd 100644 --- a/wqflask/tests/wqflask/show_trait/test_show_trait.py +++ b/wqflask/tests/wqflask/show_trait/test_show_trait.py @@ -1,24 +1,12 @@ """test for wqflask/show_trait/test_show_trait.py""" - import unittest from unittest import mock from wqflask import app -from wqflask.show_trait.show_trait import check_if_attr_exists -from wqflask.show_trait.show_trait import requests - -from wqflask.show_trait.show_trait import get_ncbi_summary - -from wqflask.show_trait.show_trait import has_num_cases - -from wqflask.show_trait.show_trait import get_table_widths - -from wqflask.show_trait.show_trait import get_categorical_variables -from wqflask.show_trait.show_trait import get_trait_units - -from wqflask.show_trait.show_trait import get_nearest_marker - -from wqflask.show_trait.show_trait import get_genotype_scales +from wqflask.show_trait.show_trait import (check_if_attr_exists, get_ncbi_summary, + has_num_cases, get_table_widths, + get_categorical_variables, + get_trait_units, get_nearest_marker, get_genotype_scales, requests) class TraitObject: @@ -42,8 +30,8 @@ class TestTraits(unittest.TestCase): results = check_if_attr_exists(trait_obj, "id_type") result2 = check_if_attr_exists(trait_obj2, "sample_name") self.assertIsInstance(trait_obj, TraitObject) - self.assertEqual(results, True) - self.assertEqual(result2, True) + self.assertTrue(results, True) + self.assertTrue(result2, True) def test_check_if_attr_exists_empty_attr(self): """test if attributes exists with false return""" @@ -51,14 +39,14 @@ class TestTraits(unittest.TestCase): trait_obj2 = TraitObject({"group": None}) result = check_if_attr_exists(trait_obj, "sample") result2 = check_if_attr_exists(trait_obj, "group") - self.assertEqual(result, False) - self.assertEqual(result2, False) + self.assertFalse(result, False) + self.assertFalse(result2, False) def test_check_if_attr_exists_falsey(self): """check if attribute exists with empty attributes""" trait_obj = TraitObject({}) results = check_if_attr_exists(trait_obj, "any") - self.assertEqual(results, False) + self.assertFalse(results, False) @mock.patch("wqflask.show_trait.show_trait.requests.get") @mock.patch("wqflask.show_trait.show_trait.check_if_attr_exists") @@ -110,7 +98,7 @@ class TestTraits(unittest.TestCase): create_dataset = TraitObject({"type": "ProbeSet"}) create_trait = TraitObject({"dataset": create_dataset}) - self.assertEqual(has_num_cases(create_trait), False) + self.assertFalse(has_num_cases(create_trait), False) def test_hash_num_cases_no_probeset(self): """test for hash num cases with dataset.type not Probeset""" @@ -136,8 +124,8 @@ class TestTraits(unittest.TestCase): results = has_num_cases(create_trait) - self.assertEqual(has_num_cases(create_trait), True) - self.assertEqual(has_num_cases(create_trait2), False) + self.assertTrue(has_num_cases(create_trait), True) + self.assertFalse(has_num_cases(create_trait2), False) def test_get_table_widths(self): """test for getting table widths""" @@ -171,7 +159,7 @@ class TestTraits(unittest.TestCase): pass def test_get_trait_units(self): - """test for gettting trait units""" + """test for getting trait units""" trait = TraitObject( {"description_fmt": "[this is a description] another test [N/A]"}) -- cgit v1.2.3 From ef0c9bb30523b32decc163dcb62c125e7ba5a076 Mon Sep 17 00:00:00 2001 From: Alexanderlacuna Date: Tue, 3 Nov 2020 16:50:23 +0300 Subject: switch from assertTrue/False to assertIs to make the tests tighter --- wqflask/tests/wqflask/show_trait/test_show_trait.py | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/wqflask/show_trait/test_show_trait.py b/wqflask/tests/wqflask/show_trait/test_show_trait.py index a2ef71dd..f666912b 100644 --- a/wqflask/tests/wqflask/show_trait/test_show_trait.py +++ b/wqflask/tests/wqflask/show_trait/test_show_trait.py @@ -1,5 +1,4 @@ """test for wqflask/show_trait/test_show_trait.py""" - import unittest from unittest import mock from wqflask import app @@ -30,8 +29,9 @@ class TestTraits(unittest.TestCase): results = check_if_attr_exists(trait_obj, "id_type") result2 = check_if_attr_exists(trait_obj2, "sample_name") self.assertIsInstance(trait_obj, TraitObject) - self.assertTrue(results, True) - self.assertTrue(result2, True) + self.assertIs(results, True) + self.assertIs(result2, True) + def test_check_if_attr_exists_empty_attr(self): """test if attributes exists with false return""" @@ -39,14 +39,14 @@ class TestTraits(unittest.TestCase): trait_obj2 = TraitObject({"group": None}) result = check_if_attr_exists(trait_obj, "sample") result2 = check_if_attr_exists(trait_obj, "group") - self.assertFalse(result, False) - self.assertFalse(result2, False) + self.assertIs(result, False) + self.assertIs(result2, False) def test_check_if_attr_exists_falsey(self): """check if attribute exists with empty attributes""" trait_obj = TraitObject({}) results = check_if_attr_exists(trait_obj, "any") - self.assertFalse(results, False) + self.assertIs(results, False) @mock.patch("wqflask.show_trait.show_trait.requests.get") @mock.patch("wqflask.show_trait.show_trait.check_if_attr_exists") @@ -124,8 +124,8 @@ class TestTraits(unittest.TestCase): results = has_num_cases(create_trait) - self.assertTrue(has_num_cases(create_trait), True) - self.assertFalse(has_num_cases(create_trait2), False) + self.assertIs(has_num_cases(create_trait), True) + self.assertIs(has_num_cases(create_trait2), False) def test_get_table_widths(self): """test for getting table widths""" -- cgit v1.2.3 From 7da9a5206800d305f97b025e180300ca451ac92d Mon Sep 17 00:00:00 2001 From: Alexanderlacuna Date: Tue, 3 Nov 2020 17:08:05 +0300 Subject: switch from assertFalse to assertIs --- wqflask/tests/wqflask/show_trait/test_show_trait.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/wqflask/show_trait/test_show_trait.py b/wqflask/tests/wqflask/show_trait/test_show_trait.py index f666912b..ec45d558 100644 --- a/wqflask/tests/wqflask/show_trait/test_show_trait.py +++ b/wqflask/tests/wqflask/show_trait/test_show_trait.py @@ -31,7 +31,6 @@ class TestTraits(unittest.TestCase): self.assertIsInstance(trait_obj, TraitObject) self.assertIs(results, True) self.assertIs(result2, True) - def test_check_if_attr_exists_empty_attr(self): """test if attributes exists with false return""" @@ -98,7 +97,7 @@ class TestTraits(unittest.TestCase): create_dataset = TraitObject({"type": "ProbeSet"}) create_trait = TraitObject({"dataset": create_dataset}) - self.assertFalse(has_num_cases(create_trait), False) + self.assertIs(has_num_cases(create_trait), False) def test_hash_num_cases_no_probeset(self): """test for hash num cases with dataset.type not Probeset""" -- cgit v1.2.3 From 5d9b1f5d6380beaf8a2d713b5c33baa5a163b2bc Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Tue, 3 Nov 2020 18:11:06 +0300 Subject: Add test for "/glossary" route --- wqflask/tests/integration/__init__.py | 0 wqflask/tests/integration/test_glossary.py | 28 ++++++++++++++++++++++++++++ 2 files changed, 28 insertions(+) create mode 100644 wqflask/tests/integration/__init__.py create mode 100644 wqflask/tests/integration/test_glossary.py (limited to 'wqflask/tests') diff --git a/wqflask/tests/integration/__init__.py b/wqflask/tests/integration/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/wqflask/tests/integration/test_glossary.py b/wqflask/tests/integration/test_glossary.py new file mode 100644 index 00000000..c9f1e62a --- /dev/null +++ b/wqflask/tests/integration/test_glossary.py @@ -0,0 +1,28 @@ +"Integration tests for glossary" +import unittest + +from bs4 import BeautifulSoup + +from wqflask import app + + +class TestGenMenu(unittest.TestCase): + """Tests for glossary""" + + def setUp(self): + self.app = app.test_client() + + def tearDown(self): + pass + + def test_glossary_page(self): + """Test that the glossary page is rendered properly""" + response = self.app.get('/glossary', follow_redirects=True) + html_content = BeautifulSoup(response.data, "lxml") + self.assertEqual(html_content.find("title").get_text(), + "Glossary GeneNetwork 2") + self.assertEqual( + html_content.find( + 'p', + attrs={'id': 'mytest'}).get_text(), + "Test") -- cgit v1.2.3 From f4a3652ee5b8087f551553df9498d5f00e169a86 Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Tue, 3 Nov 2020 18:13:57 +0300 Subject: Separate unittests from integration tests --- wqflask/tests/base/__init__.py | 0 wqflask/tests/base/data.py | 110 ------ wqflask/tests/base/test_data_set.py | 181 --------- wqflask/tests/base/test_general_object.py | 40 -- wqflask/tests/base/test_trait.py | 241 ------------ wqflask/tests/base/test_webqtl_case_data.py | 39 -- wqflask/tests/unit/__init__.py | 0 wqflask/tests/unit/base/__init__.py | 0 wqflask/tests/unit/base/data.py | 110 ++++++ wqflask/tests/unit/base/test_data_set.py | 181 +++++++++ wqflask/tests/unit/base/test_general_object.py | 40 ++ wqflask/tests/unit/base/test_trait.py | 241 ++++++++++++ wqflask/tests/unit/base/test_webqtl_case_data.py | 39 ++ wqflask/tests/unit/utility/__init__.py | 0 .../unit/utility/test_authentication_tools.py | 189 ++++++++++ wqflask/tests/unit/utility/test_chunks.py | 19 + wqflask/tests/unit/utility/test_corestats.py | 55 +++ .../tests/unit/utility/test_corr_result_helpers.py | 32 ++ wqflask/tests/unit/utility/test_formatting.py | 33 ++ wqflask/tests/unit/utility/test_hmac.py | 52 +++ wqflask/tests/unit/wqflask/__init__.py | 0 wqflask/tests/unit/wqflask/api/__init__.py | 0 wqflask/tests/unit/wqflask/api/test_gen_menu.py | 413 +++++++++++++++++++++ .../unit/wqflask/marker_regression/__init__.py | 0 .../test_display_mapping_results.py | 156 ++++++++ wqflask/tests/unit/wqflask/show_trait/__init__.py | 0 .../wqflask/show_trait/test_export_trait_data.py | 212 +++++++++++ wqflask/tests/unit/wqflask/test_collect.py | 73 ++++ wqflask/tests/unit/wqflask/test_pbkdf2.py | 61 +++ wqflask/tests/unit/wqflask/test_user_login.py | 21 ++ wqflask/tests/unit/wqflask/test_user_session.py | 15 + wqflask/tests/utility/__init__.py | 0 wqflask/tests/utility/test_authentication_tools.py | 189 ---------- wqflask/tests/utility/test_chunks.py | 19 - wqflask/tests/utility/test_corestats.py | 55 --- wqflask/tests/utility/test_corr_result_helpers.py | 32 -- wqflask/tests/utility/test_formatting.py | 33 -- wqflask/tests/utility/test_hmac.py | 52 --- wqflask/tests/wqflask/__init__.py | 0 wqflask/tests/wqflask/api/__init__.py | 0 wqflask/tests/wqflask/api/test_gen_menu.py | 413 --------------------- .../tests/wqflask/marker_regression/__init__.py | 0 .../test_display_mapping_results.py | 156 -------- wqflask/tests/wqflask/show_trait/__init__.py | 0 .../wqflask/show_trait/test_export_trait_data.py | 212 ----------- wqflask/tests/wqflask/test_collect.py | 73 ---- wqflask/tests/wqflask/test_pbkdf2.py | 61 --- wqflask/tests/wqflask/test_user_login.py | 21 -- wqflask/tests/wqflask/test_user_session.py | 15 - wqflask/wqflask/templates/glossary.html | 2 +- 50 files changed, 1943 insertions(+), 1943 deletions(-) delete mode 100644 wqflask/tests/base/__init__.py delete mode 100644 wqflask/tests/base/data.py delete mode 100644 wqflask/tests/base/test_data_set.py delete mode 100644 wqflask/tests/base/test_general_object.py delete mode 100644 wqflask/tests/base/test_trait.py delete mode 100644 wqflask/tests/base/test_webqtl_case_data.py create mode 100644 wqflask/tests/unit/__init__.py create mode 100644 wqflask/tests/unit/base/__init__.py create mode 100644 wqflask/tests/unit/base/data.py create mode 100644 wqflask/tests/unit/base/test_data_set.py create mode 100644 wqflask/tests/unit/base/test_general_object.py create mode 100644 wqflask/tests/unit/base/test_trait.py create mode 100644 wqflask/tests/unit/base/test_webqtl_case_data.py create mode 100644 wqflask/tests/unit/utility/__init__.py create mode 100644 wqflask/tests/unit/utility/test_authentication_tools.py create mode 100644 wqflask/tests/unit/utility/test_chunks.py create mode 100644 wqflask/tests/unit/utility/test_corestats.py create mode 100644 wqflask/tests/unit/utility/test_corr_result_helpers.py create mode 100644 wqflask/tests/unit/utility/test_formatting.py create mode 100644 wqflask/tests/unit/utility/test_hmac.py create mode 100644 wqflask/tests/unit/wqflask/__init__.py create mode 100644 wqflask/tests/unit/wqflask/api/__init__.py create mode 100644 wqflask/tests/unit/wqflask/api/test_gen_menu.py create mode 100644 wqflask/tests/unit/wqflask/marker_regression/__init__.py create mode 100644 wqflask/tests/unit/wqflask/marker_regression/test_display_mapping_results.py create mode 100644 wqflask/tests/unit/wqflask/show_trait/__init__.py create mode 100644 wqflask/tests/unit/wqflask/show_trait/test_export_trait_data.py create mode 100644 wqflask/tests/unit/wqflask/test_collect.py create mode 100644 wqflask/tests/unit/wqflask/test_pbkdf2.py create mode 100644 wqflask/tests/unit/wqflask/test_user_login.py create mode 100644 wqflask/tests/unit/wqflask/test_user_session.py delete mode 100644 wqflask/tests/utility/__init__.py delete mode 100644 wqflask/tests/utility/test_authentication_tools.py delete mode 100644 wqflask/tests/utility/test_chunks.py delete mode 100644 wqflask/tests/utility/test_corestats.py delete mode 100644 wqflask/tests/utility/test_corr_result_helpers.py delete mode 100644 wqflask/tests/utility/test_formatting.py delete mode 100644 wqflask/tests/utility/test_hmac.py delete mode 100644 wqflask/tests/wqflask/__init__.py delete mode 100644 wqflask/tests/wqflask/api/__init__.py delete mode 100644 wqflask/tests/wqflask/api/test_gen_menu.py delete mode 100644 wqflask/tests/wqflask/marker_regression/__init__.py delete mode 100644 wqflask/tests/wqflask/marker_regression/test_display_mapping_results.py delete mode 100644 wqflask/tests/wqflask/show_trait/__init__.py delete mode 100644 wqflask/tests/wqflask/show_trait/test_export_trait_data.py delete mode 100644 wqflask/tests/wqflask/test_collect.py delete mode 100644 wqflask/tests/wqflask/test_pbkdf2.py delete mode 100644 wqflask/tests/wqflask/test_user_login.py delete mode 100644 wqflask/tests/wqflask/test_user_session.py (limited to 'wqflask/tests') diff --git a/wqflask/tests/base/__init__.py b/wqflask/tests/base/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/wqflask/tests/base/data.py b/wqflask/tests/base/data.py deleted file mode 100644 index 06a5a989..00000000 --- a/wqflask/tests/base/data.py +++ /dev/null @@ -1,110 +0,0 @@ -gen_menu_json = """ -{ - "datasets": { - "human": { - "HLC": { - "Liver mRNA": [ - [ - "320", - "HLC_0311", - "GSE9588 Human Liver Normal (Mar11) Both Sexes" - ] - ], - "Phenotypes": [ - [ - "635", - "HLCPublish", - "HLC Published Phenotypes" - ] - ] - } - }, - "mouse": { - "BXD": { - "Genotypes": [ - [ - "600", - "BXDGeno", - "BXD Genotypes" - ] - ], - "Hippocampus mRNA": [ - [ - "112", - "HC_M2_0606_P", - "Hippocampus Consortium M430v2 (Jun06) PDNN" - ] - ], - "Phenotypes": [ - [ - "602", - "BXDPublish", - "BXD Published Phenotypes" - ] - ] - } - } - }, - "groups": { - "human": [ - [ - "HLC", - "Liver: Normal Gene Expression with Genotypes (Merck)", - "Family:None" - ] - ], - "mouse": [ - [ - "BXD", - "BXD", - "Family:None" - ] - ] - }, - "species": [ - [ - "human", - "Human" - ], - [ - "mouse", - "Mouse" - ] - ], - "types": { - "human": { - "HLC": [ - [ - "Phenotypes", - "Traits and Cofactors", - "Phenotypes" - ], - [ - "Liver mRNA", - "Liver mRNA", - "Molecular Trait Datasets" - ] - ] - }, - "mouse": { - "BXD": [ - [ - "Phenotypes", - "Traits and Cofactors", - "Phenotypes" - ], - [ - "Genotypes", - "DNA Markers and SNPs", - "Genotypes" - ], - [ - "Hippocampus mRNA", - "Hippocampus mRNA", - "Molecular Trait Datasets" - ] - ] - } - } -} -""" diff --git a/wqflask/tests/base/test_data_set.py b/wqflask/tests/base/test_data_set.py deleted file mode 100644 index 96563a16..00000000 --- a/wqflask/tests/base/test_data_set.py +++ /dev/null @@ -1,181 +0,0 @@ -"""Tests for wqflask/base/data_set.py""" - -import unittest -from unittest import mock - -from wqflask import app -from .data import gen_menu_json -from base.data_set import DatasetType - - -class TestDataSetTypes(unittest.TestCase): - """Tests for the DataSetType class""" - - def setUp(self): - self.test_dataset = """ - { - "AD-cases-controls-MyersGeno": "Geno", - "AD-cases-controls-MyersPublish": "Publish", - "AKXDGeno": "Geno", - "AXBXAGeno": "Geno", - "AXBXAPublish": "Publish", - "Aging-Brain-UCIPublish": "Publish", - "All Phenotypes": "Publish", - "B139_K_1206_M": "ProbeSet", - "B139_K_1206_R": "ProbeSet" - } - """ - self.app_context = app.app_context() - self.app_context.push() - - def tearDown(self): - self.app_context.pop() - - @mock.patch('base.data_set.g') - def test_data_set_type(self, db_mock): - """Test that DatasetType returns correctly if the Redis Instance is not empty - and the name variable exists in the dictionary - - """ - with app.app_context(): - db_mock.get = mock.Mock() - redis_mock = mock.Mock() - redis_mock.get.return_value = self.test_dataset - self.assertEqual(DatasetType(redis_mock) - ("All Phenotypes"), "Publish") - redis_mock.get.assert_called_once_with("dataset_structure") - - @mock.patch('base.data_set.requests.get') - def test_data_set_type_with_empty_redis(self, request_mock): - """Test that DatasetType returns correctly if the Redis Instance is empty and - the name variable exists in the dictionary - - """ - with app.app_context(): - request_mock.return_value.content = gen_menu_json - redis_mock = mock.Mock() - redis_mock.get.return_value = None - data_set = DatasetType(redis_mock) - self.assertEqual(data_set("BXDGeno"), "Geno") - self.assertEqual(data_set("BXDPublish"), "Publish") - self.assertEqual(data_set("HLC_0311"), "ProbeSet") - - redis_mock.set.assert_called_once_with( - "dataset_structure", - ('{"HLC_0311": "ProbeSet", ' - '"HLCPublish": "Publish", ' - '"BXDGeno": "Geno", ' - '"HC_M2_0606_P": "ProbeSet", ' - '"BXDPublish": "Publish"}')) - - @mock.patch('base.data_set.g') - def test_set_dataset_key_mrna(self, db_mock): - with app.app_context(): - db_mock.db.execute.return_value.fetchone.return_value = [1, 2, 3] - redis_mock = mock.Mock() - redis_mock.get.return_value = self.test_dataset - data_set = DatasetType(redis_mock) - data_set.set_dataset_key("mrna_expr", "Test") - self.assertEqual(data_set("Test"), "ProbeSet") - redis_mock.set.assert_called_once_with( - "dataset_structure", - ('{"AD-cases-controls-MyersGeno": "Geno", ' - '"AD-cases-controls-MyersPublish": "Publish", ' - '"AKXDGeno": "Geno", ' - '"AXBXAGeno": "Geno", ' - '"AXBXAPublish": "Publish", ' - '"Aging-Brain-UCIPublish": "Publish", ' - '"All Phenotypes": "Publish", ' - '"B139_K_1206_M": "ProbeSet", ' - '"B139_K_1206_R": "ProbeSet", ' - '"Test": "ProbeSet"}')) - - db_mock.db.execute.assert_called_with( - ("SELECT ProbeSetFreeze.Id FROM ProbeSetFreeze " + - "WHERE ProbeSetFreeze.Name = \"Test\" ") - ) - - @mock.patch('base.data_set.g') - def test_set_dataset_key_pheno(self, db_mock): - with app.app_context(): - db_mock.db.execute.return_value.fetchone.return_value = [1, 2, 3] - redis_mock = mock.Mock() - redis_mock.get.return_value = self.test_dataset - data_set = DatasetType(redis_mock) - data_set.set_dataset_key("pheno", "Test") - self.assertEqual(data_set("Test"), "Publish") - redis_mock.set.assert_called_once_with( - "dataset_structure", - ('{"AD-cases-controls-MyersGeno": "Geno", ' - '"AD-cases-controls-MyersPublish": "Publish", ' - '"AKXDGeno": "Geno", ' - '"AXBXAGeno": "Geno", ' - '"AXBXAPublish": "Publish", ' - '"Aging-Brain-UCIPublish": "Publish", ' - '"All Phenotypes": "Publish", ' - '"B139_K_1206_M": "ProbeSet", ' - '"B139_K_1206_R": "ProbeSet", ' - '"Test": "Publish"}')) - db_mock.db.execute.assert_called_with( - ("SELECT InfoFiles.GN_AccesionId " - "FROM InfoFiles, PublishFreeze, InbredSet " - "WHERE InbredSet.Name = 'Test' AND " - "PublishFreeze.InbredSetId = InbredSet.Id AND " - "InfoFiles.InfoPageName = PublishFreeze.Name") - ) - - @mock.patch('base.data_set.g') - def test_set_dataset_other_pheno(self, db_mock): - with app.app_context(): - db_mock.db.execute.return_value.fetchone.return_value = [1, 2, 3] - redis_mock = mock.Mock() - redis_mock.get.return_value = self.test_dataset - data_set = DatasetType(redis_mock) - data_set.set_dataset_key("other_pheno", "Test") - self.assertEqual(data_set("Test"), "Publish") - - redis_mock.set.assert_called_once_with( - "dataset_structure", - ('{"AD-cases-controls-MyersGeno": "Geno", ' - '"AD-cases-controls-MyersPublish": "Publish", ' - '"AKXDGeno": "Geno", ' - '"AXBXAGeno": "Geno", ' - '"AXBXAPublish": "Publish", ' - '"Aging-Brain-UCIPublish": "Publish", ' - '"All Phenotypes": "Publish", ' - '"B139_K_1206_M": "ProbeSet", ' - '"B139_K_1206_R": "ProbeSet", ' - '"Test": "Publish"}')) - - db_mock.db.execute.assert_called_with( - ("SELECT PublishFreeze.Name " + - "FROM PublishFreeze, InbredSet " + - "WHERE InbredSet.Name = 'Test' AND " - "PublishFreeze.InbredSetId = InbredSet.Id") - ) - - @mock.patch('base.data_set.g') - def test_set_dataset_geno(self, db_mock): - with app.app_context(): - db_mock.db.execute.return_value.fetchone.return_value = [1, 2, 3] - redis_mock = mock.Mock() - redis_mock.get.return_value = self.test_dataset - data_set = DatasetType(redis_mock) - data_set.set_dataset_key("geno", "Test") - self.assertEqual(data_set("Test"), "Geno") - redis_mock.set.assert_called_once_with( - "dataset_structure", - ('{"AD-cases-controls-MyersGeno": "Geno", ' - '"AD-cases-controls-MyersPublish": "Publish", ' - '"AKXDGeno": "Geno", ' - '"AXBXAGeno": "Geno", ' - '"AXBXAPublish": "Publish", ' - '"Aging-Brain-UCIPublish": "Publish", ' - '"All Phenotypes": "Publish", ' - '"B139_K_1206_M": "ProbeSet", ' - '"B139_K_1206_R": "ProbeSet", ' - '"Test": "Geno"}')) - - db_mock.db.execute.assert_called_with( - ("SELECT GenoFreeze.Id FROM " - "GenoFreeze WHERE GenoFreeze.Name = \"Test\" ")) diff --git a/wqflask/tests/base/test_general_object.py b/wqflask/tests/base/test_general_object.py deleted file mode 100644 index 00fd3c72..00000000 --- a/wqflask/tests/base/test_general_object.py +++ /dev/null @@ -1,40 +0,0 @@ -import unittest - -from base.GeneralObject import GeneralObject - - -class TestGeneralObjectTests(unittest.TestCase): - """ - Test the GeneralObject base class - """ - - def test_object_contents(self): - """Test whether base contents are stored properly""" - test_obj = GeneralObject("a", "b", "c") - self.assertEqual("abc", ''.join(test_obj.contents)) - self.assertEqual(len(test_obj), 0) - - def test_object_dict(self): - """Test whether the base class is printed properly""" - test_obj = GeneralObject("a", name="test", value=1) - self.assertEqual(str(test_obj), "name = test\nvalue = 1\n") - self.assertEqual( - repr(test_obj), "contents = ['a']\nname = test\nvalue = 1\n") - self.assertEqual(len(test_obj), 2) - self.assertEqual(test_obj["value"], 1) - test_obj["test"] = 1 - self.assertEqual(test_obj["test"], 1) - - def test_get_attribute(self): - "Test that getattr works" - test_obj = GeneralObject("a", name="test", value=1) - self.assertEqual(getattr(test_obj, "value", None), 1) - self.assertEqual(getattr(test_obj, "non-existent", None), None) - - def test_object_comparisons(self): - "Test that 2 objects of the same length are equal" - test_obj1 = GeneralObject("a", name="test", value=1) - test_obj2 = GeneralObject("b", name="test2", value=2) - test_obj3 = GeneralObject("a", name="test", x=1, y=2) - self.assertTrue(test_obj1 == test_obj2) - self.assertFalse(test_obj1 == test_obj3) diff --git a/wqflask/tests/base/test_trait.py b/wqflask/tests/base/test_trait.py deleted file mode 100644 index 826ccefd..00000000 --- a/wqflask/tests/base/test_trait.py +++ /dev/null @@ -1,241 +0,0 @@ -# -*- coding: utf-8 -*- -"""Tests wqflask/base/trait.py""" -import unittest -from unittest import mock - -from wqflask import app -from base.trait import GeneralTrait -from base.trait import retrieve_trait_info - - -class TestResponse: - """Mock Test Response after a request""" - @property - def content(self): - """Mock the content from Requests.get(params).content""" - return "[1, 2, 3, 4]" - - -class TestNilResponse: - """Mock Test Response after a request""" - @property - def content(self): - """Mock the content from Requests.get(params).content""" - return "{}" - - -class MockTrait(GeneralTrait): - @property - def wikidata_alias_fmt(self): - return "Mock alias" - - -class TestRetrieveTraitInfo(unittest.TestCase): - """Tests for 'retrieve_trait_info'""" - - def setUp(self): - self.app_context = app.app_context() - self.app_context.push() - - def tearDown(self): - self.app_context.pop() - - def test_retrieve_trait_info_with_empty_dataset(self): - """Test that an exception is raised when dataset is empty""" - with self.assertRaises(AssertionError): - retrieve_trait_info(trait=mock.MagicMock(), - dataset={}) - - @mock.patch('base.trait.requests.get') - @mock.patch('base.trait.g', mock.Mock()) - def test_retrieve_trait_info_with_empty_trait_info(self, - requests_mock): - """Empty trait info""" - requests_mock.return_value = TestNilResponse() - with self.assertRaises(KeyError): - retrieve_trait_info(trait=mock.MagicMock(), - dataset=mock.MagicMock()) - - @mock.patch('base.trait.requests.get') - @mock.patch('base.trait.g', mock.Mock()) - def test_retrieve_trait_info_with_non_empty_trait_info(self, - requests_mock): - """Test that attributes are set""" - mock_dataset = mock.MagicMock() - requests_mock.return_value = TestResponse() - type(mock_dataset).display_fields = mock.PropertyMock( - return_value=["a", "b", "c", "d"]) - test_trait = retrieve_trait_info(trait=MockTrait(dataset=mock_dataset), - dataset=mock_dataset) - self.assertEqual(test_trait.a, 1) - self.assertEqual(test_trait.b, 2) - self.assertEqual(test_trait.c, 3) - self.assertEqual(test_trait.d, 4) - - @mock.patch('base.trait.requests.get') - @mock.patch('base.trait.g', mock.Mock()) - def test_retrieve_trait_info_utf8_parsing(self, - requests_mock): - """Test that utf-8 strings are parsed correctly""" - utf_8_string = "test_string" - mock_dataset = mock.MagicMock() - requests_mock.return_value = TestResponse() - type(mock_dataset).display_fields = mock.PropertyMock( - return_value=["a", "b", "c", "d"]) - type(mock_dataset).type = 'Publish' - - mock_trait = MockTrait( - dataset=mock_dataset, - pre_publication_description=utf_8_string - ) - trait_attrs = { - "group_code": "test_code", - "pre_publication_description": "test_pre_pub", - "pre_publication_abbreviation": "ファイルを画面毎に見て行くには、次のコマンドを使います。", - "post_publication_description": None, - "pubmed_id": None, - 'year': "2020", - "authors": "Jane Doe かいと", - } - for key, val in list(trait_attrs.items()): - setattr(mock_trait, key, val) - test_trait = retrieve_trait_info(trait=mock_trait, - dataset=mock_dataset) - self.assertEqual(test_trait.abbreviation, - "ファイルを画面毎に見て行くには、次のコマンドを使います。") - self.assertEqual(test_trait.authors, - "Jane Doe かいと") - - @mock.patch('base.trait.requests.get') - @mock.patch('base.trait.g') - @mock.patch('base.trait.get_resource_id') - def test_retrieve_trait_info_with_non_empty_lrs(self, - resource_id_mock, - g_mock, - requests_mock): - """Test retrieve trait info when lrs has a value""" - resource_id_mock.return_value = 1 - g_mock.db.execute.return_value.fetchone = mock.Mock() - g_mock.db.execute.return_value.fetchone.side_effect = [ - [1, 2, 3, 4], # trait_info = g.db.execute(query).fetchone() - [1, 2.37, 3, 4, 5], # trait_qtl = g.db.execute(query).fetchone() - [2.7333, 2.1204] # trait_info = g.db.execute(query).fetchone() - ] - requests_mock.return_value = None - - mock_dataset = mock.MagicMock() - type(mock_dataset).display_fields = mock.PropertyMock( - return_value=["a", "b", "c", "d"]) - type(mock_dataset).type = "ProbeSet" - type(mock_dataset).name = "RandomName" - - mock_trait = MockTrait( - dataset=mock_dataset, - pre_publication_description="test_string" - ) - trait_attrs = { - "description": "some description", - "probe_target_description": "some description", - "cellid": False, - "chr": 2.733, - "mb": 2.1204 - } - - for key, val in list(trait_attrs.items()): - setattr(mock_trait, key, val) - test_trait = retrieve_trait_info(trait=mock_trait, - dataset=mock_dataset, - get_qtl_info=True) - self.assertEqual(test_trait.LRS_score_repr, - "2.4") - - @mock.patch('base.trait.requests.get') - @mock.patch('base.trait.g') - @mock.patch('base.trait.get_resource_id') - def test_retrieve_trait_info_with_empty_lrs_field(self, - resource_id_mock, - g_mock, - requests_mock): - """Test retrieve trait info with empty lrs field""" - resource_id_mock.return_value = 1 - g_mock.db.execute.return_value.fetchone = mock.Mock() - g_mock.db.execute.return_value.fetchone.side_effect = [ - [1, 2, 3, 4], # trait_info = g.db.execute(query).fetchone() - [1, None, 3, 4, 5], # trait_qtl = g.db.execute(query).fetchone() - [2, 3] # trait_info = g.db.execute(query).fetchone() - ] - requests_mock.return_value = None - - mock_dataset = mock.MagicMock() - type(mock_dataset).display_fields = mock.PropertyMock( - return_value=["a", "b", "c", "d"]) - type(mock_dataset).type = "ProbeSet" - type(mock_dataset).name = "RandomName" - - mock_trait = MockTrait( - dataset=mock_dataset, - pre_publication_description="test_string" - ) - trait_attrs = { - "description": "some description", - "probe_target_description": "some description", - "cellid": False, - "chr": 2.733, - "mb": 2.1204 - } - - for key, val in list(trait_attrs.items()): - setattr(mock_trait, key, val) - test_trait = retrieve_trait_info(trait=mock_trait, - dataset=mock_dataset, - get_qtl_info=True) - self.assertEqual(test_trait.LRS_score_repr, - "N/A") - self.assertEqual(test_trait.LRS_location_repr, - "Chr2: 3.000000") - - @mock.patch('base.trait.requests.get') - @mock.patch('base.trait.g') - @mock.patch('base.trait.get_resource_id') - def test_retrieve_trait_info_with_empty_chr_field(self, - resource_id_mock, - g_mock, - requests_mock): - """Test retrieve trait info with empty chr field""" - resource_id_mock.return_value = 1 - g_mock.db.execute.return_value.fetchone = mock.Mock() - g_mock.db.execute.return_value.fetchone.side_effect = [ - [1, 2, 3, 4], # trait_info = g.db.execute(query).fetchone() - [1, 2, 3, 4, 5], # trait_qtl = g.db.execute(query).fetchone() - [None, 3] # trait_info = g.db.execute(query).fetchone() - ] - - requests_mock.return_value = None - - mock_dataset = mock.MagicMock() - type(mock_dataset).display_fields = mock.PropertyMock( - return_value=["a", "b", "c", "d"]) - type(mock_dataset).type = "ProbeSet" - type(mock_dataset).name = "RandomName" - - mock_trait = MockTrait( - dataset=mock_dataset, - pre_publication_description="test_string" - ) - trait_attrs = { - "description": "some description", - "probe_target_description": "some description", - "cellid": False, - "chr": 2.733, - "mb": 2.1204 - } - - for key, val in list(trait_attrs.items()): - setattr(mock_trait, key, val) - test_trait = retrieve_trait_info(trait=mock_trait, - dataset=mock_dataset, - get_qtl_info=True) - self.assertEqual(test_trait.LRS_score_repr, - "N/A") - self.assertEqual(test_trait.LRS_location_repr, - "N/A") diff --git a/wqflask/tests/base/test_webqtl_case_data.py b/wqflask/tests/base/test_webqtl_case_data.py deleted file mode 100644 index 8e8ba482..00000000 --- a/wqflask/tests/base/test_webqtl_case_data.py +++ /dev/null @@ -1,39 +0,0 @@ -"""Tests for wqflask/base/webqtlCaseData.py""" -import unittest - -from wqflask import app # Required because of utility.tools in webqtlCaseData.py -from base.webqtlCaseData import webqtlCaseData - -class TestWebqtlCaseData(unittest.TestCase): - """Tests for WebqtlCaseData class""" - - def setUp(self): - self.w = webqtlCaseData(name="Test", - value=0, - variance=0.0, - num_cases=10, - name2="Test2") - - def test_webqtl_case_data_repr(self): - self.assertEqual( - repr(self.w), - " value=0.000 variance=0.000 ndata=10 name=Test name2=Test2" - ) - - def test_class_outlier(self): - self.assertEqual(self.w.class_outlier, "") - - def test_display_value(self): - self.assertEqual(self.w.display_value, "0.000") - self.w.value = None - self.assertEqual(self.w.display_value, "x") - - def test_display_variance(self): - self.assertEqual(self.w.display_variance, "0.000") - self.w.variance = None - self.assertEqual(self.w.display_variance, "x") - - def test_display_num_cases(self): - self.assertEqual(self.w.display_num_cases, "10") - self.w.num_cases = None - self.assertEqual(self.w.display_num_cases, "x") diff --git a/wqflask/tests/unit/__init__.py b/wqflask/tests/unit/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/wqflask/tests/unit/base/__init__.py b/wqflask/tests/unit/base/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/wqflask/tests/unit/base/data.py b/wqflask/tests/unit/base/data.py new file mode 100644 index 00000000..06a5a989 --- /dev/null +++ b/wqflask/tests/unit/base/data.py @@ -0,0 +1,110 @@ +gen_menu_json = """ +{ + "datasets": { + "human": { + "HLC": { + "Liver mRNA": [ + [ + "320", + "HLC_0311", + "GSE9588 Human Liver Normal (Mar11) Both Sexes" + ] + ], + "Phenotypes": [ + [ + "635", + "HLCPublish", + "HLC Published Phenotypes" + ] + ] + } + }, + "mouse": { + "BXD": { + "Genotypes": [ + [ + "600", + "BXDGeno", + "BXD Genotypes" + ] + ], + "Hippocampus mRNA": [ + [ + "112", + "HC_M2_0606_P", + "Hippocampus Consortium M430v2 (Jun06) PDNN" + ] + ], + "Phenotypes": [ + [ + "602", + "BXDPublish", + "BXD Published Phenotypes" + ] + ] + } + } + }, + "groups": { + "human": [ + [ + "HLC", + "Liver: Normal Gene Expression with Genotypes (Merck)", + "Family:None" + ] + ], + "mouse": [ + [ + "BXD", + "BXD", + "Family:None" + ] + ] + }, + "species": [ + [ + "human", + "Human" + ], + [ + "mouse", + "Mouse" + ] + ], + "types": { + "human": { + "HLC": [ + [ + "Phenotypes", + "Traits and Cofactors", + "Phenotypes" + ], + [ + "Liver mRNA", + "Liver mRNA", + "Molecular Trait Datasets" + ] + ] + }, + "mouse": { + "BXD": [ + [ + "Phenotypes", + "Traits and Cofactors", + "Phenotypes" + ], + [ + "Genotypes", + "DNA Markers and SNPs", + "Genotypes" + ], + [ + "Hippocampus mRNA", + "Hippocampus mRNA", + "Molecular Trait Datasets" + ] + ] + } + } +} +""" diff --git a/wqflask/tests/unit/base/test_data_set.py b/wqflask/tests/unit/base/test_data_set.py new file mode 100644 index 00000000..96563a16 --- /dev/null +++ b/wqflask/tests/unit/base/test_data_set.py @@ -0,0 +1,181 @@ +"""Tests for wqflask/base/data_set.py""" + +import unittest +from unittest import mock + +from wqflask import app +from .data import gen_menu_json +from base.data_set import DatasetType + + +class TestDataSetTypes(unittest.TestCase): + """Tests for the DataSetType class""" + + def setUp(self): + self.test_dataset = """ + { + "AD-cases-controls-MyersGeno": "Geno", + "AD-cases-controls-MyersPublish": "Publish", + "AKXDGeno": "Geno", + "AXBXAGeno": "Geno", + "AXBXAPublish": "Publish", + "Aging-Brain-UCIPublish": "Publish", + "All Phenotypes": "Publish", + "B139_K_1206_M": "ProbeSet", + "B139_K_1206_R": "ProbeSet" + } + """ + self.app_context = app.app_context() + self.app_context.push() + + def tearDown(self): + self.app_context.pop() + + @mock.patch('base.data_set.g') + def test_data_set_type(self, db_mock): + """Test that DatasetType returns correctly if the Redis Instance is not empty + and the name variable exists in the dictionary + + """ + with app.app_context(): + db_mock.get = mock.Mock() + redis_mock = mock.Mock() + redis_mock.get.return_value = self.test_dataset + self.assertEqual(DatasetType(redis_mock) + ("All Phenotypes"), "Publish") + redis_mock.get.assert_called_once_with("dataset_structure") + + @mock.patch('base.data_set.requests.get') + def test_data_set_type_with_empty_redis(self, request_mock): + """Test that DatasetType returns correctly if the Redis Instance is empty and + the name variable exists in the dictionary + + """ + with app.app_context(): + request_mock.return_value.content = gen_menu_json + redis_mock = mock.Mock() + redis_mock.get.return_value = None + data_set = DatasetType(redis_mock) + self.assertEqual(data_set("BXDGeno"), "Geno") + self.assertEqual(data_set("BXDPublish"), "Publish") + self.assertEqual(data_set("HLC_0311"), "ProbeSet") + + redis_mock.set.assert_called_once_with( + "dataset_structure", + ('{"HLC_0311": "ProbeSet", ' + '"HLCPublish": "Publish", ' + '"BXDGeno": "Geno", ' + '"HC_M2_0606_P": "ProbeSet", ' + '"BXDPublish": "Publish"}')) + + @mock.patch('base.data_set.g') + def test_set_dataset_key_mrna(self, db_mock): + with app.app_context(): + db_mock.db.execute.return_value.fetchone.return_value = [1, 2, 3] + redis_mock = mock.Mock() + redis_mock.get.return_value = self.test_dataset + data_set = DatasetType(redis_mock) + data_set.set_dataset_key("mrna_expr", "Test") + self.assertEqual(data_set("Test"), "ProbeSet") + redis_mock.set.assert_called_once_with( + "dataset_structure", + ('{"AD-cases-controls-MyersGeno": "Geno", ' + '"AD-cases-controls-MyersPublish": "Publish", ' + '"AKXDGeno": "Geno", ' + '"AXBXAGeno": "Geno", ' + '"AXBXAPublish": "Publish", ' + '"Aging-Brain-UCIPublish": "Publish", ' + '"All Phenotypes": "Publish", ' + '"B139_K_1206_M": "ProbeSet", ' + '"B139_K_1206_R": "ProbeSet", ' + '"Test": "ProbeSet"}')) + + db_mock.db.execute.assert_called_with( + ("SELECT ProbeSetFreeze.Id FROM ProbeSetFreeze " + + "WHERE ProbeSetFreeze.Name = \"Test\" ") + ) + + @mock.patch('base.data_set.g') + def test_set_dataset_key_pheno(self, db_mock): + with app.app_context(): + db_mock.db.execute.return_value.fetchone.return_value = [1, 2, 3] + redis_mock = mock.Mock() + redis_mock.get.return_value = self.test_dataset + data_set = DatasetType(redis_mock) + data_set.set_dataset_key("pheno", "Test") + self.assertEqual(data_set("Test"), "Publish") + redis_mock.set.assert_called_once_with( + "dataset_structure", + ('{"AD-cases-controls-MyersGeno": "Geno", ' + '"AD-cases-controls-MyersPublish": "Publish", ' + '"AKXDGeno": "Geno", ' + '"AXBXAGeno": "Geno", ' + '"AXBXAPublish": "Publish", ' + '"Aging-Brain-UCIPublish": "Publish", ' + '"All Phenotypes": "Publish", ' + '"B139_K_1206_M": "ProbeSet", ' + '"B139_K_1206_R": "ProbeSet", ' + '"Test": "Publish"}')) + db_mock.db.execute.assert_called_with( + ("SELECT InfoFiles.GN_AccesionId " + "FROM InfoFiles, PublishFreeze, InbredSet " + "WHERE InbredSet.Name = 'Test' AND " + "PublishFreeze.InbredSetId = InbredSet.Id AND " + "InfoFiles.InfoPageName = PublishFreeze.Name") + ) + + @mock.patch('base.data_set.g') + def test_set_dataset_other_pheno(self, db_mock): + with app.app_context(): + db_mock.db.execute.return_value.fetchone.return_value = [1, 2, 3] + redis_mock = mock.Mock() + redis_mock.get.return_value = self.test_dataset + data_set = DatasetType(redis_mock) + data_set.set_dataset_key("other_pheno", "Test") + self.assertEqual(data_set("Test"), "Publish") + + redis_mock.set.assert_called_once_with( + "dataset_structure", + ('{"AD-cases-controls-MyersGeno": "Geno", ' + '"AD-cases-controls-MyersPublish": "Publish", ' + '"AKXDGeno": "Geno", ' + '"AXBXAGeno": "Geno", ' + '"AXBXAPublish": "Publish", ' + '"Aging-Brain-UCIPublish": "Publish", ' + '"All Phenotypes": "Publish", ' + '"B139_K_1206_M": "ProbeSet", ' + '"B139_K_1206_R": "ProbeSet", ' + '"Test": "Publish"}')) + + db_mock.db.execute.assert_called_with( + ("SELECT PublishFreeze.Name " + + "FROM PublishFreeze, InbredSet " + + "WHERE InbredSet.Name = 'Test' AND " + "PublishFreeze.InbredSetId = InbredSet.Id") + ) + + @mock.patch('base.data_set.g') + def test_set_dataset_geno(self, db_mock): + with app.app_context(): + db_mock.db.execute.return_value.fetchone.return_value = [1, 2, 3] + redis_mock = mock.Mock() + redis_mock.get.return_value = self.test_dataset + data_set = DatasetType(redis_mock) + data_set.set_dataset_key("geno", "Test") + self.assertEqual(data_set("Test"), "Geno") + redis_mock.set.assert_called_once_with( + "dataset_structure", + ('{"AD-cases-controls-MyersGeno": "Geno", ' + '"AD-cases-controls-MyersPublish": "Publish", ' + '"AKXDGeno": "Geno", ' + '"AXBXAGeno": "Geno", ' + '"AXBXAPublish": "Publish", ' + '"Aging-Brain-UCIPublish": "Publish", ' + '"All Phenotypes": "Publish", ' + '"B139_K_1206_M": "ProbeSet", ' + '"B139_K_1206_R": "ProbeSet", ' + '"Test": "Geno"}')) + + db_mock.db.execute.assert_called_with( + ("SELECT GenoFreeze.Id FROM " + "GenoFreeze WHERE GenoFreeze.Name = \"Test\" ")) diff --git a/wqflask/tests/unit/base/test_general_object.py b/wqflask/tests/unit/base/test_general_object.py new file mode 100644 index 00000000..00fd3c72 --- /dev/null +++ b/wqflask/tests/unit/base/test_general_object.py @@ -0,0 +1,40 @@ +import unittest + +from base.GeneralObject import GeneralObject + + +class TestGeneralObjectTests(unittest.TestCase): + """ + Test the GeneralObject base class + """ + + def test_object_contents(self): + """Test whether base contents are stored properly""" + test_obj = GeneralObject("a", "b", "c") + self.assertEqual("abc", ''.join(test_obj.contents)) + self.assertEqual(len(test_obj), 0) + + def test_object_dict(self): + """Test whether the base class is printed properly""" + test_obj = GeneralObject("a", name="test", value=1) + self.assertEqual(str(test_obj), "name = test\nvalue = 1\n") + self.assertEqual( + repr(test_obj), "contents = ['a']\nname = test\nvalue = 1\n") + self.assertEqual(len(test_obj), 2) + self.assertEqual(test_obj["value"], 1) + test_obj["test"] = 1 + self.assertEqual(test_obj["test"], 1) + + def test_get_attribute(self): + "Test that getattr works" + test_obj = GeneralObject("a", name="test", value=1) + self.assertEqual(getattr(test_obj, "value", None), 1) + self.assertEqual(getattr(test_obj, "non-existent", None), None) + + def test_object_comparisons(self): + "Test that 2 objects of the same length are equal" + test_obj1 = GeneralObject("a", name="test", value=1) + test_obj2 = GeneralObject("b", name="test2", value=2) + test_obj3 = GeneralObject("a", name="test", x=1, y=2) + self.assertTrue(test_obj1 == test_obj2) + self.assertFalse(test_obj1 == test_obj3) diff --git a/wqflask/tests/unit/base/test_trait.py b/wqflask/tests/unit/base/test_trait.py new file mode 100644 index 00000000..826ccefd --- /dev/null +++ b/wqflask/tests/unit/base/test_trait.py @@ -0,0 +1,241 @@ +# -*- coding: utf-8 -*- +"""Tests wqflask/base/trait.py""" +import unittest +from unittest import mock + +from wqflask import app +from base.trait import GeneralTrait +from base.trait import retrieve_trait_info + + +class TestResponse: + """Mock Test Response after a request""" + @property + def content(self): + """Mock the content from Requests.get(params).content""" + return "[1, 2, 3, 4]" + + +class TestNilResponse: + """Mock Test Response after a request""" + @property + def content(self): + """Mock the content from Requests.get(params).content""" + return "{}" + + +class MockTrait(GeneralTrait): + @property + def wikidata_alias_fmt(self): + return "Mock alias" + + +class TestRetrieveTraitInfo(unittest.TestCase): + """Tests for 'retrieve_trait_info'""" + + def setUp(self): + self.app_context = app.app_context() + self.app_context.push() + + def tearDown(self): + self.app_context.pop() + + def test_retrieve_trait_info_with_empty_dataset(self): + """Test that an exception is raised when dataset is empty""" + with self.assertRaises(AssertionError): + retrieve_trait_info(trait=mock.MagicMock(), + dataset={}) + + @mock.patch('base.trait.requests.get') + @mock.patch('base.trait.g', mock.Mock()) + def test_retrieve_trait_info_with_empty_trait_info(self, + requests_mock): + """Empty trait info""" + requests_mock.return_value = TestNilResponse() + with self.assertRaises(KeyError): + retrieve_trait_info(trait=mock.MagicMock(), + dataset=mock.MagicMock()) + + @mock.patch('base.trait.requests.get') + @mock.patch('base.trait.g', mock.Mock()) + def test_retrieve_trait_info_with_non_empty_trait_info(self, + requests_mock): + """Test that attributes are set""" + mock_dataset = mock.MagicMock() + requests_mock.return_value = TestResponse() + type(mock_dataset).display_fields = mock.PropertyMock( + return_value=["a", "b", "c", "d"]) + test_trait = retrieve_trait_info(trait=MockTrait(dataset=mock_dataset), + dataset=mock_dataset) + self.assertEqual(test_trait.a, 1) + self.assertEqual(test_trait.b, 2) + self.assertEqual(test_trait.c, 3) + self.assertEqual(test_trait.d, 4) + + @mock.patch('base.trait.requests.get') + @mock.patch('base.trait.g', mock.Mock()) + def test_retrieve_trait_info_utf8_parsing(self, + requests_mock): + """Test that utf-8 strings are parsed correctly""" + utf_8_string = "test_string" + mock_dataset = mock.MagicMock() + requests_mock.return_value = TestResponse() + type(mock_dataset).display_fields = mock.PropertyMock( + return_value=["a", "b", "c", "d"]) + type(mock_dataset).type = 'Publish' + + mock_trait = MockTrait( + dataset=mock_dataset, + pre_publication_description=utf_8_string + ) + trait_attrs = { + "group_code": "test_code", + "pre_publication_description": "test_pre_pub", + "pre_publication_abbreviation": "ファイルを画面毎に見て行くには、次のコマンドを使います。", + "post_publication_description": None, + "pubmed_id": None, + 'year': "2020", + "authors": "Jane Doe かいと", + } + for key, val in list(trait_attrs.items()): + setattr(mock_trait, key, val) + test_trait = retrieve_trait_info(trait=mock_trait, + dataset=mock_dataset) + self.assertEqual(test_trait.abbreviation, + "ファイルを画面毎に見て行くには、次のコマンドを使います。") + self.assertEqual(test_trait.authors, + "Jane Doe かいと") + + @mock.patch('base.trait.requests.get') + @mock.patch('base.trait.g') + @mock.patch('base.trait.get_resource_id') + def test_retrieve_trait_info_with_non_empty_lrs(self, + resource_id_mock, + g_mock, + requests_mock): + """Test retrieve trait info when lrs has a value""" + resource_id_mock.return_value = 1 + g_mock.db.execute.return_value.fetchone = mock.Mock() + g_mock.db.execute.return_value.fetchone.side_effect = [ + [1, 2, 3, 4], # trait_info = g.db.execute(query).fetchone() + [1, 2.37, 3, 4, 5], # trait_qtl = g.db.execute(query).fetchone() + [2.7333, 2.1204] # trait_info = g.db.execute(query).fetchone() + ] + requests_mock.return_value = None + + mock_dataset = mock.MagicMock() + type(mock_dataset).display_fields = mock.PropertyMock( + return_value=["a", "b", "c", "d"]) + type(mock_dataset).type = "ProbeSet" + type(mock_dataset).name = "RandomName" + + mock_trait = MockTrait( + dataset=mock_dataset, + pre_publication_description="test_string" + ) + trait_attrs = { + "description": "some description", + "probe_target_description": "some description", + "cellid": False, + "chr": 2.733, + "mb": 2.1204 + } + + for key, val in list(trait_attrs.items()): + setattr(mock_trait, key, val) + test_trait = retrieve_trait_info(trait=mock_trait, + dataset=mock_dataset, + get_qtl_info=True) + self.assertEqual(test_trait.LRS_score_repr, + "2.4") + + @mock.patch('base.trait.requests.get') + @mock.patch('base.trait.g') + @mock.patch('base.trait.get_resource_id') + def test_retrieve_trait_info_with_empty_lrs_field(self, + resource_id_mock, + g_mock, + requests_mock): + """Test retrieve trait info with empty lrs field""" + resource_id_mock.return_value = 1 + g_mock.db.execute.return_value.fetchone = mock.Mock() + g_mock.db.execute.return_value.fetchone.side_effect = [ + [1, 2, 3, 4], # trait_info = g.db.execute(query).fetchone() + [1, None, 3, 4, 5], # trait_qtl = g.db.execute(query).fetchone() + [2, 3] # trait_info = g.db.execute(query).fetchone() + ] + requests_mock.return_value = None + + mock_dataset = mock.MagicMock() + type(mock_dataset).display_fields = mock.PropertyMock( + return_value=["a", "b", "c", "d"]) + type(mock_dataset).type = "ProbeSet" + type(mock_dataset).name = "RandomName" + + mock_trait = MockTrait( + dataset=mock_dataset, + pre_publication_description="test_string" + ) + trait_attrs = { + "description": "some description", + "probe_target_description": "some description", + "cellid": False, + "chr": 2.733, + "mb": 2.1204 + } + + for key, val in list(trait_attrs.items()): + setattr(mock_trait, key, val) + test_trait = retrieve_trait_info(trait=mock_trait, + dataset=mock_dataset, + get_qtl_info=True) + self.assertEqual(test_trait.LRS_score_repr, + "N/A") + self.assertEqual(test_trait.LRS_location_repr, + "Chr2: 3.000000") + + @mock.patch('base.trait.requests.get') + @mock.patch('base.trait.g') + @mock.patch('base.trait.get_resource_id') + def test_retrieve_trait_info_with_empty_chr_field(self, + resource_id_mock, + g_mock, + requests_mock): + """Test retrieve trait info with empty chr field""" + resource_id_mock.return_value = 1 + g_mock.db.execute.return_value.fetchone = mock.Mock() + g_mock.db.execute.return_value.fetchone.side_effect = [ + [1, 2, 3, 4], # trait_info = g.db.execute(query).fetchone() + [1, 2, 3, 4, 5], # trait_qtl = g.db.execute(query).fetchone() + [None, 3] # trait_info = g.db.execute(query).fetchone() + ] + + requests_mock.return_value = None + + mock_dataset = mock.MagicMock() + type(mock_dataset).display_fields = mock.PropertyMock( + return_value=["a", "b", "c", "d"]) + type(mock_dataset).type = "ProbeSet" + type(mock_dataset).name = "RandomName" + + mock_trait = MockTrait( + dataset=mock_dataset, + pre_publication_description="test_string" + ) + trait_attrs = { + "description": "some description", + "probe_target_description": "some description", + "cellid": False, + "chr": 2.733, + "mb": 2.1204 + } + + for key, val in list(trait_attrs.items()): + setattr(mock_trait, key, val) + test_trait = retrieve_trait_info(trait=mock_trait, + dataset=mock_dataset, + get_qtl_info=True) + self.assertEqual(test_trait.LRS_score_repr, + "N/A") + self.assertEqual(test_trait.LRS_location_repr, + "N/A") diff --git a/wqflask/tests/unit/base/test_webqtl_case_data.py b/wqflask/tests/unit/base/test_webqtl_case_data.py new file mode 100644 index 00000000..8e8ba482 --- /dev/null +++ b/wqflask/tests/unit/base/test_webqtl_case_data.py @@ -0,0 +1,39 @@ +"""Tests for wqflask/base/webqtlCaseData.py""" +import unittest + +from wqflask import app # Required because of utility.tools in webqtlCaseData.py +from base.webqtlCaseData import webqtlCaseData + +class TestWebqtlCaseData(unittest.TestCase): + """Tests for WebqtlCaseData class""" + + def setUp(self): + self.w = webqtlCaseData(name="Test", + value=0, + variance=0.0, + num_cases=10, + name2="Test2") + + def test_webqtl_case_data_repr(self): + self.assertEqual( + repr(self.w), + " value=0.000 variance=0.000 ndata=10 name=Test name2=Test2" + ) + + def test_class_outlier(self): + self.assertEqual(self.w.class_outlier, "") + + def test_display_value(self): + self.assertEqual(self.w.display_value, "0.000") + self.w.value = None + self.assertEqual(self.w.display_value, "x") + + def test_display_variance(self): + self.assertEqual(self.w.display_variance, "0.000") + self.w.variance = None + self.assertEqual(self.w.display_variance, "x") + + def test_display_num_cases(self): + self.assertEqual(self.w.display_num_cases, "10") + self.w.num_cases = None + self.assertEqual(self.w.display_num_cases, "x") diff --git a/wqflask/tests/unit/utility/__init__.py b/wqflask/tests/unit/utility/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/wqflask/tests/unit/utility/test_authentication_tools.py b/wqflask/tests/unit/utility/test_authentication_tools.py new file mode 100644 index 00000000..5c391be5 --- /dev/null +++ b/wqflask/tests/unit/utility/test_authentication_tools.py @@ -0,0 +1,189 @@ +"""Tests for authentication tools""" +import unittest +from unittest import mock + +from utility.authentication_tools import check_resource_availability +from utility.authentication_tools import add_new_resource + + +class TestResponse: + """Mock Test Response after a request""" + @property + def content(self): + """Mock the content from Requests.get(params).content""" + return '["foo"]' + + +class TestUser: + """Mock user""" + @property + def user_id(self): + """Mockes user id. Used in Flask.g.user_session.user_id""" + return "Jane" + + +class TestUserSession: + """Mock user session""" + @property + def user_session(self): + """Mock user session. Mocks Flask.g.user_session object""" + return TestUser() + + +def mock_add_resource(resource_ob, update=False): + return resource_ob + + +class TestCheckResourceAvailability(unittest.TestCase): + """Test methods related to checking the resource availability""" + @mock.patch('utility.authentication_tools.add_new_resource') + @mock.patch('utility.authentication_tools.Redis') + @mock.patch('utility.authentication_tools.g', mock.Mock()) + @mock.patch('utility.authentication_tools.get_resource_id') + def test_check_resource_availability_default_mask( + self, + resource_id_mock, + redis_mock, + add_new_resource_mock): + """Test the resource availability with default mask""" + resource_id_mock.return_value = 1 + redis_mock.smembers.return_value = [] + test_dataset = mock.MagicMock() + type(test_dataset).type = mock.PropertyMock(return_value="Test") + add_new_resource_mock.return_value = {"default_mask": 2} + self.assertEqual(check_resource_availability(test_dataset), 2) + + @mock.patch('utility.authentication_tools.requests.get') + @mock.patch('utility.authentication_tools.add_new_resource') + @mock.patch('utility.authentication_tools.Redis') + @mock.patch('utility.authentication_tools.g', TestUserSession()) + @mock.patch('utility.authentication_tools.get_resource_id') + def test_check_resource_availability_non_default_mask( + self, + resource_id_mock, + redis_mock, + add_new_resource_mock, + requests_mock): + """Test the resource availability with default mask""" + resource_id_mock.return_value = 1 + redis_mock.smembers.return_value = [] + add_new_resource_mock.return_value = {"default_mask": 2} + requests_mock.return_value = TestResponse() + test_dataset = mock.MagicMock() + type(test_dataset).type = mock.PropertyMock(return_value="Test") + self.assertEqual(check_resource_availability(test_dataset), + ['foo']) + + @mock.patch('utility.authentication_tools.webqtlConfig.SUPER_PRIVILEGES', + "SUPERUSER") + @mock.patch('utility.authentication_tools.requests.get') + @mock.patch('utility.authentication_tools.add_new_resource') + @mock.patch('utility.authentication_tools.Redis') + @mock.patch('utility.authentication_tools.g', TestUserSession()) + @mock.patch('utility.authentication_tools.get_resource_id') + def test_check_resource_availability_of_super_user( + self, + resource_id_mock, + redis_mock, + add_new_resource_mock, + requests_mock): + """Test the resource availability if the user is the super user""" + resource_id_mock.return_value = 1 + redis_mock.smembers.return_value = ["Jane"] + add_new_resource_mock.return_value = {"default_mask": 2} + requests_mock.return_value = TestResponse() + test_dataset = mock.MagicMock() + type(test_dataset).type = mock.PropertyMock(return_value="Test") + self.assertEqual(check_resource_availability(test_dataset), + "SUPERUSER") + + @mock.patch('utility.authentication_tools.webqtlConfig.DEFAULT_PRIVILEGES', + "John Doe") + def test_check_resource_availability_string_dataset(self): + """Test the resource availability if the dataset is a string""" + self.assertEqual(check_resource_availability("Test"), + "John Doe") + + @mock.patch('utility.authentication_tools.webqtlConfig.DEFAULT_PRIVILEGES', + "John Doe") + def test_check_resource_availability_temp(self): + """Test the resource availability if the dataset is a string""" + test_dataset = mock.MagicMock() + type(test_dataset).type = mock.PropertyMock(return_value="Temp") + self.assertEqual(check_resource_availability(test_dataset), + "John Doe") + + +class TestAddNewResource(unittest.TestCase): + """Test cases for add_new_resource method""" + @mock.patch('utility.authentication_tools.webqtlConfig.DEFAULT_PRIVILEGES', + "John Doe") + @mock.patch('utility.authentication_tools.add_resource', mock_add_resource) + @mock.patch('utility.authentication_tools.get_group_code') + def test_add_new_resource_if_publish_datatype(self, group_code_mock): + """Test add_new_resource if dataset type is 'publish'""" + group_code_mock.return_value = "Test" + test_dataset = mock.MagicMock() + type(test_dataset).type = mock.PropertyMock(return_value="Publish") + type(test_dataset).id = mock.PropertyMock(return_value=10) + expected_value = { + "owner_id": "none", + "default_mask": "John Doe", + "group_masks": {}, + "name": "Test_None", + "data": { + "dataset": 10, + "trait": None + }, + "type": "dataset-publish" + } + self.assertEqual(add_new_resource(test_dataset), + expected_value) + + @mock.patch('utility.authentication_tools.webqtlConfig.DEFAULT_PRIVILEGES', + "John Doe") + @mock.patch('utility.authentication_tools.add_resource', mock_add_resource) + @mock.patch('utility.authentication_tools.get_group_code') + def test_add_new_resource_if_geno_datatype(self, group_code_mock): + """Test add_new_resource if dataset type is 'geno'""" + group_code_mock.return_value = "Test" + test_dataset = mock.MagicMock() + type(test_dataset).name = mock.PropertyMock(return_value="Geno") + type(test_dataset).type = mock.PropertyMock(return_value="Geno") + type(test_dataset).id = mock.PropertyMock(return_value=20) + expected_value = { + "owner_id": "none", + "default_mask": "John Doe", + "group_masks": {}, + "name": "Geno", + "data": { + "dataset": 20, + }, + "type": "dataset-geno" + } + self.assertEqual(add_new_resource(test_dataset), + expected_value) + + @mock.patch('utility.authentication_tools.webqtlConfig.DEFAULT_PRIVILEGES', + "John Doe") + @mock.patch('utility.authentication_tools.add_resource', mock_add_resource) + @mock.patch('utility.authentication_tools.get_group_code') + def test_add_new_resource_if_other_datatype(self, group_code_mock): + """Test add_new_resource if dataset type is not 'geno' or 'publish'""" + group_code_mock.return_value = "Test" + test_dataset = mock.MagicMock() + type(test_dataset).name = mock.PropertyMock(return_value="Geno") + type(test_dataset).type = mock.PropertyMock(return_value="other") + type(test_dataset).id = mock.PropertyMock(return_value=20) + expected_value = { + "owner_id": "none", + "default_mask": "John Doe", + "group_masks": {}, + "name": "Geno", + "data": { + "dataset": 20, + }, + "type": "dataset-probeset" + } + self.assertEqual(add_new_resource(test_dataset), + expected_value) diff --git a/wqflask/tests/unit/utility/test_chunks.py b/wqflask/tests/unit/utility/test_chunks.py new file mode 100644 index 00000000..8d90a1ec --- /dev/null +++ b/wqflask/tests/unit/utility/test_chunks.py @@ -0,0 +1,19 @@ +"""Test chunking""" + +import unittest + +from utility.chunks import divide_into_chunks + + +class TestChunks(unittest.TestCase): + "Test Utility method for chunking" + def test_divide_into_chunks(self): + "Check that a list is chunked correctly" + self.assertEqual(divide_into_chunks([1, 2, 7, 3, 22, 8, 5, 22, 333], 3), + [[1, 2, 7], [3, 22, 8], [5, 22, 333]]) + self.assertEqual(divide_into_chunks([1, 2, 7, 3, 22, 8, 5, 22, 333], 4), + [[1, 2, 7], [3, 22, 8], [5, 22, 333]]) + self.assertEqual(divide_into_chunks([1, 2, 7, 3, 22, 8, 5, 22, 333], 5), + [[1, 2], [7, 3], [22, 8], [5, 22], [333]]) + self.assertEqual(divide_into_chunks([], 5), + [[]]) diff --git a/wqflask/tests/unit/utility/test_corestats.py b/wqflask/tests/unit/utility/test_corestats.py new file mode 100644 index 00000000..cf91a248 --- /dev/null +++ b/wqflask/tests/unit/utility/test_corestats.py @@ -0,0 +1,55 @@ +"""Test Core Stats""" + +import unittest + +from utility.corestats import Stats + + +class TestChunks(unittest.TestCase): + "Test Utility method for chunking" + + def setUp(self): + self.stat_test = Stats((x for x in range(1, 11))) + + def test_stats_sum(self): + """ Test sequence sum """ + self.assertEqual(self.stat_test.sum(), 55) + self.stat_test = Stats([]) + self.assertEqual(self.stat_test.sum(), None) + + def test_stats_count(self): + """ Test sequence count """ + self.assertEqual(self.stat_test.count(), 10) + self.stat_test = Stats([]) + self.assertEqual(self.stat_test.count(), 0) + + def test_stats_min(self): + """ Test min value in sequence""" + self.assertEqual(self.stat_test.min(), 1) + self.stat_test = Stats([]) + self.assertEqual(self.stat_test.min(), None) + + def test_stats_max(self): + """ Test max value in sequence """ + self.assertEqual(self.stat_test.max(), 10) + self.stat_test = Stats([]) + self.assertEqual(self.stat_test.max(), None) + + def test_stats_avg(self): + """ Test avg of sequence """ + self.assertEqual(self.stat_test.avg(), 5.5) + self.stat_test = Stats([]) + self.assertEqual(self.stat_test.avg(), None) + + def test_stats_stdev(self): + """ Test standard deviation of sequence """ + self.assertEqual(self.stat_test.stdev(), 3.0276503540974917) + self.stat_test = Stats([]) + self.assertEqual(self.stat_test.stdev(), None) + + def test_stats_percentile(self): + """ Test percentile of sequence """ + self.assertEqual(self.stat_test.percentile(20), 3.0) + self.assertEqual(self.stat_test.percentile(101), None) + self.stat_test = Stats([]) + self.assertEqual(self.stat_test.percentile(20), None) diff --git a/wqflask/tests/unit/utility/test_corr_result_helpers.py b/wqflask/tests/unit/utility/test_corr_result_helpers.py new file mode 100644 index 00000000..e196fbdf --- /dev/null +++ b/wqflask/tests/unit/utility/test_corr_result_helpers.py @@ -0,0 +1,32 @@ +""" Test correlation helper methods """ + +import unittest +from utility.corr_result_helpers import normalize_values, common_keys, normalize_values_with_samples + + +class TestCorrelationHelpers(unittest.TestCase): + """Test methods for normalising lists""" + + def test_normalize_values(self): + """Test that a list is normalised correctly""" + self.assertEqual( + normalize_values([2.3, None, None, 3.2, 4.1, 5], [ + 3.4, 7.2, 1.3, None, 6.2, 4.1]), + ([2.3, 4.1, 5], [3.4, 6.2, 4.1], 3) + ) + + def test_common_keys(self): + """Test that common keys are returned as a list""" + a = dict(BXD1=9.113, BXD2=9.825, BXD14=8.985, BXD15=9.300) + b = dict(BXD1=9.723, BXD3=9.825, BXD14=9.124, BXD16=9.300) + self.assertEqual(sorted(common_keys(a, b)), ['BXD1', 'BXD14']) + + def test_normalize_values_with_samples(self): + """Test that a sample(dict) is normalised correctly""" + self.assertEqual( + normalize_values_with_samples( + dict(BXD1=9.113, BXD2=9.825, BXD14=8.985, + BXD15=9.300, BXD20=9.300), + dict(BXD1=9.723, BXD3=9.825, BXD14=9.124, BXD16=9.300)), + (({'BXD1': 9.113, 'BXD14': 8.985}, {'BXD1': 9.723, 'BXD14': 9.124}, 2)) + ) diff --git a/wqflask/tests/unit/utility/test_formatting.py b/wqflask/tests/unit/utility/test_formatting.py new file mode 100644 index 00000000..9d3033d1 --- /dev/null +++ b/wqflask/tests/unit/utility/test_formatting.py @@ -0,0 +1,33 @@ +import unittest +from utility.formatting import numify, commify + + +class TestFormatting(unittest.TestCase): + """Test formatting numbers by numifying or commifying""" + + def test_numify(self): + "Test that a number is correctly converted to a English readable string" + self.assertEqual(numify(1, 'item', 'items'), + 'one item') + self.assertEqual(numify(2, 'book'), 'two') + self.assertEqual(numify(2, 'book', 'books'), 'two books') + self.assertEqual(numify(0, 'book', 'books'), 'zero books') + self.assertEqual(numify(0), 'zero') + self.assertEqual(numify(5), 'five') + self.assertEqual(numify(14, 'book', 'books'), '14 books') + self.assertEqual(numify(999, 'book', 'books'), '999 books') + self.assertEqual(numify(1000000, 'book', 'books'), '1,000,000 books') + self.assertEqual(numify(1956), '1956') + + def test_commify(self): + "Test that commas are added correctly" + self.assertEqual(commify(1), '1') + self.assertEqual(commify(123), '123') + self.assertEqual(commify(1234), '1234') + self.assertEqual(commify(12345), '12,345') + self.assertEqual(commify(1234567890), '1,234,567,890') + self.assertEqual(commify(123.0), '123.0') + self.assertEqual(commify(1234.5), '1234.5') + self.assertEqual(commify(1234.56789), '1234.56789') + self.assertEqual(commify(123456.789), '123,456.789') + self.assertEqual(commify(None), None) diff --git a/wqflask/tests/unit/utility/test_hmac.py b/wqflask/tests/unit/utility/test_hmac.py new file mode 100644 index 00000000..4e3652f8 --- /dev/null +++ b/wqflask/tests/unit/utility/test_hmac.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +"""Test hmac utility functions""" + +import unittest +from unittest import mock + +from utility.hmac import data_hmac +from utility.hmac import url_for_hmac +from utility.hmac import hmac_creation + + +class TestHmacUtil(unittest.TestCase): + """Test Utility method for hmac creation""" + + @mock.patch("utility.hmac.app.config", {'SECRET_HMAC_CODE': "secret"}) + def test_hmac_creation(self): + """Test hmac creation with a utf-8 string""" + self.assertEqual(hmac_creation("ファイ"), "7410466338cfe109e946") + + @mock.patch("utility.hmac.app.config", + {'SECRET_HMAC_CODE': ('\x08\xdf\xfa\x93N\x80' + '\xd9\\H@\\\x9f`\x98d^' + '\xb4a;\xc6OM\x946a\xbc' + '\xfc\x80:*\xebc')}) + def test_hmac_creation_with_cookie(self): + """Test hmac creation with a cookie""" + cookie = "3f4c1dbf-5b56-4260-87d6-f35445bda37e:af4fcf5eace9e7c864ce" + uuid_, _, signature = cookie.partition(":") + self.assertEqual( + hmac_creation(uuid_), + "af4fcf5eace9e7c864ce") + + @mock.patch("utility.hmac.app.config", {'SECRET_HMAC_CODE': "secret"}) + def test_data_hmac(self): + """Test data_hmac fn with a utf-8 string""" + self.assertEqual(data_hmac("ファイ"), "ファイ:7410466338cfe109e946") + + @mock.patch("utility.hmac.app.config", {'SECRET_HMAC_CODE': "secret"}) + @mock.patch("utility.hmac.url_for") + def test_url_for_hmac_with_plain_url(self, mock_url): + """Test url_for_hmac without params""" + mock_url.return_value = "https://mock_url.com/ファイ/" + self.assertEqual(url_for_hmac("ファイ"), + "https://mock_url.com/ファイ/?hm=05bc39e659b1948f41e7") + + @mock.patch("utility.hmac.app.config", {'SECRET_HMAC_CODE': "secret"}) + @mock.patch("utility.hmac.url_for") + def test_url_for_hmac_with_param_in_url(self, mock_url): + """Test url_for_hmac with params""" + mock_url.return_value = "https://mock_url.com/?ファイ=1" + self.assertEqual(url_for_hmac("ファイ"), + "https://mock_url.com/?ファイ=1&hm=4709c1708270644aed79") diff --git a/wqflask/tests/unit/wqflask/__init__.py b/wqflask/tests/unit/wqflask/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/wqflask/tests/unit/wqflask/api/__init__.py b/wqflask/tests/unit/wqflask/api/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/wqflask/tests/unit/wqflask/api/test_gen_menu.py b/wqflask/tests/unit/wqflask/api/test_gen_menu.py new file mode 100644 index 00000000..84898bd1 --- /dev/null +++ b/wqflask/tests/unit/wqflask/api/test_gen_menu.py @@ -0,0 +1,413 @@ +"""Test cases for wqflask.api.gen_menu""" +import unittest +from unittest import mock + +from wqflask import app +from wqflask.api.gen_menu import gen_dropdown_json +from wqflask.api.gen_menu import get_species +from wqflask.api.gen_menu import get_groups +from wqflask.api.gen_menu import get_types +from wqflask.api.gen_menu import get_datasets +from wqflask.api.gen_menu import phenotypes_exist +from wqflask.api.gen_menu import genotypes_exist +from wqflask.api.gen_menu import build_datasets +from wqflask.api.gen_menu import build_types + + +class TestGenMenu(unittest.TestCase): + """Tests for the gen_menu module""" + + def setUp(self): + self.app_context = app.app_context() + self.app_context.push() + self.test_group = { + 'mouse': [ + ['H_T1', + 'H_T', + 'Family:DescriptionA' + ], + ['H_T2', "H_T'", 'Family:None'] + ], + 'human': [ + ['BXD', 'BXD', 'Family:None'], + ['HLC', 'Liver: Normal Gene Expression with Genotypes (Merck)', + 'Family:Test'] + ] + } + + self.test_type = { + 'mouse': { + 'H_T2': [('Phenotypes', + 'Traits and Cofactors', + 'Phenotypes'), + ('Genotypes', + 'DNA Markers and SNPs', + 'Genotypes'), + ['M', 'M', 'Molecular Trait Datasets']], + 'H_T1': [('Phenotypes', + 'Traits and Cofactors', + 'Phenotypes'), + ('Genotypes', + 'DNA Markers and SNPs', + 'Genotypes'), + ['M', 'M', 'Molecular Trait Datasets']] + }, + 'human': { + 'HLC': [('Phenotypes', + 'Traits and Cofactors', + 'Phenotypes'), + ('Genotypes', + 'DNA Markers and SNPs', + 'Genotypes'), + ['M', 'M', 'Molecular Trait Datasets']], + 'BXD': [('Phenotypes', + 'Traits and Cofactors', + 'Phenotypes'), + ('Genotypes', + 'DNA Markers and SNPs', + 'Genotypes'), + ['M', 'M', 'Molecular Trait Datasets']] + } + } + + def tearDown(self): + self.app_context.pop() + + @mock.patch('wqflask.api.gen_menu.g') + def test_get_species(self, db_mock): + """Test that assertion is raised when dataset and dataset_name + are defined""" + db_mock.db.execute.return_value.fetchall.return_value = ( + ('human', 'Human'), + ('mouse', 'Mouse')) + self.assertEqual(get_species(), + [['human', 'Human'], ['mouse', 'Mouse']]) + db_mock.db.execute.assert_called_once_with( + "SELECT Name, MenuName FROM Species ORDER BY OrderId" + ) + + @mock.patch('wqflask.api.gen_menu.g') + def test_get_groups(self, db_mock): + """Test that species groups are grouped correctly""" + db_mock.db.execute.return_value.fetchall.side_effect = [ + # Mouse + (('BXD', 'BXD', None), + ('HLC', 'Liver: Normal Gene Expression with Genotypes (Merck)', + 'Test')), + # Human + (('H_T1', "H_T", "DescriptionA"), + ('H_T2', "H_T'", None)) + ] + + self.assertEqual(get_groups([["human", "Human"], ["mouse", "Mouse"]]), + self.test_group) + + for name in ["mouse", "human"]: + db_mock.db.execute.assert_any_call( + ("SELECT InbredSet.Name, InbredSet.FullName, " + + "IFNULL(InbredSet.Family, 'None') " + + "FROM InbredSet, Species WHERE Species.Name " + + "= '{}' AND InbredSet.SpeciesId = Species.Id GROUP by " + + "InbredSet.Name ORDER BY IFNULL(InbredSet.FamilyOrder, " + + "InbredSet.FullName) ASC, IFNULL(InbredSet.Family, " + + "InbredSet.FullName) ASC, InbredSet.FullName ASC, " + + "InbredSet.MenuOrderId ASC").format(name) + ) + + @mock.patch('wqflask.api.gen_menu.g') + def test_phenotypes_exist_called_with_correct_query(self, db_mock): + """Test that phenotypes_exist is called with the correct query""" + db_mock.db.execute.return_value.fetchone.return_value = None + phenotypes_exist("test") + db_mock.db.execute.assert_called_with( + "SELECT Name FROM PublishFreeze " + "WHERE PublishFreeze.Name = 'testPublish'" + ) + + @mock.patch('wqflask.api.gen_menu.g') + def test_phenotypes_exist_with_falsy_values(self, db_mock): + """Test that phenotype check returns correctly when given + a None value""" + for x in [None, False, (), [], ""]: + db_mock.db.execute.return_value.fetchone.return_value = x + self.assertFalse(phenotypes_exist("test")) + + @mock.patch('wqflask.api.gen_menu.g') + def test_phenotypes_exist_with_truthy_value(self, db_mock): + """Test that phenotype check returns correctly when given Truthy """ + for x in ["x", ("result"), ["result"], [1]]: + db_mock.db.execute.return_value.fetchone.return_value = (x) + self.assertTrue(phenotypes_exist("test")) + + @mock.patch('wqflask.api.gen_menu.g') + def test_genotypes_exist_called_with_correct_query(self, db_mock): + """Test that genotypes_exist is called with the correct query""" + db_mock.db.execute.return_value.fetchone.return_value = None + genotypes_exist("test") + db_mock.db.execute.assert_called_with( + "SELECT Name FROM GenoFreeze WHERE GenoFreeze.Name = 'testGeno'" + ) + + @mock.patch('wqflask.api.gen_menu.g') + def test_genotypes_exist_with_falsy_values(self, db_mock): + """Test that genotype check returns correctly when given + a None value""" + for x in [None, False, (), [], ""]: + db_mock.db.execute.return_value.fetchone.return_value = x + self.assertFalse(genotypes_exist("test")) + + @mock.patch('wqflask.api.gen_menu.g') + def test_genotypes_exist_with_truthy_value(self, db_mock): + """Test that genotype check returns correctly when given Truthy """ + for x in ["x", ("result"), ["result"], [1]]: + db_mock.db.execute.return_value.fetchone.return_value = (x) + self.assertTrue(phenotypes_exist("test")) + + @mock.patch('wqflask.api.gen_menu.g') + def test_build_datasets_with_type_phenotypes(self, db_mock): + """Test that correct dataset is returned for a phenotype type""" + db_mock.db.execute.return_value.fetchall.return_value = ( + (602, "BXDPublish", "BXD Published Phenotypes"), + ) + self.assertEqual(build_datasets("Mouse", "BXD", "Phenotypes"), + [['602', "BXDPublish", "BXD Published Phenotypes"]]) + db_mock.db.execute.assert_called_with( + "SELECT InfoFiles.GN_AccesionId, PublishFreeze.Name, " + + "PublishFreeze.FullName FROM InfoFiles, PublishFreeze, " + + "InbredSet WHERE InbredSet.Name = 'BXD' AND " + + "PublishFreeze.InbredSetId = InbredSet.Id AND " + + "InfoFiles.InfoPageName = PublishFreeze.Name " + + "ORDER BY PublishFreeze.CreateTime ASC" + ) + self.assertEqual(build_datasets("Mouse", "MDP", "Phenotypes"), + [['602', "BXDPublish", "Mouse Phenome Database"]]) + + db_mock.db.execute.return_value.fetchall.return_value = () + db_mock.db.execute.return_value.fetchone.return_value = ( + "BXDPublish", "Mouse Phenome Database" + ) + self.assertEqual(build_datasets("Mouse", "MDP", "Phenotypes"), + [["None", "BXDPublish", "Mouse Phenome Database"]]) + + @mock.patch('wqflask.api.gen_menu.g') + def test_build_datasets_with_type_phenotypes_and_no_results(self, db_mock): + """Test that correct dataset is returned for a phenotype type with no + results + + """ + db_mock.db.execute.return_value.fetchall.return_value = None + db_mock.db.execute.return_value.fetchone.return_value = (121, + "text value") + self.assertEqual(build_datasets("Mouse", "BXD", "Phenotypes"), + [["None", "121", "text value"]]) + db_mock.db.execute.assert_called_with( + "SELECT PublishFreeze.Name, PublishFreeze.FullName " + "FROM PublishFreeze, InbredSet " + "WHERE InbredSet.Name = 'BXD' AND " + "PublishFreeze.InbredSetId = InbredSet.Id " + "ORDER BY PublishFreeze.CreateTime ASC" + ) + + @mock.patch('wqflask.api.gen_menu.g') + def test_build_datasets_with_type_genotypes(self, db_mock): + """Test that correct dataset is returned for a phenotype type""" + db_mock.db.execute.return_value.fetchone.return_value = ( + 635, "HLCPublish", "HLC Published Genotypes" + ) + + self.assertEqual(build_datasets("Mouse", "HLC", "Genotypes"), + [["635", "HLCGeno", "HLC Genotypes"]]) + db_mock.db.execute.assert_called_with( + "SELECT InfoFiles.GN_AccesionId FROM InfoFiles, " + "GenoFreeze, InbredSet WHERE InbredSet.Name = 'HLC' AND " + "GenoFreeze.InbredSetId = InbredSet.Id AND " + "InfoFiles.InfoPageName = GenoFreeze.ShortName " + + "ORDER BY GenoFreeze.CreateTime DESC" + ) + db_mock.db.execute.return_value.fetchone.return_value = () + self.assertEqual(build_datasets("Mouse", "HLC", "Genotypes"), + [["None", "HLCGeno", "HLC Genotypes"]]) + + @mock.patch('wqflask.api.gen_menu.g') + def test_build_datasets_with_type_mrna(self, db_mock): + """Test that correct dataset is returned for a mRNA + expression/ Probeset""" + db_mock.db.execute.return_value.fetchall.return_value = ( + (112, "HC_M2_0606_P", + "Hippocampus Consortium M430v2 (Jun06) PDNN"), ) + self.assertEqual(build_datasets("Mouse", "HLC", "mRNA"), [[ + "112", 'HC_M2_0606_P', "Hippocampus Consortium M430v2 (Jun06) PDNN" + ]]) + db_mock.db.execute.assert_called_once_with( + "SELECT ProbeSetFreeze.Id, ProbeSetFreeze.Name, " + + "ProbeSetFreeze.FullName FROM ProbeSetFreeze, " + + "ProbeFreeze, InbredSet, Tissue, Species WHERE " + + "Species.Name = 'Mouse' AND Species.Id = " + + "InbredSet.SpeciesId AND InbredSet.Name = 'HLC' AND " + + "ProbeSetFreeze.ProbeFreezeId = ProbeFreeze.Id and " + + "Tissue.Name = 'mRNA' AND ProbeFreeze.TissueId = " + + "Tissue.Id and ProbeFreeze.InbredSetId = InbredSet.Id " + + "ORDER BY ProbeSetFreeze.CreateTime DESC") + + @mock.patch('wqflask.api.gen_menu.build_datasets') + @mock.patch('wqflask.api.gen_menu.g') + def test_build_types(self, db_mock, datasets_mock): + """Test that correct tissue metadata is returned""" + datasets_mock.return_value = [ + ["112", 'HC_M2_0606_P', + "Hippocampus Consortium M430v2 (Jun06) PDNN"] + ] + db_mock.db.execute.return_value.fetchall.return_value = ( + ('Mouse Tissue'), ('Human Tissue'), ('Rat Tissue') + ) + self.assertEqual(build_types('mouse', 'random group'), + [['M', 'M', 'Molecular Traits'], + ['H', 'H', 'Molecular Traits'], + ['R', 'R', 'Molecular Traits']]) + db_mock.db.execute.assert_called_once_with( + "SELECT DISTINCT Tissue.Name " + + "FROM ProbeFreeze, ProbeSetFreeze, InbredSet, " + + "Tissue, Species WHERE Species.Name = 'mouse' " + + "AND Species.Id = InbredSet.SpeciesId AND " + + "InbredSet.Name = 'random group' AND " + + "ProbeFreeze.TissueId = Tissue.Id AND " + + "ProbeFreeze.InbredSetId = InbredSet.Id AND " + + "ProbeSetFreeze.ProbeFreezeId = ProbeFreeze.Id " + + "ORDER BY Tissue.Name" + ) + + @mock.patch('wqflask.api.gen_menu.build_types') + @mock.patch('wqflask.api.gen_menu.genotypes_exist') + @mock.patch('wqflask.api.gen_menu.phenotypes_exist') + def test_get_types_with_existing_genotype_and_phenotypes( + self, + phenotypes_exist_mock, + genotypes_exist_mock, + build_types_mock): + """Test that build types are constructed correctly if phenotypes and genotypes + exist + + """ + phenotypes_exist_mock.return_value = True + genotypes_exist_mock.return_value = True + + expected_result = self.test_type + + build_types_mock.return_value = [ + ['M', 'M', 'Molecular Trait Datasets'] + ] + self.assertEqual(get_types(self.test_group), expected_result) + + @mock.patch('wqflask.api.gen_menu.build_types') + @mock.patch('wqflask.api.gen_menu.genotypes_exist') + @mock.patch('wqflask.api.gen_menu.phenotypes_exist') + def test_get_types_with_buildtype_and_non_existent_genotype_and_phenotypes( + self, + phenotypes_exist_mock, + genotypes_exist_mock, + build_types_mock): + """Test that build types are constructed correctly if phenotypes_exist and + genotypes_exist are false but build_type is falsy + + """ + phenotypes_exist_mock.return_value = False + genotypes_exist_mock.return_value = False + + build_types_mock.return_value = [] + self.assertEqual(get_types(self.test_group), { + 'mouse': {}, + 'human': {} + }) + + @mock.patch('wqflask.api.gen_menu.build_types') + @mock.patch('wqflask.api.gen_menu.genotypes_exist') + @mock.patch('wqflask.api.gen_menu.phenotypes_exist') + def test_get_types_with_non_existent_genotype_phenotypes_and_buildtype( + self, + phenotypes_exist_mock, + genotypes_exist_mock, + build_types_mock): + """Test that build types are constructed correctly if phenotypes_exist, + genotypes_exist and build_types are truthy + + """ + phenotypes_exist_mock.return_value = False + genotypes_exist_mock.return_value = False + + build_types_mock.return_value = [ + ['M', 'M', 'Molecular Trait Datasets'] + ] + expected_result = { + 'mouse': { + 'H_T2': [['M', 'M', 'Molecular Trait Datasets']], + 'H_T1': [['M', 'M', 'Molecular Trait Datasets']]}, + 'human': { + 'HLC': [['M', 'M', 'Molecular Trait Datasets']], + 'BXD': [['M', 'M', 'Molecular Trait Datasets']]}} + self.assertEqual(get_types(self.test_group), + expected_result) + + @mock.patch('wqflask.api.gen_menu.build_datasets') + def test_get_datasets_with_existent_datasets(self, + build_datasets_mock): + """Test correct dataset is returned with existent build_datasets""" + build_datasets_mock.return_value = "Test" + expected_result = { + 'mouse': { + 'H_T2': {'Genotypes': 'Test', + 'M': 'Test', + 'Phenotypes': 'Test'}, + 'H_T1': {'Genotypes': 'Test', + 'M': 'Test', + 'Phenotypes': 'Test'}}, + 'human': {'HLC': {'Genotypes': 'Test', + 'M': 'Test', + 'Phenotypes': 'Test'}, + 'BXD': {'Genotypes': 'Test', + 'M': 'Test', + 'Phenotypes': 'Test'}}} + self.assertEqual(get_datasets(self.test_type), + expected_result) + + @mock.patch('wqflask.api.gen_menu.build_datasets') + def test_get_datasets_with_non_existent_datasets(self, + build_datasets_mock): + """Test correct dataset is returned with non-existent build_datasets""" + build_datasets_mock.return_value = None + expected_result = { + 'mouse': { + 'H_T2': {}, + 'H_T1': {}}, + 'human': {'HLC': {}, + 'BXD': {}}} + self.assertEqual(get_datasets(self.test_type), + expected_result) + + @mock.patch('wqflask.api.gen_menu.get_datasets') + @mock.patch('wqflask.api.gen_menu.get_types') + @mock.patch('wqflask.api.gen_menu.get_groups') + @mock.patch('wqflask.api.gen_menu.get_species') + def test_gen_dropdown_json(self, + species_mock, + groups_mock, + types_mock, + datasets_mock): + "Test that the correct dictionary is constructed properly" + species_mock.return_value = ("speciesA speciesB speciesC speciesD" + .split(" ")) + datasets_mock.return_value = ("datasetA datasetB datasetC datasetD" + .split(" ")) + groups_mock.return_value = ("groupA groupB groupC groupD" + .split(" ")) + types_mock.return_value = ("typeA typeB typeC typeD" + .split(" ")) + datasets_mock.return_value = ("datasetA datasetB datasetC datasetD" + .split(" ")) + + expected_result = { + 'datasets': ['datasetA', 'datasetB', 'datasetC', 'datasetD'], + 'types': ['typeA', 'typeB', 'typeC', 'typeD'], + 'groups': ['groupA', 'groupB', 'groupC', 'groupD'], + 'species': ['speciesA', 'speciesB', 'speciesC', 'speciesD']} + + self.assertEqual(gen_dropdown_json(), expected_result) diff --git a/wqflask/tests/unit/wqflask/marker_regression/__init__.py b/wqflask/tests/unit/wqflask/marker_regression/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/wqflask/tests/unit/wqflask/marker_regression/test_display_mapping_results.py b/wqflask/tests/unit/wqflask/marker_regression/test_display_mapping_results.py new file mode 100644 index 00000000..8ae0f09f --- /dev/null +++ b/wqflask/tests/unit/wqflask/marker_regression/test_display_mapping_results.py @@ -0,0 +1,156 @@ +import unittest + +import htmlgen as HT +from wqflask.marker_regression.display_mapping_results import ( + DisplayMappingResults, + HtmlGenWrapper +) + + +class TestDisplayMappingResults(unittest.TestCase): + """Basic Methods to test Mapping Results""" + def test_pil_colors(self): + """Test that colors use PILLOW color format""" + self.assertEqual(DisplayMappingResults.CLICKABLE_WEBQTL_REGION_COLOR, + (245, 211, 211)) + + +class TestHtmlGenWrapper(unittest.TestCase): + """Test Wrapper around HTMLGen""" + def test_create_image(self): + """Test HT.Image method""" + self.assertEqual( + str(HtmlGenWrapper.create_image_tag(src="test.png", + alt="random", + border="0", + width="10", + height="13", + usemap="#webqtlmap")), + ("""random""") + ) + + def test_create_form(self): + """Test HT.Form method""" + test_form = HtmlGenWrapper.create_form_tag( + cgi="/testing/", + enctype='multipart/form-data', + name="formName", + submit=HtmlGenWrapper.create_input_tag(type_='hidden', name='Default_Name') + ) + test_image = HtmlGenWrapper.create_image_tag( + src="test.png", + alt="random", + border="0", + width="10", + height="13", + usemap="#webqtlmap" + ) + self.assertEqual( + str(test_form).replace("\n", ""), + ("""
""")) + hddn = { + 'FormID': 'showDatabase', + 'ProbeSetID': '_', + 'database': "TestGeno", + 'CellID': '_', + 'RISet': "Test", + 'incparentsf1': 'ON' + } + for key in hddn.keys(): + test_form.append( + HtmlGenWrapper.create_input_tag( + name=key, + value=hddn[key], + type_='hidden')) + test_form.append(test_image) + + self.assertEqual(str(test_form).replace("\n", ""), ( + """
""" + """""" + """""" + """""" + """""" + """""" + """""" + """""" + """random""" + """
""")) + + def test_create_paragraph(self): + """Test HT.Paragraph method""" + test_p_element = HtmlGenWrapper.create_p_tag(id="smallSize") + par_text = ( + "Mapping using genotype data as " + "a trait will result in infinity LRS at one locus. " + "In order to display the result properly, all LRSs " + "higher than 100 are capped at 100." + ) + self.assertEqual( + str(test_p_element), + """

""" + ) + test_p_element.append(HtmlGenWrapper.create_br_tag()) + test_p_element.append(par_text) + self.assertEqual( + str(test_p_element), + """


{}

""".format(par_text) + ) + + def test_create_br_tag(self): + """Test HT.BR() method""" + self.assertEqual(str(HtmlGenWrapper.create_br_tag()), + "
") + + def test_create_input_tag(self): + """Test HT.Input method""" + self.assertEqual( + str(HtmlGenWrapper.create_input_tag( + type_="hidden", + name="name", + value="key", + Class="trait trait_")).replace("\n", ""), + ("""""")) + + def test_create_map_tag(self): + """Test HT.Map method""" + self.assertEqual(str(HtmlGenWrapper.create_map_tag( + name="WebqTLImageMap")).replace("\n", ""), + """""") + gifmap = HtmlGenWrapper.create_map_tag(name="test") + gifmap.append(HtmlGenWrapper.create_area_tag(shape="rect", + coords='1 2 3', href='#area1')) + gifmap.append(HtmlGenWrapper.create_area_tag(shape="rect", + coords='1 2 3', href='#area2')) + self.assertEqual( + str(gifmap).replace("\n", ""), + ("""""" + """""" + """""" + """""")) + + def test_create_area_tag(self): + """Test HT.Area method""" + self.assertEqual( + str(HtmlGenWrapper.create_area_tag( + shape="rect", + coords="1 2", + href="http://test.com", + title="Some Title")).replace("\n", ""), + ("""""")) + + def test_create_link_tag(self): + """Test HT.HREF method""" + self.assertEqual( + str(HtmlGenWrapper.create_link_tag( + "www.test.com", "test", target="_blank")).replace("\n", ""), + """test""") diff --git a/wqflask/tests/unit/wqflask/show_trait/__init__.py b/wqflask/tests/unit/wqflask/show_trait/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/wqflask/tests/unit/wqflask/show_trait/test_export_trait_data.py b/wqflask/tests/unit/wqflask/show_trait/test_export_trait_data.py new file mode 100644 index 00000000..41761944 --- /dev/null +++ b/wqflask/tests/unit/wqflask/show_trait/test_export_trait_data.py @@ -0,0 +1,212 @@ +import unittest +from unittest import mock +from wqflask.show_trait.export_trait_data import dict_to_sorted_list +from wqflask.show_trait.export_trait_data import cmp_samples +from wqflask.show_trait.export_trait_data import export_sample_table +from wqflask.show_trait.export_trait_data import get_export_metadata + + +class AttributesSetter: + def __init__(self, obj): + for key, value in obj.items(): + setattr(self, key, value) + + +class TestExportTraits(unittest.TestCase): + """Test methods related to converting dict to sortedlist""" + @mock.patch("wqflask.show_trait.export_trait_data.create_trait") + @mock.patch("wqflask.show_trait.export_trait_data.data_set") + def test_get_export_metadata_no_publish(self, mock_dataset, mock_trait): + """test for exporting metadata with no publish""" + mock_dataset_attributes = AttributesSetter( + {"type": "no_publish", "dataset_name": "Temp", "name": "Temp"}) + + mock_nested_attributes = AttributesSetter({"name": "name"}) + mock_dataset_attributes.group = mock_nested_attributes + mock_dataset.create_dataset.return_value = mock_dataset_attributes + mock_trait.return_value = AttributesSetter({"symbol": "", "description_display": "Description", + "title": "research1", "journal": "", "authors": ""}) + + results = get_export_metadata("random_id", "Temp") + expected = [["Record ID: random_id"], + ["Trait URL: http://genenetwork.org/show_trait?trait_id=random_id&dataset=Temp"], + ["Dataset: Temp"], + ["Group: name"], []] + + mock_dataset.create_dataset.assert_called_with("Temp") + mock_trait.assert_called_with( + dataset=mock_dataset_attributes, name="random_id", cellid=None, get_qtl_info=False) + self.assertEqual(results, expected) + + @mock.patch("wqflask.show_trait.export_trait_data.create_trait") + @mock.patch("wqflask.show_trait.export_trait_data.data_set") + def test_get_export_metadata_with_publish(self, data_mock, trait_mock): + """test for exporting metadata with dataset.type=Publish""" + mock_dataset_attributes = AttributesSetter({"type": "Publish", "dataset_name": "Temp", + "name": "Temp", "description_display": "Description goes here"}) + + mock_nested_attributes = AttributesSetter({"name": "name"}) + mock_dataset_attributes.group = mock_nested_attributes + data_mock.create_dataset.return_value = mock_dataset_attributes + trait_instance = AttributesSetter({"symbol": "", "description_display": "Description", + "title": "research1", "journal": "", "authors": ""}) + trait_mock.return_value = trait_instance + + results = get_export_metadata( + "29ae0615-0d77-4814-97c7-c9e91f6bfd7b", "Temp") + + expected = [['Phenotype ID: 29ae0615-0d77-4814-97c7-c9e91f6bfd7b'], + ['Phenotype URL: http://genenetwork.org/show_trait?trait_id=29ae0615-0d77-4814-97c7-c9e91f6bfd7b&dataset=Temp'], [ + 'Group: name'], ['Phenotype: Description'], + ['Authors: N/A'], ['Title: research1'], + ['Journal: N/A'], ['Dataset Link: http://gn1.genenetwork.org/webqtl/main.py?FormID=sharinginfo&InfoPageName=Temp'], []] + + self.assertEqual(results, expected) + + @mock.patch("wqflask.show_trait.export_trait_data.dict_to_sorted_list") + @mock.patch("wqflask.show_trait.export_trait_data.get_export_metadata") + def test_export_sample_table(self, exp_metadata, dict_list): + """test for exporting sample table""" + targs_obj = { + "export_data": """{ + "primary_samples": [ + { + "other": "germanotta", + "name": "Sauroniops", + "se":{ + "name":"S2" + }, + "num_cases":{ + "k1":"value" + + } + } + ], + "other_samples": [ + { + "se": 1, + "num_cases": 4, + "value": 6, + "name": 3 + } + ] + }""", + "trait_display_name": "Hair_color", + "trait_id": "23177fdc-312e-4084-ad0c-f3eae785fff5", + "dataset": { + } + } + exp_metadata.return_value = [ + ["Phenotype ID:0a2be192-57f5-400b-bbbd-0cf50135995f"], ['Group:gp1'], + ["Phenotype:p1"], [ + "Authors:N/A"], + ["Title:research1"], + ["Journal:N/A"], + ["Dataset Link: http://gn1.genenetwork.org/webqtl/main.py?FormID=sharinginfo&InfoPageName=name1"], []] + expected = ('Hair_color', + [['Phenotype ID:0a2be192-57f5-400b-bbbd-0cf50135995f'], + ['Group:gp1'], + ['Phenotype:p1'], + ['Authors:N/A'], + ['Title:research1'], + ['Journal:N/A'], + ['Dataset Link: ' + 'http://gn1.genenetwork.org/webqtl/main.py?FormID=sharinginfo&InfoPageName=name1'], + [], + ['Name', 'Value', 'SE', 'N'], + ['Sauroniops', 'germanotta'], + [3, 6, 1, 4]]) + + dict_list.side_effect = [['Sauroniops', 'germanotta'], [3, 6, 1, 4]] + + self.assertEqual(export_sample_table(targs_obj), expected) + exp_metadata.assert_called_with( + "23177fdc-312e-4084-ad0c-f3eae785fff5", {}) + self.assertEqual(dict_list.call_count, 2) + + def test_dict_to_sortedlist(self): + """test for conversion of dict to sorted list""" + sample1 = { + "other": "exp1", + "name": "exp2" + } + sample2 = { + "se": 1, + "num_cases": 4, + "value": 6, + "name": 3 + + } + rever = { + "name": 3, + "value": 6, + "num_cases": 4, + "se": 1 + } + oneItem = { + "item1": "one" + } + + self.assertEqual(["exp2", "exp1"], dict_to_sorted_list(sample1)) + self.assertEqual([3, 6, 1, 4], dict_to_sorted_list(sample2)) + self.assertEqual([3, 6, 1, 4], dict_to_sorted_list(rever)) + self.assertEqual(["one"], dict_to_sorted_list(oneItem)) + """test that the func returns the values not the keys""" + self.assertFalse(["other", "name"] == dict_to_sorted_list(sample1)) + + def test_cmp_samples(self): + """test for comparing samples function""" + sampleA = [ + [ + ("value", "other"), + ("name", "test_name") + ] + ] + sampleB = [ + [ + ("value", "other"), + ("unknown", "test_name") + ] + ] + sampleC = [ + [("other", "value"), + ("name", "value") + ], + [ + ("name", "value"), + ("value", "name") + ], + [ + ("other", "value"), + ("name", "value" + )], + [ + ("name", "name1"), + ("se", "valuex") + ], + [( + "value", "name1"), + ("se", "valuex") + ], + [( + "other", "name1"), + ("se", "valuex" + ) + ], + [( + "name", "name_val"), + ("num_cases", "num_val") + ], + [( + "other_a", "val_a"), + ("other_b", "val" + ) + ] + ] + results = [cmp_samples(val[0], val[1]) for val in sampleA] + resultB = [cmp_samples(val[0], val[1]) for val in sampleB] + resultC = [cmp_samples(val[0], val[1]) for val in sampleC] + + self.assertEqual(1, *results) + self.assertEqual(-1, *resultB) + self.assertEqual([1, -1, 1, -1, -1, 1, -1, -1], resultC) diff --git a/wqflask/tests/unit/wqflask/test_collect.py b/wqflask/tests/unit/wqflask/test_collect.py new file mode 100644 index 00000000..9a36132d --- /dev/null +++ b/wqflask/tests/unit/wqflask/test_collect.py @@ -0,0 +1,73 @@ +"""Test cases for some methods in collect.py""" + +import unittest +from unittest import mock + +from flask import Flask +from wqflask.collect import process_traits + +app = Flask(__name__) + + +class MockSession: + """Helper class for mocking wqflask.collect.g.user_session.logged_in""" + def __init__(self, is_logged_in=False): + self.is_logged_in = is_logged_in + + @property + def logged_in(self): + return self.is_logged_in + + +class MockFlaskG: + """Helper class for mocking wqflask.collect.g.user_session""" + def __init__(self, is_logged_in=False): + self.is_logged_in = is_logged_in + + @property + def user_session(self): + if self.is_logged_in: + return MockSession(is_logged_in=True) + return MockSession() + + +class TestCollect(unittest.TestCase): + + def setUp(self): + self.app_context = app.app_context() + self.app_context.push() + + def tearDown(self): + self.app_context.pop() + + @mock.patch("wqflask.collect.g", MockFlaskG()) + def test_process_traits_with_bytestring(self): + """ + Test that the correct traits are returned when the user is logged + out and bytes are used. + """ + self.assertEqual(process_traits( + b'1452452_at:HC_M2_0606_P:163d04f7db7c9e110de6,' + b'1452447_at:HC_M2_0606_P:eeece8fceb67072debea,' + b'1451401_a_at:HC_M2_0606_P:a043d23b3b3906d8318e,' + b'1429252_at:HC_M2_0606_P:6fa378b349bc9180e8f5'), + set(['1429252_at:HC_M2_0606_P', + '1451401_a_at:HC_M2_0606_P', + '1452447_at:HC_M2_0606_P', + '1452452_at:HC_M2_0606_P'])) + + @mock.patch("wqflask.collect.g", MockFlaskG()) + def test_process_traits_with_normal_string(self): + """ + Test that the correct traits are returned when the user is logged + out and a normal string is used. + """ + self.assertEqual(process_traits( + '1452452_at:HC_M2_0606_P:163d04f7db7c9e110de6,' + '1452447_at:HC_M2_0606_P:eeece8fceb67072debea,' + '1451401_a_at:HC_M2_0606_P:a043d23b3b3906d8318e,' + '1429252_at:HC_M2_0606_P:6fa378b349bc9180e8f5'), + set(['1429252_at:HC_M2_0606_P', + '1451401_a_at:HC_M2_0606_P', + '1452447_at:HC_M2_0606_P', + '1452452_at:HC_M2_0606_P'])) diff --git a/wqflask/tests/unit/wqflask/test_pbkdf2.py b/wqflask/tests/unit/wqflask/test_pbkdf2.py new file mode 100644 index 00000000..a33fbd4f --- /dev/null +++ b/wqflask/tests/unit/wqflask/test_pbkdf2.py @@ -0,0 +1,61 @@ +"""Test cases pbkdf2""" + +import unittest +from wqflask.pbkdf2 import pbkdf2_hex + + +class TestPbkdf2(unittest.TestCase): + def test_pbkdf2_hex(self): + """ + Test pbkdf2_hex function + """ + + for password, salt, iterations, keylen, expected_value in [ + ('password', 'salt', 1, 20, + '0c60c80f961f0e71f3a9b524af6012062fe037a6'), + ('password', 'salt', 2, 20, + 'ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957'), + ('password', 'salt', 4096, 20, + '4b007901b765489abead49d926f721d065a429c1'), + ('passwordPASSWORDpassword', + 'saltSALTsaltSALTsaltSALTsaltSALTsalt', + 4096, 25, + '3d2eec4fe41c849b80c8d83662c0e44a8b291a964cf2f07038'), + ('pass\x00word', 'sa\x00lt', 4096, 16, + '56fa6aa75548099dcc37d7f03425e0c3'), + ('password', 'ATHENA.MIT.EDUraeburn', 1, 16, + 'cdedb5281bb2f801565a1122b2563515'), + ('password', 'ATHENA.MIT.EDUraeburn', 1, 32, + ('cdedb5281bb2f80' + '1565a1122b256351' + '50ad1f7a04bb9f3a33' + '3ecc0e2e1f70837')), + ('password', 'ATHENA.MIT.EDUraeburn', 2, 16, + '01dbee7f4a9e243e988b62c73cda935d'), + ('password', 'ATHENA.MIT.EDUraeburn', 2, 32, + ('01dbee7f4a9e243e9' + '88b62c73cda935da05' + '378b93244ec8f48a99' + 'e61ad799d86')), + ('password', 'ATHENA.MIT.EDUraeburn', 1200, 32, + ('5c08eb61fdf71e' + '4e4ec3cf6ba1f55' + '12ba7e52ddbc5e51' + '42f708a31e2e62b1e13')), + ('X' * 64, 'pass phrase equals block size', 1200, 32, + ('139c30c0966bc32ba' + '55fdbf212530ac9c5' + 'ec59f1a452f5cc9ad' + '940fea0598ed1')), + ('X' * 65, 'pass phrase exceeds block size', 1200, 32, + ('9ccad6d468770cd' + '51b10e6a68721be6' + '11a8b4d282601db3' + 'b36be9246915ec82a')) + ]: + self.assertEqual( + pbkdf2_hex(data=password, + salt=salt, + iterations=iterations, + keylen=keylen), + expected_value) diff --git a/wqflask/tests/unit/wqflask/test_user_login.py b/wqflask/tests/unit/wqflask/test_user_login.py new file mode 100644 index 00000000..61cd9ab9 --- /dev/null +++ b/wqflask/tests/unit/wqflask/test_user_login.py @@ -0,0 +1,21 @@ +"""Test cases for some methods in login.py""" + +import unittest +from wqflask.user_login import encode_password + + +class TestUserLogin(unittest.TestCase): + def test_encode_password(self): + """ + Test encode password + """ + pass_gen_fields = { + "salt": "salt", + "hashfunc": "sha1", + "iterations": 4096, + "keylength": 20, + } + self.assertEqual( + encode_password(pass_gen_fields, + "password").get("password"), + '4b007901b765489abead49d926f721d065a429c1') diff --git a/wqflask/tests/unit/wqflask/test_user_session.py b/wqflask/tests/unit/wqflask/test_user_session.py new file mode 100644 index 00000000..ebb0334a --- /dev/null +++ b/wqflask/tests/unit/wqflask/test_user_session.py @@ -0,0 +1,15 @@ +"""Test cases for some methods in user_session.py""" + +import unittest +from wqflask.user_session import verify_cookie + + +class TestUserSession(unittest.TestCase): + def test_verify_cookie(self): + """ + Test cookie verification + """ + self.assertEqual( + "3f4c1dbf-5b56-4260-87d6-f35445bda37e", + verify_cookie(("3f4c1dbf-5b56-4260-87d6-" + "f35445bda37e:af4fcf5eace9e7c864ce"))) diff --git a/wqflask/tests/utility/__init__.py b/wqflask/tests/utility/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/wqflask/tests/utility/test_authentication_tools.py b/wqflask/tests/utility/test_authentication_tools.py deleted file mode 100644 index 5c391be5..00000000 --- a/wqflask/tests/utility/test_authentication_tools.py +++ /dev/null @@ -1,189 +0,0 @@ -"""Tests for authentication tools""" -import unittest -from unittest import mock - -from utility.authentication_tools import check_resource_availability -from utility.authentication_tools import add_new_resource - - -class TestResponse: - """Mock Test Response after a request""" - @property - def content(self): - """Mock the content from Requests.get(params).content""" - return '["foo"]' - - -class TestUser: - """Mock user""" - @property - def user_id(self): - """Mockes user id. Used in Flask.g.user_session.user_id""" - return "Jane" - - -class TestUserSession: - """Mock user session""" - @property - def user_session(self): - """Mock user session. Mocks Flask.g.user_session object""" - return TestUser() - - -def mock_add_resource(resource_ob, update=False): - return resource_ob - - -class TestCheckResourceAvailability(unittest.TestCase): - """Test methods related to checking the resource availability""" - @mock.patch('utility.authentication_tools.add_new_resource') - @mock.patch('utility.authentication_tools.Redis') - @mock.patch('utility.authentication_tools.g', mock.Mock()) - @mock.patch('utility.authentication_tools.get_resource_id') - def test_check_resource_availability_default_mask( - self, - resource_id_mock, - redis_mock, - add_new_resource_mock): - """Test the resource availability with default mask""" - resource_id_mock.return_value = 1 - redis_mock.smembers.return_value = [] - test_dataset = mock.MagicMock() - type(test_dataset).type = mock.PropertyMock(return_value="Test") - add_new_resource_mock.return_value = {"default_mask": 2} - self.assertEqual(check_resource_availability(test_dataset), 2) - - @mock.patch('utility.authentication_tools.requests.get') - @mock.patch('utility.authentication_tools.add_new_resource') - @mock.patch('utility.authentication_tools.Redis') - @mock.patch('utility.authentication_tools.g', TestUserSession()) - @mock.patch('utility.authentication_tools.get_resource_id') - def test_check_resource_availability_non_default_mask( - self, - resource_id_mock, - redis_mock, - add_new_resource_mock, - requests_mock): - """Test the resource availability with default mask""" - resource_id_mock.return_value = 1 - redis_mock.smembers.return_value = [] - add_new_resource_mock.return_value = {"default_mask": 2} - requests_mock.return_value = TestResponse() - test_dataset = mock.MagicMock() - type(test_dataset).type = mock.PropertyMock(return_value="Test") - self.assertEqual(check_resource_availability(test_dataset), - ['foo']) - - @mock.patch('utility.authentication_tools.webqtlConfig.SUPER_PRIVILEGES', - "SUPERUSER") - @mock.patch('utility.authentication_tools.requests.get') - @mock.patch('utility.authentication_tools.add_new_resource') - @mock.patch('utility.authentication_tools.Redis') - @mock.patch('utility.authentication_tools.g', TestUserSession()) - @mock.patch('utility.authentication_tools.get_resource_id') - def test_check_resource_availability_of_super_user( - self, - resource_id_mock, - redis_mock, - add_new_resource_mock, - requests_mock): - """Test the resource availability if the user is the super user""" - resource_id_mock.return_value = 1 - redis_mock.smembers.return_value = ["Jane"] - add_new_resource_mock.return_value = {"default_mask": 2} - requests_mock.return_value = TestResponse() - test_dataset = mock.MagicMock() - type(test_dataset).type = mock.PropertyMock(return_value="Test") - self.assertEqual(check_resource_availability(test_dataset), - "SUPERUSER") - - @mock.patch('utility.authentication_tools.webqtlConfig.DEFAULT_PRIVILEGES', - "John Doe") - def test_check_resource_availability_string_dataset(self): - """Test the resource availability if the dataset is a string""" - self.assertEqual(check_resource_availability("Test"), - "John Doe") - - @mock.patch('utility.authentication_tools.webqtlConfig.DEFAULT_PRIVILEGES', - "John Doe") - def test_check_resource_availability_temp(self): - """Test the resource availability if the dataset is a string""" - test_dataset = mock.MagicMock() - type(test_dataset).type = mock.PropertyMock(return_value="Temp") - self.assertEqual(check_resource_availability(test_dataset), - "John Doe") - - -class TestAddNewResource(unittest.TestCase): - """Test cases for add_new_resource method""" - @mock.patch('utility.authentication_tools.webqtlConfig.DEFAULT_PRIVILEGES', - "John Doe") - @mock.patch('utility.authentication_tools.add_resource', mock_add_resource) - @mock.patch('utility.authentication_tools.get_group_code') - def test_add_new_resource_if_publish_datatype(self, group_code_mock): - """Test add_new_resource if dataset type is 'publish'""" - group_code_mock.return_value = "Test" - test_dataset = mock.MagicMock() - type(test_dataset).type = mock.PropertyMock(return_value="Publish") - type(test_dataset).id = mock.PropertyMock(return_value=10) - expected_value = { - "owner_id": "none", - "default_mask": "John Doe", - "group_masks": {}, - "name": "Test_None", - "data": { - "dataset": 10, - "trait": None - }, - "type": "dataset-publish" - } - self.assertEqual(add_new_resource(test_dataset), - expected_value) - - @mock.patch('utility.authentication_tools.webqtlConfig.DEFAULT_PRIVILEGES', - "John Doe") - @mock.patch('utility.authentication_tools.add_resource', mock_add_resource) - @mock.patch('utility.authentication_tools.get_group_code') - def test_add_new_resource_if_geno_datatype(self, group_code_mock): - """Test add_new_resource if dataset type is 'geno'""" - group_code_mock.return_value = "Test" - test_dataset = mock.MagicMock() - type(test_dataset).name = mock.PropertyMock(return_value="Geno") - type(test_dataset).type = mock.PropertyMock(return_value="Geno") - type(test_dataset).id = mock.PropertyMock(return_value=20) - expected_value = { - "owner_id": "none", - "default_mask": "John Doe", - "group_masks": {}, - "name": "Geno", - "data": { - "dataset": 20, - }, - "type": "dataset-geno" - } - self.assertEqual(add_new_resource(test_dataset), - expected_value) - - @mock.patch('utility.authentication_tools.webqtlConfig.DEFAULT_PRIVILEGES', - "John Doe") - @mock.patch('utility.authentication_tools.add_resource', mock_add_resource) - @mock.patch('utility.authentication_tools.get_group_code') - def test_add_new_resource_if_other_datatype(self, group_code_mock): - """Test add_new_resource if dataset type is not 'geno' or 'publish'""" - group_code_mock.return_value = "Test" - test_dataset = mock.MagicMock() - type(test_dataset).name = mock.PropertyMock(return_value="Geno") - type(test_dataset).type = mock.PropertyMock(return_value="other") - type(test_dataset).id = mock.PropertyMock(return_value=20) - expected_value = { - "owner_id": "none", - "default_mask": "John Doe", - "group_masks": {}, - "name": "Geno", - "data": { - "dataset": 20, - }, - "type": "dataset-probeset" - } - self.assertEqual(add_new_resource(test_dataset), - expected_value) diff --git a/wqflask/tests/utility/test_chunks.py b/wqflask/tests/utility/test_chunks.py deleted file mode 100644 index 8d90a1ec..00000000 --- a/wqflask/tests/utility/test_chunks.py +++ /dev/null @@ -1,19 +0,0 @@ -"""Test chunking""" - -import unittest - -from utility.chunks import divide_into_chunks - - -class TestChunks(unittest.TestCase): - "Test Utility method for chunking" - def test_divide_into_chunks(self): - "Check that a list is chunked correctly" - self.assertEqual(divide_into_chunks([1, 2, 7, 3, 22, 8, 5, 22, 333], 3), - [[1, 2, 7], [3, 22, 8], [5, 22, 333]]) - self.assertEqual(divide_into_chunks([1, 2, 7, 3, 22, 8, 5, 22, 333], 4), - [[1, 2, 7], [3, 22, 8], [5, 22, 333]]) - self.assertEqual(divide_into_chunks([1, 2, 7, 3, 22, 8, 5, 22, 333], 5), - [[1, 2], [7, 3], [22, 8], [5, 22], [333]]) - self.assertEqual(divide_into_chunks([], 5), - [[]]) diff --git a/wqflask/tests/utility/test_corestats.py b/wqflask/tests/utility/test_corestats.py deleted file mode 100644 index cf91a248..00000000 --- a/wqflask/tests/utility/test_corestats.py +++ /dev/null @@ -1,55 +0,0 @@ -"""Test Core Stats""" - -import unittest - -from utility.corestats import Stats - - -class TestChunks(unittest.TestCase): - "Test Utility method for chunking" - - def setUp(self): - self.stat_test = Stats((x for x in range(1, 11))) - - def test_stats_sum(self): - """ Test sequence sum """ - self.assertEqual(self.stat_test.sum(), 55) - self.stat_test = Stats([]) - self.assertEqual(self.stat_test.sum(), None) - - def test_stats_count(self): - """ Test sequence count """ - self.assertEqual(self.stat_test.count(), 10) - self.stat_test = Stats([]) - self.assertEqual(self.stat_test.count(), 0) - - def test_stats_min(self): - """ Test min value in sequence""" - self.assertEqual(self.stat_test.min(), 1) - self.stat_test = Stats([]) - self.assertEqual(self.stat_test.min(), None) - - def test_stats_max(self): - """ Test max value in sequence """ - self.assertEqual(self.stat_test.max(), 10) - self.stat_test = Stats([]) - self.assertEqual(self.stat_test.max(), None) - - def test_stats_avg(self): - """ Test avg of sequence """ - self.assertEqual(self.stat_test.avg(), 5.5) - self.stat_test = Stats([]) - self.assertEqual(self.stat_test.avg(), None) - - def test_stats_stdev(self): - """ Test standard deviation of sequence """ - self.assertEqual(self.stat_test.stdev(), 3.0276503540974917) - self.stat_test = Stats([]) - self.assertEqual(self.stat_test.stdev(), None) - - def test_stats_percentile(self): - """ Test percentile of sequence """ - self.assertEqual(self.stat_test.percentile(20), 3.0) - self.assertEqual(self.stat_test.percentile(101), None) - self.stat_test = Stats([]) - self.assertEqual(self.stat_test.percentile(20), None) diff --git a/wqflask/tests/utility/test_corr_result_helpers.py b/wqflask/tests/utility/test_corr_result_helpers.py deleted file mode 100644 index e196fbdf..00000000 --- a/wqflask/tests/utility/test_corr_result_helpers.py +++ /dev/null @@ -1,32 +0,0 @@ -""" Test correlation helper methods """ - -import unittest -from utility.corr_result_helpers import normalize_values, common_keys, normalize_values_with_samples - - -class TestCorrelationHelpers(unittest.TestCase): - """Test methods for normalising lists""" - - def test_normalize_values(self): - """Test that a list is normalised correctly""" - self.assertEqual( - normalize_values([2.3, None, None, 3.2, 4.1, 5], [ - 3.4, 7.2, 1.3, None, 6.2, 4.1]), - ([2.3, 4.1, 5], [3.4, 6.2, 4.1], 3) - ) - - def test_common_keys(self): - """Test that common keys are returned as a list""" - a = dict(BXD1=9.113, BXD2=9.825, BXD14=8.985, BXD15=9.300) - b = dict(BXD1=9.723, BXD3=9.825, BXD14=9.124, BXD16=9.300) - self.assertEqual(sorted(common_keys(a, b)), ['BXD1', 'BXD14']) - - def test_normalize_values_with_samples(self): - """Test that a sample(dict) is normalised correctly""" - self.assertEqual( - normalize_values_with_samples( - dict(BXD1=9.113, BXD2=9.825, BXD14=8.985, - BXD15=9.300, BXD20=9.300), - dict(BXD1=9.723, BXD3=9.825, BXD14=9.124, BXD16=9.300)), - (({'BXD1': 9.113, 'BXD14': 8.985}, {'BXD1': 9.723, 'BXD14': 9.124}, 2)) - ) diff --git a/wqflask/tests/utility/test_formatting.py b/wqflask/tests/utility/test_formatting.py deleted file mode 100644 index 9d3033d1..00000000 --- a/wqflask/tests/utility/test_formatting.py +++ /dev/null @@ -1,33 +0,0 @@ -import unittest -from utility.formatting import numify, commify - - -class TestFormatting(unittest.TestCase): - """Test formatting numbers by numifying or commifying""" - - def test_numify(self): - "Test that a number is correctly converted to a English readable string" - self.assertEqual(numify(1, 'item', 'items'), - 'one item') - self.assertEqual(numify(2, 'book'), 'two') - self.assertEqual(numify(2, 'book', 'books'), 'two books') - self.assertEqual(numify(0, 'book', 'books'), 'zero books') - self.assertEqual(numify(0), 'zero') - self.assertEqual(numify(5), 'five') - self.assertEqual(numify(14, 'book', 'books'), '14 books') - self.assertEqual(numify(999, 'book', 'books'), '999 books') - self.assertEqual(numify(1000000, 'book', 'books'), '1,000,000 books') - self.assertEqual(numify(1956), '1956') - - def test_commify(self): - "Test that commas are added correctly" - self.assertEqual(commify(1), '1') - self.assertEqual(commify(123), '123') - self.assertEqual(commify(1234), '1234') - self.assertEqual(commify(12345), '12,345') - self.assertEqual(commify(1234567890), '1,234,567,890') - self.assertEqual(commify(123.0), '123.0') - self.assertEqual(commify(1234.5), '1234.5') - self.assertEqual(commify(1234.56789), '1234.56789') - self.assertEqual(commify(123456.789), '123,456.789') - self.assertEqual(commify(None), None) diff --git a/wqflask/tests/utility/test_hmac.py b/wqflask/tests/utility/test_hmac.py deleted file mode 100644 index 4e3652f8..00000000 --- a/wqflask/tests/utility/test_hmac.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -"""Test hmac utility functions""" - -import unittest -from unittest import mock - -from utility.hmac import data_hmac -from utility.hmac import url_for_hmac -from utility.hmac import hmac_creation - - -class TestHmacUtil(unittest.TestCase): - """Test Utility method for hmac creation""" - - @mock.patch("utility.hmac.app.config", {'SECRET_HMAC_CODE': "secret"}) - def test_hmac_creation(self): - """Test hmac creation with a utf-8 string""" - self.assertEqual(hmac_creation("ファイ"), "7410466338cfe109e946") - - @mock.patch("utility.hmac.app.config", - {'SECRET_HMAC_CODE': ('\x08\xdf\xfa\x93N\x80' - '\xd9\\H@\\\x9f`\x98d^' - '\xb4a;\xc6OM\x946a\xbc' - '\xfc\x80:*\xebc')}) - def test_hmac_creation_with_cookie(self): - """Test hmac creation with a cookie""" - cookie = "3f4c1dbf-5b56-4260-87d6-f35445bda37e:af4fcf5eace9e7c864ce" - uuid_, _, signature = cookie.partition(":") - self.assertEqual( - hmac_creation(uuid_), - "af4fcf5eace9e7c864ce") - - @mock.patch("utility.hmac.app.config", {'SECRET_HMAC_CODE': "secret"}) - def test_data_hmac(self): - """Test data_hmac fn with a utf-8 string""" - self.assertEqual(data_hmac("ファイ"), "ファイ:7410466338cfe109e946") - - @mock.patch("utility.hmac.app.config", {'SECRET_HMAC_CODE': "secret"}) - @mock.patch("utility.hmac.url_for") - def test_url_for_hmac_with_plain_url(self, mock_url): - """Test url_for_hmac without params""" - mock_url.return_value = "https://mock_url.com/ファイ/" - self.assertEqual(url_for_hmac("ファイ"), - "https://mock_url.com/ファイ/?hm=05bc39e659b1948f41e7") - - @mock.patch("utility.hmac.app.config", {'SECRET_HMAC_CODE': "secret"}) - @mock.patch("utility.hmac.url_for") - def test_url_for_hmac_with_param_in_url(self, mock_url): - """Test url_for_hmac with params""" - mock_url.return_value = "https://mock_url.com/?ファイ=1" - self.assertEqual(url_for_hmac("ファイ"), - "https://mock_url.com/?ファイ=1&hm=4709c1708270644aed79") diff --git a/wqflask/tests/wqflask/__init__.py b/wqflask/tests/wqflask/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/wqflask/tests/wqflask/api/__init__.py b/wqflask/tests/wqflask/api/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/wqflask/tests/wqflask/api/test_gen_menu.py b/wqflask/tests/wqflask/api/test_gen_menu.py deleted file mode 100644 index 84898bd1..00000000 --- a/wqflask/tests/wqflask/api/test_gen_menu.py +++ /dev/null @@ -1,413 +0,0 @@ -"""Test cases for wqflask.api.gen_menu""" -import unittest -from unittest import mock - -from wqflask import app -from wqflask.api.gen_menu import gen_dropdown_json -from wqflask.api.gen_menu import get_species -from wqflask.api.gen_menu import get_groups -from wqflask.api.gen_menu import get_types -from wqflask.api.gen_menu import get_datasets -from wqflask.api.gen_menu import phenotypes_exist -from wqflask.api.gen_menu import genotypes_exist -from wqflask.api.gen_menu import build_datasets -from wqflask.api.gen_menu import build_types - - -class TestGenMenu(unittest.TestCase): - """Tests for the gen_menu module""" - - def setUp(self): - self.app_context = app.app_context() - self.app_context.push() - self.test_group = { - 'mouse': [ - ['H_T1', - 'H_T', - 'Family:DescriptionA' - ], - ['H_T2', "H_T'", 'Family:None'] - ], - 'human': [ - ['BXD', 'BXD', 'Family:None'], - ['HLC', 'Liver: Normal Gene Expression with Genotypes (Merck)', - 'Family:Test'] - ] - } - - self.test_type = { - 'mouse': { - 'H_T2': [('Phenotypes', - 'Traits and Cofactors', - 'Phenotypes'), - ('Genotypes', - 'DNA Markers and SNPs', - 'Genotypes'), - ['M', 'M', 'Molecular Trait Datasets']], - 'H_T1': [('Phenotypes', - 'Traits and Cofactors', - 'Phenotypes'), - ('Genotypes', - 'DNA Markers and SNPs', - 'Genotypes'), - ['M', 'M', 'Molecular Trait Datasets']] - }, - 'human': { - 'HLC': [('Phenotypes', - 'Traits and Cofactors', - 'Phenotypes'), - ('Genotypes', - 'DNA Markers and SNPs', - 'Genotypes'), - ['M', 'M', 'Molecular Trait Datasets']], - 'BXD': [('Phenotypes', - 'Traits and Cofactors', - 'Phenotypes'), - ('Genotypes', - 'DNA Markers and SNPs', - 'Genotypes'), - ['M', 'M', 'Molecular Trait Datasets']] - } - } - - def tearDown(self): - self.app_context.pop() - - @mock.patch('wqflask.api.gen_menu.g') - def test_get_species(self, db_mock): - """Test that assertion is raised when dataset and dataset_name - are defined""" - db_mock.db.execute.return_value.fetchall.return_value = ( - ('human', 'Human'), - ('mouse', 'Mouse')) - self.assertEqual(get_species(), - [['human', 'Human'], ['mouse', 'Mouse']]) - db_mock.db.execute.assert_called_once_with( - "SELECT Name, MenuName FROM Species ORDER BY OrderId" - ) - - @mock.patch('wqflask.api.gen_menu.g') - def test_get_groups(self, db_mock): - """Test that species groups are grouped correctly""" - db_mock.db.execute.return_value.fetchall.side_effect = [ - # Mouse - (('BXD', 'BXD', None), - ('HLC', 'Liver: Normal Gene Expression with Genotypes (Merck)', - 'Test')), - # Human - (('H_T1', "H_T", "DescriptionA"), - ('H_T2', "H_T'", None)) - ] - - self.assertEqual(get_groups([["human", "Human"], ["mouse", "Mouse"]]), - self.test_group) - - for name in ["mouse", "human"]: - db_mock.db.execute.assert_any_call( - ("SELECT InbredSet.Name, InbredSet.FullName, " + - "IFNULL(InbredSet.Family, 'None') " + - "FROM InbredSet, Species WHERE Species.Name " + - "= '{}' AND InbredSet.SpeciesId = Species.Id GROUP by " + - "InbredSet.Name ORDER BY IFNULL(InbredSet.FamilyOrder, " + - "InbredSet.FullName) ASC, IFNULL(InbredSet.Family, " + - "InbredSet.FullName) ASC, InbredSet.FullName ASC, " + - "InbredSet.MenuOrderId ASC").format(name) - ) - - @mock.patch('wqflask.api.gen_menu.g') - def test_phenotypes_exist_called_with_correct_query(self, db_mock): - """Test that phenotypes_exist is called with the correct query""" - db_mock.db.execute.return_value.fetchone.return_value = None - phenotypes_exist("test") - db_mock.db.execute.assert_called_with( - "SELECT Name FROM PublishFreeze " - "WHERE PublishFreeze.Name = 'testPublish'" - ) - - @mock.patch('wqflask.api.gen_menu.g') - def test_phenotypes_exist_with_falsy_values(self, db_mock): - """Test that phenotype check returns correctly when given - a None value""" - for x in [None, False, (), [], ""]: - db_mock.db.execute.return_value.fetchone.return_value = x - self.assertFalse(phenotypes_exist("test")) - - @mock.patch('wqflask.api.gen_menu.g') - def test_phenotypes_exist_with_truthy_value(self, db_mock): - """Test that phenotype check returns correctly when given Truthy """ - for x in ["x", ("result"), ["result"], [1]]: - db_mock.db.execute.return_value.fetchone.return_value = (x) - self.assertTrue(phenotypes_exist("test")) - - @mock.patch('wqflask.api.gen_menu.g') - def test_genotypes_exist_called_with_correct_query(self, db_mock): - """Test that genotypes_exist is called with the correct query""" - db_mock.db.execute.return_value.fetchone.return_value = None - genotypes_exist("test") - db_mock.db.execute.assert_called_with( - "SELECT Name FROM GenoFreeze WHERE GenoFreeze.Name = 'testGeno'" - ) - - @mock.patch('wqflask.api.gen_menu.g') - def test_genotypes_exist_with_falsy_values(self, db_mock): - """Test that genotype check returns correctly when given - a None value""" - for x in [None, False, (), [], ""]: - db_mock.db.execute.return_value.fetchone.return_value = x - self.assertFalse(genotypes_exist("test")) - - @mock.patch('wqflask.api.gen_menu.g') - def test_genotypes_exist_with_truthy_value(self, db_mock): - """Test that genotype check returns correctly when given Truthy """ - for x in ["x", ("result"), ["result"], [1]]: - db_mock.db.execute.return_value.fetchone.return_value = (x) - self.assertTrue(phenotypes_exist("test")) - - @mock.patch('wqflask.api.gen_menu.g') - def test_build_datasets_with_type_phenotypes(self, db_mock): - """Test that correct dataset is returned for a phenotype type""" - db_mock.db.execute.return_value.fetchall.return_value = ( - (602, "BXDPublish", "BXD Published Phenotypes"), - ) - self.assertEqual(build_datasets("Mouse", "BXD", "Phenotypes"), - [['602', "BXDPublish", "BXD Published Phenotypes"]]) - db_mock.db.execute.assert_called_with( - "SELECT InfoFiles.GN_AccesionId, PublishFreeze.Name, " + - "PublishFreeze.FullName FROM InfoFiles, PublishFreeze, " + - "InbredSet WHERE InbredSet.Name = 'BXD' AND " + - "PublishFreeze.InbredSetId = InbredSet.Id AND " + - "InfoFiles.InfoPageName = PublishFreeze.Name " + - "ORDER BY PublishFreeze.CreateTime ASC" - ) - self.assertEqual(build_datasets("Mouse", "MDP", "Phenotypes"), - [['602', "BXDPublish", "Mouse Phenome Database"]]) - - db_mock.db.execute.return_value.fetchall.return_value = () - db_mock.db.execute.return_value.fetchone.return_value = ( - "BXDPublish", "Mouse Phenome Database" - ) - self.assertEqual(build_datasets("Mouse", "MDP", "Phenotypes"), - [["None", "BXDPublish", "Mouse Phenome Database"]]) - - @mock.patch('wqflask.api.gen_menu.g') - def test_build_datasets_with_type_phenotypes_and_no_results(self, db_mock): - """Test that correct dataset is returned for a phenotype type with no - results - - """ - db_mock.db.execute.return_value.fetchall.return_value = None - db_mock.db.execute.return_value.fetchone.return_value = (121, - "text value") - self.assertEqual(build_datasets("Mouse", "BXD", "Phenotypes"), - [["None", "121", "text value"]]) - db_mock.db.execute.assert_called_with( - "SELECT PublishFreeze.Name, PublishFreeze.FullName " - "FROM PublishFreeze, InbredSet " - "WHERE InbredSet.Name = 'BXD' AND " - "PublishFreeze.InbredSetId = InbredSet.Id " - "ORDER BY PublishFreeze.CreateTime ASC" - ) - - @mock.patch('wqflask.api.gen_menu.g') - def test_build_datasets_with_type_genotypes(self, db_mock): - """Test that correct dataset is returned for a phenotype type""" - db_mock.db.execute.return_value.fetchone.return_value = ( - 635, "HLCPublish", "HLC Published Genotypes" - ) - - self.assertEqual(build_datasets("Mouse", "HLC", "Genotypes"), - [["635", "HLCGeno", "HLC Genotypes"]]) - db_mock.db.execute.assert_called_with( - "SELECT InfoFiles.GN_AccesionId FROM InfoFiles, " - "GenoFreeze, InbredSet WHERE InbredSet.Name = 'HLC' AND " - "GenoFreeze.InbredSetId = InbredSet.Id AND " - "InfoFiles.InfoPageName = GenoFreeze.ShortName " + - "ORDER BY GenoFreeze.CreateTime DESC" - ) - db_mock.db.execute.return_value.fetchone.return_value = () - self.assertEqual(build_datasets("Mouse", "HLC", "Genotypes"), - [["None", "HLCGeno", "HLC Genotypes"]]) - - @mock.patch('wqflask.api.gen_menu.g') - def test_build_datasets_with_type_mrna(self, db_mock): - """Test that correct dataset is returned for a mRNA - expression/ Probeset""" - db_mock.db.execute.return_value.fetchall.return_value = ( - (112, "HC_M2_0606_P", - "Hippocampus Consortium M430v2 (Jun06) PDNN"), ) - self.assertEqual(build_datasets("Mouse", "HLC", "mRNA"), [[ - "112", 'HC_M2_0606_P', "Hippocampus Consortium M430v2 (Jun06) PDNN" - ]]) - db_mock.db.execute.assert_called_once_with( - "SELECT ProbeSetFreeze.Id, ProbeSetFreeze.Name, " + - "ProbeSetFreeze.FullName FROM ProbeSetFreeze, " + - "ProbeFreeze, InbredSet, Tissue, Species WHERE " + - "Species.Name = 'Mouse' AND Species.Id = " + - "InbredSet.SpeciesId AND InbredSet.Name = 'HLC' AND " + - "ProbeSetFreeze.ProbeFreezeId = ProbeFreeze.Id and " + - "Tissue.Name = 'mRNA' AND ProbeFreeze.TissueId = " + - "Tissue.Id and ProbeFreeze.InbredSetId = InbredSet.Id " + - "ORDER BY ProbeSetFreeze.CreateTime DESC") - - @mock.patch('wqflask.api.gen_menu.build_datasets') - @mock.patch('wqflask.api.gen_menu.g') - def test_build_types(self, db_mock, datasets_mock): - """Test that correct tissue metadata is returned""" - datasets_mock.return_value = [ - ["112", 'HC_M2_0606_P', - "Hippocampus Consortium M430v2 (Jun06) PDNN"] - ] - db_mock.db.execute.return_value.fetchall.return_value = ( - ('Mouse Tissue'), ('Human Tissue'), ('Rat Tissue') - ) - self.assertEqual(build_types('mouse', 'random group'), - [['M', 'M', 'Molecular Traits'], - ['H', 'H', 'Molecular Traits'], - ['R', 'R', 'Molecular Traits']]) - db_mock.db.execute.assert_called_once_with( - "SELECT DISTINCT Tissue.Name " + - "FROM ProbeFreeze, ProbeSetFreeze, InbredSet, " + - "Tissue, Species WHERE Species.Name = 'mouse' " + - "AND Species.Id = InbredSet.SpeciesId AND " + - "InbredSet.Name = 'random group' AND " + - "ProbeFreeze.TissueId = Tissue.Id AND " + - "ProbeFreeze.InbredSetId = InbredSet.Id AND " + - "ProbeSetFreeze.ProbeFreezeId = ProbeFreeze.Id " + - "ORDER BY Tissue.Name" - ) - - @mock.patch('wqflask.api.gen_menu.build_types') - @mock.patch('wqflask.api.gen_menu.genotypes_exist') - @mock.patch('wqflask.api.gen_menu.phenotypes_exist') - def test_get_types_with_existing_genotype_and_phenotypes( - self, - phenotypes_exist_mock, - genotypes_exist_mock, - build_types_mock): - """Test that build types are constructed correctly if phenotypes and genotypes - exist - - """ - phenotypes_exist_mock.return_value = True - genotypes_exist_mock.return_value = True - - expected_result = self.test_type - - build_types_mock.return_value = [ - ['M', 'M', 'Molecular Trait Datasets'] - ] - self.assertEqual(get_types(self.test_group), expected_result) - - @mock.patch('wqflask.api.gen_menu.build_types') - @mock.patch('wqflask.api.gen_menu.genotypes_exist') - @mock.patch('wqflask.api.gen_menu.phenotypes_exist') - def test_get_types_with_buildtype_and_non_existent_genotype_and_phenotypes( - self, - phenotypes_exist_mock, - genotypes_exist_mock, - build_types_mock): - """Test that build types are constructed correctly if phenotypes_exist and - genotypes_exist are false but build_type is falsy - - """ - phenotypes_exist_mock.return_value = False - genotypes_exist_mock.return_value = False - - build_types_mock.return_value = [] - self.assertEqual(get_types(self.test_group), { - 'mouse': {}, - 'human': {} - }) - - @mock.patch('wqflask.api.gen_menu.build_types') - @mock.patch('wqflask.api.gen_menu.genotypes_exist') - @mock.patch('wqflask.api.gen_menu.phenotypes_exist') - def test_get_types_with_non_existent_genotype_phenotypes_and_buildtype( - self, - phenotypes_exist_mock, - genotypes_exist_mock, - build_types_mock): - """Test that build types are constructed correctly if phenotypes_exist, - genotypes_exist and build_types are truthy - - """ - phenotypes_exist_mock.return_value = False - genotypes_exist_mock.return_value = False - - build_types_mock.return_value = [ - ['M', 'M', 'Molecular Trait Datasets'] - ] - expected_result = { - 'mouse': { - 'H_T2': [['M', 'M', 'Molecular Trait Datasets']], - 'H_T1': [['M', 'M', 'Molecular Trait Datasets']]}, - 'human': { - 'HLC': [['M', 'M', 'Molecular Trait Datasets']], - 'BXD': [['M', 'M', 'Molecular Trait Datasets']]}} - self.assertEqual(get_types(self.test_group), - expected_result) - - @mock.patch('wqflask.api.gen_menu.build_datasets') - def test_get_datasets_with_existent_datasets(self, - build_datasets_mock): - """Test correct dataset is returned with existent build_datasets""" - build_datasets_mock.return_value = "Test" - expected_result = { - 'mouse': { - 'H_T2': {'Genotypes': 'Test', - 'M': 'Test', - 'Phenotypes': 'Test'}, - 'H_T1': {'Genotypes': 'Test', - 'M': 'Test', - 'Phenotypes': 'Test'}}, - 'human': {'HLC': {'Genotypes': 'Test', - 'M': 'Test', - 'Phenotypes': 'Test'}, - 'BXD': {'Genotypes': 'Test', - 'M': 'Test', - 'Phenotypes': 'Test'}}} - self.assertEqual(get_datasets(self.test_type), - expected_result) - - @mock.patch('wqflask.api.gen_menu.build_datasets') - def test_get_datasets_with_non_existent_datasets(self, - build_datasets_mock): - """Test correct dataset is returned with non-existent build_datasets""" - build_datasets_mock.return_value = None - expected_result = { - 'mouse': { - 'H_T2': {}, - 'H_T1': {}}, - 'human': {'HLC': {}, - 'BXD': {}}} - self.assertEqual(get_datasets(self.test_type), - expected_result) - - @mock.patch('wqflask.api.gen_menu.get_datasets') - @mock.patch('wqflask.api.gen_menu.get_types') - @mock.patch('wqflask.api.gen_menu.get_groups') - @mock.patch('wqflask.api.gen_menu.get_species') - def test_gen_dropdown_json(self, - species_mock, - groups_mock, - types_mock, - datasets_mock): - "Test that the correct dictionary is constructed properly" - species_mock.return_value = ("speciesA speciesB speciesC speciesD" - .split(" ")) - datasets_mock.return_value = ("datasetA datasetB datasetC datasetD" - .split(" ")) - groups_mock.return_value = ("groupA groupB groupC groupD" - .split(" ")) - types_mock.return_value = ("typeA typeB typeC typeD" - .split(" ")) - datasets_mock.return_value = ("datasetA datasetB datasetC datasetD" - .split(" ")) - - expected_result = { - 'datasets': ['datasetA', 'datasetB', 'datasetC', 'datasetD'], - 'types': ['typeA', 'typeB', 'typeC', 'typeD'], - 'groups': ['groupA', 'groupB', 'groupC', 'groupD'], - 'species': ['speciesA', 'speciesB', 'speciesC', 'speciesD']} - - self.assertEqual(gen_dropdown_json(), expected_result) diff --git a/wqflask/tests/wqflask/marker_regression/__init__.py b/wqflask/tests/wqflask/marker_regression/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/wqflask/tests/wqflask/marker_regression/test_display_mapping_results.py b/wqflask/tests/wqflask/marker_regression/test_display_mapping_results.py deleted file mode 100644 index 8ae0f09f..00000000 --- a/wqflask/tests/wqflask/marker_regression/test_display_mapping_results.py +++ /dev/null @@ -1,156 +0,0 @@ -import unittest - -import htmlgen as HT -from wqflask.marker_regression.display_mapping_results import ( - DisplayMappingResults, - HtmlGenWrapper -) - - -class TestDisplayMappingResults(unittest.TestCase): - """Basic Methods to test Mapping Results""" - def test_pil_colors(self): - """Test that colors use PILLOW color format""" - self.assertEqual(DisplayMappingResults.CLICKABLE_WEBQTL_REGION_COLOR, - (245, 211, 211)) - - -class TestHtmlGenWrapper(unittest.TestCase): - """Test Wrapper around HTMLGen""" - def test_create_image(self): - """Test HT.Image method""" - self.assertEqual( - str(HtmlGenWrapper.create_image_tag(src="test.png", - alt="random", - border="0", - width="10", - height="13", - usemap="#webqtlmap")), - ("""random""") - ) - - def test_create_form(self): - """Test HT.Form method""" - test_form = HtmlGenWrapper.create_form_tag( - cgi="/testing/", - enctype='multipart/form-data', - name="formName", - submit=HtmlGenWrapper.create_input_tag(type_='hidden', name='Default_Name') - ) - test_image = HtmlGenWrapper.create_image_tag( - src="test.png", - alt="random", - border="0", - width="10", - height="13", - usemap="#webqtlmap" - ) - self.assertEqual( - str(test_form).replace("\n", ""), - ("""
""")) - hddn = { - 'FormID': 'showDatabase', - 'ProbeSetID': '_', - 'database': "TestGeno", - 'CellID': '_', - 'RISet': "Test", - 'incparentsf1': 'ON' - } - for key in hddn.keys(): - test_form.append( - HtmlGenWrapper.create_input_tag( - name=key, - value=hddn[key], - type_='hidden')) - test_form.append(test_image) - - self.assertEqual(str(test_form).replace("\n", ""), ( - """
""" - """""" - """""" - """""" - """""" - """""" - """""" - """""" - """random""" - """
""")) - - def test_create_paragraph(self): - """Test HT.Paragraph method""" - test_p_element = HtmlGenWrapper.create_p_tag(id="smallSize") - par_text = ( - "Mapping using genotype data as " - "a trait will result in infinity LRS at one locus. " - "In order to display the result properly, all LRSs " - "higher than 100 are capped at 100." - ) - self.assertEqual( - str(test_p_element), - """

""" - ) - test_p_element.append(HtmlGenWrapper.create_br_tag()) - test_p_element.append(par_text) - self.assertEqual( - str(test_p_element), - """


{}

""".format(par_text) - ) - - def test_create_br_tag(self): - """Test HT.BR() method""" - self.assertEqual(str(HtmlGenWrapper.create_br_tag()), - "
") - - def test_create_input_tag(self): - """Test HT.Input method""" - self.assertEqual( - str(HtmlGenWrapper.create_input_tag( - type_="hidden", - name="name", - value="key", - Class="trait trait_")).replace("\n", ""), - ("""""")) - - def test_create_map_tag(self): - """Test HT.Map method""" - self.assertEqual(str(HtmlGenWrapper.create_map_tag( - name="WebqTLImageMap")).replace("\n", ""), - """""") - gifmap = HtmlGenWrapper.create_map_tag(name="test") - gifmap.append(HtmlGenWrapper.create_area_tag(shape="rect", - coords='1 2 3', href='#area1')) - gifmap.append(HtmlGenWrapper.create_area_tag(shape="rect", - coords='1 2 3', href='#area2')) - self.assertEqual( - str(gifmap).replace("\n", ""), - ("""""" - """""" - """""" - """""")) - - def test_create_area_tag(self): - """Test HT.Area method""" - self.assertEqual( - str(HtmlGenWrapper.create_area_tag( - shape="rect", - coords="1 2", - href="http://test.com", - title="Some Title")).replace("\n", ""), - ("""""")) - - def test_create_link_tag(self): - """Test HT.HREF method""" - self.assertEqual( - str(HtmlGenWrapper.create_link_tag( - "www.test.com", "test", target="_blank")).replace("\n", ""), - """test""") diff --git a/wqflask/tests/wqflask/show_trait/__init__.py b/wqflask/tests/wqflask/show_trait/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/wqflask/tests/wqflask/show_trait/test_export_trait_data.py b/wqflask/tests/wqflask/show_trait/test_export_trait_data.py deleted file mode 100644 index 41761944..00000000 --- a/wqflask/tests/wqflask/show_trait/test_export_trait_data.py +++ /dev/null @@ -1,212 +0,0 @@ -import unittest -from unittest import mock -from wqflask.show_trait.export_trait_data import dict_to_sorted_list -from wqflask.show_trait.export_trait_data import cmp_samples -from wqflask.show_trait.export_trait_data import export_sample_table -from wqflask.show_trait.export_trait_data import get_export_metadata - - -class AttributesSetter: - def __init__(self, obj): - for key, value in obj.items(): - setattr(self, key, value) - - -class TestExportTraits(unittest.TestCase): - """Test methods related to converting dict to sortedlist""" - @mock.patch("wqflask.show_trait.export_trait_data.create_trait") - @mock.patch("wqflask.show_trait.export_trait_data.data_set") - def test_get_export_metadata_no_publish(self, mock_dataset, mock_trait): - """test for exporting metadata with no publish""" - mock_dataset_attributes = AttributesSetter( - {"type": "no_publish", "dataset_name": "Temp", "name": "Temp"}) - - mock_nested_attributes = AttributesSetter({"name": "name"}) - mock_dataset_attributes.group = mock_nested_attributes - mock_dataset.create_dataset.return_value = mock_dataset_attributes - mock_trait.return_value = AttributesSetter({"symbol": "", "description_display": "Description", - "title": "research1", "journal": "", "authors": ""}) - - results = get_export_metadata("random_id", "Temp") - expected = [["Record ID: random_id"], - ["Trait URL: http://genenetwork.org/show_trait?trait_id=random_id&dataset=Temp"], - ["Dataset: Temp"], - ["Group: name"], []] - - mock_dataset.create_dataset.assert_called_with("Temp") - mock_trait.assert_called_with( - dataset=mock_dataset_attributes, name="random_id", cellid=None, get_qtl_info=False) - self.assertEqual(results, expected) - - @mock.patch("wqflask.show_trait.export_trait_data.create_trait") - @mock.patch("wqflask.show_trait.export_trait_data.data_set") - def test_get_export_metadata_with_publish(self, data_mock, trait_mock): - """test for exporting metadata with dataset.type=Publish""" - mock_dataset_attributes = AttributesSetter({"type": "Publish", "dataset_name": "Temp", - "name": "Temp", "description_display": "Description goes here"}) - - mock_nested_attributes = AttributesSetter({"name": "name"}) - mock_dataset_attributes.group = mock_nested_attributes - data_mock.create_dataset.return_value = mock_dataset_attributes - trait_instance = AttributesSetter({"symbol": "", "description_display": "Description", - "title": "research1", "journal": "", "authors": ""}) - trait_mock.return_value = trait_instance - - results = get_export_metadata( - "29ae0615-0d77-4814-97c7-c9e91f6bfd7b", "Temp") - - expected = [['Phenotype ID: 29ae0615-0d77-4814-97c7-c9e91f6bfd7b'], - ['Phenotype URL: http://genenetwork.org/show_trait?trait_id=29ae0615-0d77-4814-97c7-c9e91f6bfd7b&dataset=Temp'], [ - 'Group: name'], ['Phenotype: Description'], - ['Authors: N/A'], ['Title: research1'], - ['Journal: N/A'], ['Dataset Link: http://gn1.genenetwork.org/webqtl/main.py?FormID=sharinginfo&InfoPageName=Temp'], []] - - self.assertEqual(results, expected) - - @mock.patch("wqflask.show_trait.export_trait_data.dict_to_sorted_list") - @mock.patch("wqflask.show_trait.export_trait_data.get_export_metadata") - def test_export_sample_table(self, exp_metadata, dict_list): - """test for exporting sample table""" - targs_obj = { - "export_data": """{ - "primary_samples": [ - { - "other": "germanotta", - "name": "Sauroniops", - "se":{ - "name":"S2" - }, - "num_cases":{ - "k1":"value" - - } - } - ], - "other_samples": [ - { - "se": 1, - "num_cases": 4, - "value": 6, - "name": 3 - } - ] - }""", - "trait_display_name": "Hair_color", - "trait_id": "23177fdc-312e-4084-ad0c-f3eae785fff5", - "dataset": { - } - } - exp_metadata.return_value = [ - ["Phenotype ID:0a2be192-57f5-400b-bbbd-0cf50135995f"], ['Group:gp1'], - ["Phenotype:p1"], [ - "Authors:N/A"], - ["Title:research1"], - ["Journal:N/A"], - ["Dataset Link: http://gn1.genenetwork.org/webqtl/main.py?FormID=sharinginfo&InfoPageName=name1"], []] - expected = ('Hair_color', - [['Phenotype ID:0a2be192-57f5-400b-bbbd-0cf50135995f'], - ['Group:gp1'], - ['Phenotype:p1'], - ['Authors:N/A'], - ['Title:research1'], - ['Journal:N/A'], - ['Dataset Link: ' - 'http://gn1.genenetwork.org/webqtl/main.py?FormID=sharinginfo&InfoPageName=name1'], - [], - ['Name', 'Value', 'SE', 'N'], - ['Sauroniops', 'germanotta'], - [3, 6, 1, 4]]) - - dict_list.side_effect = [['Sauroniops', 'germanotta'], [3, 6, 1, 4]] - - self.assertEqual(export_sample_table(targs_obj), expected) - exp_metadata.assert_called_with( - "23177fdc-312e-4084-ad0c-f3eae785fff5", {}) - self.assertEqual(dict_list.call_count, 2) - - def test_dict_to_sortedlist(self): - """test for conversion of dict to sorted list""" - sample1 = { - "other": "exp1", - "name": "exp2" - } - sample2 = { - "se": 1, - "num_cases": 4, - "value": 6, - "name": 3 - - } - rever = { - "name": 3, - "value": 6, - "num_cases": 4, - "se": 1 - } - oneItem = { - "item1": "one" - } - - self.assertEqual(["exp2", "exp1"], dict_to_sorted_list(sample1)) - self.assertEqual([3, 6, 1, 4], dict_to_sorted_list(sample2)) - self.assertEqual([3, 6, 1, 4], dict_to_sorted_list(rever)) - self.assertEqual(["one"], dict_to_sorted_list(oneItem)) - """test that the func returns the values not the keys""" - self.assertFalse(["other", "name"] == dict_to_sorted_list(sample1)) - - def test_cmp_samples(self): - """test for comparing samples function""" - sampleA = [ - [ - ("value", "other"), - ("name", "test_name") - ] - ] - sampleB = [ - [ - ("value", "other"), - ("unknown", "test_name") - ] - ] - sampleC = [ - [("other", "value"), - ("name", "value") - ], - [ - ("name", "value"), - ("value", "name") - ], - [ - ("other", "value"), - ("name", "value" - )], - [ - ("name", "name1"), - ("se", "valuex") - ], - [( - "value", "name1"), - ("se", "valuex") - ], - [( - "other", "name1"), - ("se", "valuex" - ) - ], - [( - "name", "name_val"), - ("num_cases", "num_val") - ], - [( - "other_a", "val_a"), - ("other_b", "val" - ) - ] - ] - results = [cmp_samples(val[0], val[1]) for val in sampleA] - resultB = [cmp_samples(val[0], val[1]) for val in sampleB] - resultC = [cmp_samples(val[0], val[1]) for val in sampleC] - - self.assertEqual(1, *results) - self.assertEqual(-1, *resultB) - self.assertEqual([1, -1, 1, -1, -1, 1, -1, -1], resultC) diff --git a/wqflask/tests/wqflask/test_collect.py b/wqflask/tests/wqflask/test_collect.py deleted file mode 100644 index 9a36132d..00000000 --- a/wqflask/tests/wqflask/test_collect.py +++ /dev/null @@ -1,73 +0,0 @@ -"""Test cases for some methods in collect.py""" - -import unittest -from unittest import mock - -from flask import Flask -from wqflask.collect import process_traits - -app = Flask(__name__) - - -class MockSession: - """Helper class for mocking wqflask.collect.g.user_session.logged_in""" - def __init__(self, is_logged_in=False): - self.is_logged_in = is_logged_in - - @property - def logged_in(self): - return self.is_logged_in - - -class MockFlaskG: - """Helper class for mocking wqflask.collect.g.user_session""" - def __init__(self, is_logged_in=False): - self.is_logged_in = is_logged_in - - @property - def user_session(self): - if self.is_logged_in: - return MockSession(is_logged_in=True) - return MockSession() - - -class TestCollect(unittest.TestCase): - - def setUp(self): - self.app_context = app.app_context() - self.app_context.push() - - def tearDown(self): - self.app_context.pop() - - @mock.patch("wqflask.collect.g", MockFlaskG()) - def test_process_traits_with_bytestring(self): - """ - Test that the correct traits are returned when the user is logged - out and bytes are used. - """ - self.assertEqual(process_traits( - b'1452452_at:HC_M2_0606_P:163d04f7db7c9e110de6,' - b'1452447_at:HC_M2_0606_P:eeece8fceb67072debea,' - b'1451401_a_at:HC_M2_0606_P:a043d23b3b3906d8318e,' - b'1429252_at:HC_M2_0606_P:6fa378b349bc9180e8f5'), - set(['1429252_at:HC_M2_0606_P', - '1451401_a_at:HC_M2_0606_P', - '1452447_at:HC_M2_0606_P', - '1452452_at:HC_M2_0606_P'])) - - @mock.patch("wqflask.collect.g", MockFlaskG()) - def test_process_traits_with_normal_string(self): - """ - Test that the correct traits are returned when the user is logged - out and a normal string is used. - """ - self.assertEqual(process_traits( - '1452452_at:HC_M2_0606_P:163d04f7db7c9e110de6,' - '1452447_at:HC_M2_0606_P:eeece8fceb67072debea,' - '1451401_a_at:HC_M2_0606_P:a043d23b3b3906d8318e,' - '1429252_at:HC_M2_0606_P:6fa378b349bc9180e8f5'), - set(['1429252_at:HC_M2_0606_P', - '1451401_a_at:HC_M2_0606_P', - '1452447_at:HC_M2_0606_P', - '1452452_at:HC_M2_0606_P'])) diff --git a/wqflask/tests/wqflask/test_pbkdf2.py b/wqflask/tests/wqflask/test_pbkdf2.py deleted file mode 100644 index a33fbd4f..00000000 --- a/wqflask/tests/wqflask/test_pbkdf2.py +++ /dev/null @@ -1,61 +0,0 @@ -"""Test cases pbkdf2""" - -import unittest -from wqflask.pbkdf2 import pbkdf2_hex - - -class TestPbkdf2(unittest.TestCase): - def test_pbkdf2_hex(self): - """ - Test pbkdf2_hex function - """ - - for password, salt, iterations, keylen, expected_value in [ - ('password', 'salt', 1, 20, - '0c60c80f961f0e71f3a9b524af6012062fe037a6'), - ('password', 'salt', 2, 20, - 'ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957'), - ('password', 'salt', 4096, 20, - '4b007901b765489abead49d926f721d065a429c1'), - ('passwordPASSWORDpassword', - 'saltSALTsaltSALTsaltSALTsaltSALTsalt', - 4096, 25, - '3d2eec4fe41c849b80c8d83662c0e44a8b291a964cf2f07038'), - ('pass\x00word', 'sa\x00lt', 4096, 16, - '56fa6aa75548099dcc37d7f03425e0c3'), - ('password', 'ATHENA.MIT.EDUraeburn', 1, 16, - 'cdedb5281bb2f801565a1122b2563515'), - ('password', 'ATHENA.MIT.EDUraeburn', 1, 32, - ('cdedb5281bb2f80' - '1565a1122b256351' - '50ad1f7a04bb9f3a33' - '3ecc0e2e1f70837')), - ('password', 'ATHENA.MIT.EDUraeburn', 2, 16, - '01dbee7f4a9e243e988b62c73cda935d'), - ('password', 'ATHENA.MIT.EDUraeburn', 2, 32, - ('01dbee7f4a9e243e9' - '88b62c73cda935da05' - '378b93244ec8f48a99' - 'e61ad799d86')), - ('password', 'ATHENA.MIT.EDUraeburn', 1200, 32, - ('5c08eb61fdf71e' - '4e4ec3cf6ba1f55' - '12ba7e52ddbc5e51' - '42f708a31e2e62b1e13')), - ('X' * 64, 'pass phrase equals block size', 1200, 32, - ('139c30c0966bc32ba' - '55fdbf212530ac9c5' - 'ec59f1a452f5cc9ad' - '940fea0598ed1')), - ('X' * 65, 'pass phrase exceeds block size', 1200, 32, - ('9ccad6d468770cd' - '51b10e6a68721be6' - '11a8b4d282601db3' - 'b36be9246915ec82a')) - ]: - self.assertEqual( - pbkdf2_hex(data=password, - salt=salt, - iterations=iterations, - keylen=keylen), - expected_value) diff --git a/wqflask/tests/wqflask/test_user_login.py b/wqflask/tests/wqflask/test_user_login.py deleted file mode 100644 index 61cd9ab9..00000000 --- a/wqflask/tests/wqflask/test_user_login.py +++ /dev/null @@ -1,21 +0,0 @@ -"""Test cases for some methods in login.py""" - -import unittest -from wqflask.user_login import encode_password - - -class TestUserLogin(unittest.TestCase): - def test_encode_password(self): - """ - Test encode password - """ - pass_gen_fields = { - "salt": "salt", - "hashfunc": "sha1", - "iterations": 4096, - "keylength": 20, - } - self.assertEqual( - encode_password(pass_gen_fields, - "password").get("password"), - '4b007901b765489abead49d926f721d065a429c1') diff --git a/wqflask/tests/wqflask/test_user_session.py b/wqflask/tests/wqflask/test_user_session.py deleted file mode 100644 index ebb0334a..00000000 --- a/wqflask/tests/wqflask/test_user_session.py +++ /dev/null @@ -1,15 +0,0 @@ -"""Test cases for some methods in user_session.py""" - -import unittest -from wqflask.user_session import verify_cookie - - -class TestUserSession(unittest.TestCase): - def test_verify_cookie(self): - """ - Test cookie verification - """ - self.assertEqual( - "3f4c1dbf-5b56-4260-87d6-f35445bda37e", - verify_cookie(("3f4c1dbf-5b56-4260-87d6-" - "f35445bda37e:af4fcf5eace9e7c864ce"))) diff --git a/wqflask/wqflask/templates/glossary.html b/wqflask/wqflask/templates/glossary.html index 988297d3..80e74ceb 100644 --- a/wqflask/wqflask/templates/glossary.html +++ b/wqflask/wqflask/templates/glossary.html @@ -3,5 +3,5 @@ {% block title %}Glossary{% endblock %} {% block content %} -Test +

Test

{% endblock %} -- cgit v1.2.3 From 390dcc3c46495a8e316df36ceb57dae2089456da Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Tue, 3 Nov 2020 19:14:24 +0300 Subject: Remove encoding header for file In python3 the default encoding is utf-8 so this is redundant. --- wqflask/tests/unit/utility/test_hmac.py | 1 - wqflask/wqflask/views.py | 4 +--- 2 files changed, 1 insertion(+), 4 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/unit/utility/test_hmac.py b/wqflask/tests/unit/utility/test_hmac.py index 4e3652f8..13d6261d 100644 --- a/wqflask/tests/unit/utility/test_hmac.py +++ b/wqflask/tests/unit/utility/test_hmac.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """Test hmac utility functions""" import unittest diff --git a/wqflask/wqflask/views.py b/wqflask/wqflask/views.py index 08673f79..b7c4d142 100644 --- a/wqflask/wqflask/views.py +++ b/wqflask/wqflask/views.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- -# -# Main routing table for GN2 +"""Main routing table for GN2""" import traceback # for error page import os # for error gifs -- cgit v1.2.3 From 4b6d964ccf484225f568361b3bc6136a758cd475 Mon Sep 17 00:00:00 2001 From: Alexanderlacuna Date: Tue, 3 Nov 2020 20:15:39 +0300 Subject: add tests for the get_categorical_variables function --- wqflask/tests/wqflask/show_trait/test_show_trait.py | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/wqflask/show_trait/test_show_trait.py b/wqflask/tests/wqflask/show_trait/test_show_trait.py index ec45d558..f7133292 100644 --- a/wqflask/tests/wqflask/show_trait/test_show_trait.py +++ b/wqflask/tests/wqflask/show_trait/test_show_trait.py @@ -155,7 +155,22 @@ class TestTraits(unittest.TestCase): self.assertEqual(get_categorical_variables(trait, sample_list), []) def test_get_categorical_variables_with_sample_attributes(self): - pass + this_trait=TraitObject({"data":{ + "Gene1":TraitObject({"extra_attributes":{"ex1":"ex1value"}}), + "Gene2":TraitObject({"extra_attributes":{"ex2":"ex2value"}}), + "Gene3":TraitObject({"extra_attributes":{"ex3":"ex3value"}}) + }}) + sample_list=TraitObject({"attributes":{ + "sample_attribute_1":TraitObject({"name":"ex1"}), + "sample_attribute_2":TraitObject({"name":"ex2"}), + "sample_attribute_3":TraitObject({"name":"ex3"}), + "sample_attribute_4":TraitObject({"name":"not_in_extra_attributes"}), + + + }}) + + results=get_categorical_variables(this_trait,sample_list) + self.assertEqual(["ex1","ex2","ex3","not_in_extra_attributes"],results) def test_get_trait_units(self): """test for getting trait units""" -- cgit v1.2.3 From 68f71e11343789266ccac6e079dd0bc1b16d407f Mon Sep 17 00:00:00 2001 From: Alexanderlacuna Date: Tue, 3 Nov 2020 20:23:19 +0300 Subject: add pep8 formatting --- wqflask/tests/wqflask/show_trait/test_show_trait.py | 3 +++ 1 file changed, 3 insertions(+) (limited to 'wqflask/tests') diff --git a/wqflask/tests/wqflask/show_trait/test_show_trait.py b/wqflask/tests/wqflask/show_trait/test_show_trait.py index f7133292..f41b7288 100644 --- a/wqflask/tests/wqflask/show_trait/test_show_trait.py +++ b/wqflask/tests/wqflask/show_trait/test_show_trait.py @@ -155,6 +155,7 @@ class TestTraits(unittest.TestCase): self.assertEqual(get_categorical_variables(trait, sample_list), []) def test_get_categorical_variables_with_sample_attributes(self): + """test for getting categorical variable names with no samples""" this_trait=TraitObject({"data":{ "Gene1":TraitObject({"extra_attributes":{"ex1":"ex1value"}}), "Gene2":TraitObject({"extra_attributes":{"ex2":"ex2value"}}), @@ -169,6 +170,8 @@ class TestTraits(unittest.TestCase): }}) + # + results=get_categorical_variables(this_trait,sample_list) self.assertEqual(["ex1","ex2","ex3","not_in_extra_attributes"],results) -- cgit v1.2.3 From 8630b727d80f52b3e846c9eb3bf7dd4e844fa626 Mon Sep 17 00:00:00 2001 From: Alexanderlacuna Date: Tue, 3 Nov 2020 20:34:00 +0300 Subject: remove unnecessary comments --- .../tests/wqflask/show_trait/test_show_trait.py | 35 +++++++++++----------- 1 file changed, 17 insertions(+), 18 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/wqflask/show_trait/test_show_trait.py b/wqflask/tests/wqflask/show_trait/test_show_trait.py index f41b7288..c617e9f2 100644 --- a/wqflask/tests/wqflask/show_trait/test_show_trait.py +++ b/wqflask/tests/wqflask/show_trait/test_show_trait.py @@ -156,24 +156,23 @@ class TestTraits(unittest.TestCase): def test_get_categorical_variables_with_sample_attributes(self): """test for getting categorical variable names with no samples""" - this_trait=TraitObject({"data":{ - "Gene1":TraitObject({"extra_attributes":{"ex1":"ex1value"}}), - "Gene2":TraitObject({"extra_attributes":{"ex2":"ex2value"}}), - "Gene3":TraitObject({"extra_attributes":{"ex3":"ex3value"}}) - }}) - sample_list=TraitObject({"attributes":{ - "sample_attribute_1":TraitObject({"name":"ex1"}), - "sample_attribute_2":TraitObject({"name":"ex2"}), - "sample_attribute_3":TraitObject({"name":"ex3"}), - "sample_attribute_4":TraitObject({"name":"not_in_extra_attributes"}), - - - }}) - - # - - results=get_categorical_variables(this_trait,sample_list) - self.assertEqual(["ex1","ex2","ex3","not_in_extra_attributes"],results) + this_trait = TraitObject({"data": { + "Gene1": TraitObject({"extra_attributes": {"ex1": "ex1value"}}), + "Gene2": TraitObject({"extra_attributes": {"ex2": "ex2value"}}), + "Gene3": TraitObject({"extra_attributes": {"ex3": "ex3value"}}) + }}) + sample_list = TraitObject({"attributes": { + "sample_attribute_1": TraitObject({"name": "ex1"}), + "sample_attribute_2": TraitObject({"name": "ex2"}), + "sample_attribute_3": TraitObject({"name": "ex3"}), + "sample_attribute_4": TraitObject({"name": "not_in_extra_attributes"}), + + + }}) + + results = get_categorical_variables(this_trait, sample_list) + self.assertEqual( + ["ex1", "ex2", "ex3", "not_in_extra_attributes"], results) def test_get_trait_units(self): """test for getting trait units""" -- cgit v1.2.3 From 74550ef0c76a941c473c8d024ccc0a0403631c49 Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Tue, 3 Nov 2020 22:03:26 +0300 Subject: Add basic structure for "/glossary" routes test --- wqflask/tests/integration/test_markdown_routes.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 wqflask/tests/integration/test_markdown_routes.py (limited to 'wqflask/tests') diff --git a/wqflask/tests/integration/test_markdown_routes.py b/wqflask/tests/integration/test_markdown_routes.py new file mode 100644 index 00000000..5e3e5045 --- /dev/null +++ b/wqflask/tests/integration/test_markdown_routes.py @@ -0,0 +1,21 @@ +"Integration tests for markdown routes" +import unittest + +from bs4 import BeautifulSoup + +from wqflask import app + + +class TestGenMenu(unittest.TestCase): + """Tests for glossary""" + + def setUp(self): + self.app = app.test_client() + + def tearDown(self): + pass + + def test_glossary_page(self): + """Test that the glossary page is rendered properly""" + response = self.app.get('/glossary', follow_redirects=True) + pass -- cgit v1.2.3 From bb46ab063cc86525946563c809a896532d87147a Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Tue, 3 Nov 2020 22:45:44 +0300 Subject: Add basic tests for rendering_markdown * wqflask/tests/unit/wqflask/test_markdown_routes.py: New tests. --- wqflask/tests/unit/wqflask/test_markdown_routes.py | 43 ++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 wqflask/tests/unit/wqflask/test_markdown_routes.py (limited to 'wqflask/tests') diff --git a/wqflask/tests/unit/wqflask/test_markdown_routes.py b/wqflask/tests/unit/wqflask/test_markdown_routes.py new file mode 100644 index 00000000..8b6f7490 --- /dev/null +++ b/wqflask/tests/unit/wqflask/test_markdown_routes.py @@ -0,0 +1,43 @@ +"""Test functions in markdown utils""" + +import unittest +from unittest import mock + +from wqflask.markdown_routes import render_markdown + + +class MockRequests404: + @property + def status_code(): + return 404 + +class MockRequests200: + @property + def status_code(): + return 200 + + @property + def content(): + return """ + # Glossary + + This is some content + + ## Sub-heading + This is another sub-heading + """ + +class TestMarkdownRoutesFunctions(unittest.TestCase): + """Test cases for functions in markdown_routes""" + + @mock.patch('wqflask.markdown_routes.requests.get') + def test_render_markdown(self, requests_mock): + requests_mock.return_value = MockRequests404 + markdown_content = render_markdown("glossary.md") + requests_mock.assert_called_with( + "https://raw.githubusercontent.com" + "/genenetwork/genenetwork2/" + "wqflask/wqflask/static/" + "glossary.md") + self.assertEqual("

Content

\n", + markdown_content) -- cgit v1.2.3 From 3ca276a1e9d3aa29f037696b640c64b2d8629c7f Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Tue, 3 Nov 2020 22:50:52 +0300 Subject: Delete file * wqflask/tests/integration/test_glossary.py: Delete it. Earlier renamed to test_markdown_routes. --- wqflask/tests/integration/test_glossary.py | 28 ---------------------------- 1 file changed, 28 deletions(-) delete mode 100644 wqflask/tests/integration/test_glossary.py (limited to 'wqflask/tests') diff --git a/wqflask/tests/integration/test_glossary.py b/wqflask/tests/integration/test_glossary.py deleted file mode 100644 index c9f1e62a..00000000 --- a/wqflask/tests/integration/test_glossary.py +++ /dev/null @@ -1,28 +0,0 @@ -"Integration tests for glossary" -import unittest - -from bs4 import BeautifulSoup - -from wqflask import app - - -class TestGenMenu(unittest.TestCase): - """Tests for glossary""" - - def setUp(self): - self.app = app.test_client() - - def tearDown(self): - pass - - def test_glossary_page(self): - """Test that the glossary page is rendered properly""" - response = self.app.get('/glossary', follow_redirects=True) - html_content = BeautifulSoup(response.data, "lxml") - self.assertEqual(html_content.find("title").get_text(), - "Glossary GeneNetwork 2") - self.assertEqual( - html_content.find( - 'p', - attrs={'id': 'mytest'}).get_text(), - "Test") -- cgit v1.2.3 From 5f6756f05baeeb6be34a079726d0df749a0557ec Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Tue, 3 Nov 2020 23:04:53 +0300 Subject: Fix false-positive tests * wqflask/tests/unit/wqflask/test_markdown_routes.py: (MockRequests404): Pass self in all properties. (MockRequests200): Ditto. (test_render_markdown): Rename to test_render_markdown_when_fetching_locally. (test_render_markdown_when_fetching_remotely): New test. --- wqflask/tests/unit/wqflask/test_markdown_routes.py | 37 +++++++++++++++------- 1 file changed, 26 insertions(+), 11 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/unit/wqflask/test_markdown_routes.py b/wqflask/tests/unit/wqflask/test_markdown_routes.py index 8b6f7490..3de14276 100644 --- a/wqflask/tests/unit/wqflask/test_markdown_routes.py +++ b/wqflask/tests/unit/wqflask/test_markdown_routes.py @@ -8,31 +8,30 @@ from wqflask.markdown_routes import render_markdown class MockRequests404: @property - def status_code(): + def status_code(self): return 404 class MockRequests200: @property - def status_code(): + def status_code(self): return 200 @property - def content(): - return """ - # Glossary + def content(self): + return b""" +# Glossary +This is some content - This is some content - - ## Sub-heading - This is another sub-heading +## Sub-heading +This is another sub-heading """ class TestMarkdownRoutesFunctions(unittest.TestCase): """Test cases for functions in markdown_routes""" @mock.patch('wqflask.markdown_routes.requests.get') - def test_render_markdown(self, requests_mock): - requests_mock.return_value = MockRequests404 + def test_render_markdown_when_fetching_locally(self, requests_mock): + requests_mock.return_value = MockRequests404() markdown_content = render_markdown("glossary.md") requests_mock.assert_called_with( "https://raw.githubusercontent.com" @@ -41,3 +40,19 @@ class TestMarkdownRoutesFunctions(unittest.TestCase): "glossary.md") self.assertEqual("

Content

\n", markdown_content) + + @mock.patch('wqflask.markdown_routes.requests.get') + def test_render_markdown_when_fetching_remotely(self, requests_mock): + requests_mock.return_value = MockRequests200() + markdown_content = render_markdown("glossary.md") + requests_mock.assert_called_with( + "https://raw.githubusercontent.com" + "/genenetwork/genenetwork2/" + "wqflask/wqflask/static/" + "glossary.md") + self.assertEqual("""

Glossary

+

This is some content

+

Sub-heading

+

This is another sub-heading

+""", + markdown_content) -- cgit v1.2.3 From 23915d8102b8a05930cf3fd16d651a460ebd2f58 Mon Sep 17 00:00:00 2001 From: Alexanderlacuna Date: Wed, 4 Nov 2020 09:49:13 +0300 Subject: remove whitespace and assertIs --- .../tests/wqflask/show_trait/test_show_trait.py | 30 ++++++++++++---------- 1 file changed, 17 insertions(+), 13 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/wqflask/show_trait/test_show_trait.py b/wqflask/tests/wqflask/show_trait/test_show_trait.py index c617e9f2..04c68045 100644 --- a/wqflask/tests/wqflask/show_trait/test_show_trait.py +++ b/wqflask/tests/wqflask/show_trait/test_show_trait.py @@ -2,11 +2,15 @@ import unittest from unittest import mock from wqflask import app -from wqflask.show_trait.show_trait import (check_if_attr_exists, get_ncbi_summary, - has_num_cases, get_table_widths, - get_categorical_variables, - get_trait_units, get_nearest_marker, get_genotype_scales, requests) - +from wqflask.show_trait.show_trait import check_if_attr_exists +from wqflask.show_trait.show_trait import get_ncbi_summary +from wqflask.show_trait.show_trait import has_num_cases +from wqflask.show_trait.show_trait import get_table_widths +from wqflask.show_trait.show_trait import get_categorical_variables +from wqflask.show_trait.show_trait import get_trait_units +from wqflask.show_trait.show_trait import get_nearest_marker +from wqflask.show_trait.show_trait import get_genotype_scales +from wqflask.show_trait.show_trait import requests class TraitObject: def __init__(self, obj): @@ -29,8 +33,8 @@ class TestTraits(unittest.TestCase): results = check_if_attr_exists(trait_obj, "id_type") result2 = check_if_attr_exists(trait_obj2, "sample_name") self.assertIsInstance(trait_obj, TraitObject) - self.assertIs(results, True) - self.assertIs(result2, True) + self.assertTrue(results) + self.assertTrue(result2) def test_check_if_attr_exists_empty_attr(self): """test if attributes exists with false return""" @@ -38,14 +42,14 @@ class TestTraits(unittest.TestCase): trait_obj2 = TraitObject({"group": None}) result = check_if_attr_exists(trait_obj, "sample") result2 = check_if_attr_exists(trait_obj, "group") - self.assertIs(result, False) - self.assertIs(result2, False) + self.assertFalse(result) + self.assertFalse(result2) def test_check_if_attr_exists_falsey(self): """check if attribute exists with empty attributes""" trait_obj = TraitObject({}) results = check_if_attr_exists(trait_obj, "any") - self.assertIs(results, False) + self.assertFalse(results) @mock.patch("wqflask.show_trait.show_trait.requests.get") @mock.patch("wqflask.show_trait.show_trait.check_if_attr_exists") @@ -97,7 +101,7 @@ class TestTraits(unittest.TestCase): create_dataset = TraitObject({"type": "ProbeSet"}) create_trait = TraitObject({"dataset": create_dataset}) - self.assertIs(has_num_cases(create_trait), False) + self.assertFalse(has_num_cases(create_trait)) def test_hash_num_cases_no_probeset(self): """test for hash num cases with dataset.type not Probeset""" @@ -123,8 +127,8 @@ class TestTraits(unittest.TestCase): results = has_num_cases(create_trait) - self.assertIs(has_num_cases(create_trait), True) - self.assertIs(has_num_cases(create_trait2), False) + self.assertTrue(has_num_cases(create_trait)) + self.assertFalse(has_num_cases(create_trait2)) def test_get_table_widths(self): """test for getting table widths""" -- cgit v1.2.3 From 9d2134202c0435ad4a18e0ac74ce4a99508f1a76 Mon Sep 17 00:00:00 2001 From: Alexanderlacuna Date: Wed, 4 Nov 2020 09:57:35 +0300 Subject: remove whitespace --- wqflask/tests/wqflask/show_trait/test_show_trait.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/wqflask/show_trait/test_show_trait.py b/wqflask/tests/wqflask/show_trait/test_show_trait.py index 04c68045..f82a4c04 100644 --- a/wqflask/tests/wqflask/show_trait/test_show_trait.py +++ b/wqflask/tests/wqflask/show_trait/test_show_trait.py @@ -3,7 +3,7 @@ import unittest from unittest import mock from wqflask import app from wqflask.show_trait.show_trait import check_if_attr_exists -from wqflask.show_trait.show_trait import get_ncbi_summary +from wqflask.show_trait.show_trait import get_ncbi_summary from wqflask.show_trait.show_trait import has_num_cases from wqflask.show_trait.show_trait import get_table_widths from wqflask.show_trait.show_trait import get_categorical_variables @@ -12,6 +12,7 @@ from wqflask.show_trait.show_trait import get_nearest_marker from wqflask.show_trait.show_trait import get_genotype_scales from wqflask.show_trait.show_trait import requests + class TraitObject: def __init__(self, obj): for key, value in obj.items(): @@ -169,9 +170,7 @@ class TestTraits(unittest.TestCase): "sample_attribute_1": TraitObject({"name": "ex1"}), "sample_attribute_2": TraitObject({"name": "ex2"}), "sample_attribute_3": TraitObject({"name": "ex3"}), - "sample_attribute_4": TraitObject({"name": "not_in_extra_attributes"}), - - + "sample_attribute_4": TraitObject({"name": "not_in_extra_attributes"}) }}) results = get_categorical_variables(this_trait, sample_list) -- cgit v1.2.3 From 1ef7c3cd7bc148bac8a6b47f62ba02c3819bf1f3 Mon Sep 17 00:00:00 2001 From: Alexanderlacuna Date: Wed, 4 Nov 2020 10:08:32 +0300 Subject: remove whitespace in line 119-120 --- wqflask/tests/wqflask/show_trait/test_show_trait.py | 2 -- 1 file changed, 2 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/wqflask/show_trait/test_show_trait.py b/wqflask/tests/wqflask/show_trait/test_show_trait.py index f82a4c04..70061e2d 100644 --- a/wqflask/tests/wqflask/show_trait/test_show_trait.py +++ b/wqflask/tests/wqflask/show_trait/test_show_trait.py @@ -117,8 +117,6 @@ class TestTraits(unittest.TestCase): "nm1": TraitObject({"num_cases": False}), "nm2": TraitObject({"num_cases": False}), "nm3": TraitObject({"num_cases": False}) - - } create_trait = TraitObject( -- cgit v1.2.3 From f90e77fab78c4504ac9dabb188459ab5d03ac287 Mon Sep 17 00:00:00 2001 From: Alexanderlacuna Date: Wed, 4 Nov 2020 10:15:05 +0300 Subject: remove extra whitespace --- wqflask/tests/wqflask/show_trait/test_show_trait.py | 21 --------------------- 1 file changed, 21 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/wqflask/show_trait/test_show_trait.py b/wqflask/tests/wqflask/show_trait/test_show_trait.py index 70061e2d..ce850c8b 100644 --- a/wqflask/tests/wqflask/show_trait/test_show_trait.py +++ b/wqflask/tests/wqflask/show_trait/test_show_trait.py @@ -67,11 +67,8 @@ class TestTraits(unittest.TestCase): } } """ - get_return_obj = TraitObject({"content": content_json_string}) - mock_get.return_value = get_return_obj - results = get_ncbi_summary(trait) mock_exists.assert_called_once() mock_get.assert_called_once_with(f"http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=gene&id={trait.geneid}&retmode=json") @@ -93,7 +90,6 @@ class TestTraits(unittest.TestCase): } } """ - results = get_ncbi_summary(trait) self.assertEqual(results, None) @@ -101,13 +97,11 @@ class TestTraits(unittest.TestCase): """test for hash num_cases with dataset.type set to Probeset""" create_dataset = TraitObject({"type": "ProbeSet"}) create_trait = TraitObject({"dataset": create_dataset}) - self.assertFalse(has_num_cases(create_trait)) def test_hash_num_cases_no_probeset(self): """test for hash num cases with dataset.type not Probeset""" create_dataset = TraitObject({"type": "Temp"}) - construct_data = { "nm1": TraitObject({"num_cases": False}), "nm2": TraitObject({"num_cases": True}), @@ -125,7 +119,6 @@ class TestTraits(unittest.TestCase): {"dataset": create_dataset, "data": construct_data2}) results = has_num_cases(create_trait) - self.assertTrue(has_num_cases(create_trait)) self.assertFalse(has_num_cases(create_trait2)) @@ -144,7 +137,6 @@ class TestTraits(unittest.TestCase): expected_with_numcase = (450, "750px") expected_no_numcase = (450, "670px") expected_one_sample = (250, "540px") - self.assertEqual(results_with_numcase, expected_with_numcase) self.assertEqual(result_no_numcase, expected_no_numcase) self.assertEqual(results_one_sample, @@ -154,7 +146,6 @@ class TestTraits(unittest.TestCase): """test for getting categorical variable names with no samples""" trait = TraitObject({}) sample_list = TraitObject({"se_exists": True, "attributes": []}) - self.assertEqual(get_categorical_variables(trait, sample_list), []) def test_get_categorical_variables_with_sample_attributes(self): @@ -179,9 +170,7 @@ class TestTraits(unittest.TestCase): """test for getting trait units""" trait = TraitObject( {"description_fmt": "[this is a description] another test [N/A]"}) - trait_no_unit_type = TraitObject({"description_fmt": ""}) - results = get_trait_units(trait) results_no_unit = get_trait_units(trait_no_unit_type) self.assertEqual(results, "this is a descriptionN/A") @@ -195,13 +184,9 @@ class TestTraits(unittest.TestCase): ["Geno1", "Geno2"], ["Geno3"]] trait = TraitObject({"locus_chr": "test_chr", "locus_mb": "test_mb"}) - group_name = TraitObject({"name": "group_name"}) - this_db = TraitObject({"group": group_name}) - results_with_item_db = get_nearest_marker(trait, this_db) - called_with_value = """SELECT Geno.Name FROM Geno, GenoXRef, GenoFreeze WHERE Geno.Chr = 'test_chr' AND @@ -218,11 +203,9 @@ class TestTraits(unittest.TestCase): def test_get_nearest_marker_empty_db(self, mock_db): """test for getting nearest marker with empty db""" mock_db.db.execute.return_value.fetchall.return_value = [] - trait = TraitObject({"locus_chr": "test_chr", "locus_mb": "test_mb"}) group_name = TraitObject({"name": "group_name"}) this_db = TraitObject({"group": group_name}) - results_empty_db = get_nearest_marker(trait, this_db) mock_db.db.execute.assert_called_once() self.assertEqual(results_empty_db, "") @@ -240,7 +223,6 @@ class TestTraits(unittest.TestCase): [["physic", "Mb"]]] results = get_genotype_scales(genofiles_list) - expected_results = { "~/data/files/f1": [["morgan", "cM"]], "~/data/files/f2": [["morgan", "cM"]], @@ -249,7 +231,6 @@ class TestTraits(unittest.TestCase): multiple_calls = [mock.call('~/data/files/f1'), mock.call('~/data/files/f2'), mock.call('~/data/files/f3')] - mock_get_scales.assert_has_calls(multiple_calls) self.assertEqual(results, expected_results) @@ -258,8 +239,6 @@ class TestTraits(unittest.TestCase): """test for getting genotype scales with genofile as a string""" file_location = "~/another_file_location" mock_get_scales.return_value = [["physic", "Mb"]] - expected_results = {f"{file_location}": [["physic", "Mb"]]} - self.assertEqual(get_genotype_scales(file_location), expected_results) mock_get_scales.assert_called_once_with(file_location) -- cgit v1.2.3 From 3f08f54fe3d42eca0ccf98831e4e339defa17720 Mon Sep 17 00:00:00 2001 From: Alexanderlacuna Date: Wed, 4 Nov 2020 10:25:50 +0300 Subject: correct a typo --- wqflask/tests/wqflask/show_trait/test_show_trait.py | 2 -- 1 file changed, 2 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/wqflask/show_trait/test_show_trait.py b/wqflask/tests/wqflask/show_trait/test_show_trait.py index ce850c8b..24150738 100644 --- a/wqflask/tests/wqflask/show_trait/test_show_trait.py +++ b/wqflask/tests/wqflask/show_trait/test_show_trait.py @@ -112,7 +112,6 @@ class TestTraits(unittest.TestCase): "nm2": TraitObject({"num_cases": False}), "nm3": TraitObject({"num_cases": False}) } - create_trait = TraitObject( {"dataset": create_dataset, "data": construct_data}) create_trait2 = TraitObject( @@ -161,7 +160,6 @@ class TestTraits(unittest.TestCase): "sample_attribute_3": TraitObject({"name": "ex3"}), "sample_attribute_4": TraitObject({"name": "not_in_extra_attributes"}) }}) - results = get_categorical_variables(this_trait, sample_list) self.assertEqual( ["ex1", "ex2", "ex3", "not_in_extra_attributes"], results) -- cgit v1.2.3 From fa852e4a293735215e10bff9198c812fb85912ce Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Wed, 4 Nov 2020 18:04:48 +0300 Subject: Update test_markdown_routes * wqflask/tests/unit/wqflask/test_markdown_routes.py (test_render_markdown_when_fetching_locally): Fix failing test. --- wqflask/tests/unit/wqflask/test_markdown_routes.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/unit/wqflask/test_markdown_routes.py b/wqflask/tests/unit/wqflask/test_markdown_routes.py index 3de14276..3adf63e5 100644 --- a/wqflask/tests/unit/wqflask/test_markdown_routes.py +++ b/wqflask/tests/unit/wqflask/test_markdown_routes.py @@ -38,8 +38,8 @@ class TestMarkdownRoutesFunctions(unittest.TestCase): "/genenetwork/genenetwork2/" "wqflask/wqflask/static/" "glossary.md") - self.assertEqual("

Content

\n", - markdown_content) + self.assertRegexpMatches(markdown_content, + "Glossary of Terms and Features") @mock.patch('wqflask.markdown_routes.requests.get') def test_render_markdown_when_fetching_remotely(self, requests_mock): -- cgit v1.2.3 From 6b4bcc526c27a17f96704b54fbfa6a506b3a22f9 Mon Sep 17 00:00:00 2001 From: Alexanderlacuna Date: Thu, 5 Nov 2020 22:30:33 +0300 Subject: add test for samplelist and show_trait --- wqflask/tests/wqflask/show_trait/testSampleList.py | 18 +++++++ .../tests/wqflask/show_trait/test_show_trait.py | 55 ++++++++++++++++++++++ 2 files changed, 73 insertions(+) create mode 100644 wqflask/tests/wqflask/show_trait/testSampleList.py (limited to 'wqflask/tests') diff --git a/wqflask/tests/wqflask/show_trait/testSampleList.py b/wqflask/tests/wqflask/show_trait/testSampleList.py new file mode 100644 index 00000000..4cc8c4da --- /dev/null +++ b/wqflask/tests/wqflask/show_trait/testSampleList.py @@ -0,0 +1,18 @@ +import unittest +import re +from unittest import mock +from wqflask.show_trait.SampleList import natural_sort + + +class TestSampleList(unittest.TestCase): + def test_natural_sort(self): + "Sort the list into natural alphanumeric order." + + characters_list = ["z", "f", "q", "s", "t", "a", "g"] + names_list = ["temp1", "publish", "Sample", "Dataset"] + + natural_sort(characters_list) + natural_sort(names_list) + + self.assertEqual(characters_list, ["a", "f", "g", "q", "s", "t", "z"]) + self.assertEqual(names_list, ["Dataset", "Sample", "publish", "temp1"]) diff --git a/wqflask/tests/wqflask/show_trait/test_show_trait.py b/wqflask/tests/wqflask/show_trait/test_show_trait.py index 24150738..b1a91bbe 100644 --- a/wqflask/tests/wqflask/show_trait/test_show_trait.py +++ b/wqflask/tests/wqflask/show_trait/test_show_trait.py @@ -11,6 +11,7 @@ from wqflask.show_trait.show_trait import get_trait_units from wqflask.show_trait.show_trait import get_nearest_marker from wqflask.show_trait.show_trait import get_genotype_scales from wqflask.show_trait.show_trait import requests +from wqflask.show_trait.show_trait import get_scales_from_genofile class TraitObject: @@ -240,3 +241,57 @@ class TestTraits(unittest.TestCase): expected_results = {f"{file_location}": [["physic", "Mb"]]} self.assertEqual(get_genotype_scales(file_location), expected_results) mock_get_scales.assert_called_once_with(file_location) + + @mock.patch("wqflask.show_trait.show_trait.locate_ignore_error") + def test_get_scales_from_genofile_found(self, mock_location_ignore): + # test no complete to be continued with + # a .geno file + mock_location_ignore.return_value = True + mock_file_with_one_line = mock.mock_open( + read_data="Some data from opened file") + + mock_file = """#@scale and random data:is here_returned\n + This is second with spaced with tabs\n """ + mock_file_result = mock.mock_open(read_data=mock_file) + + with mock.patch("builtins.open", mock_file_with_one_line): + result = get_scales_from_genofile("~/data/file") + self.assertEqual(result, [['morgan', 'cM']]) + + with mock.patch("builtins.open", mock_file_result): + results = get_scales_from_genofile("~data/file_geno") + self.assertEqual(results, [['physic', 'Mb']]) + + @mock.patch("wqflask.show_trait.show_trait.locate_ignore_error") + def test_get_scales_from_genofile_found(self, mock_ingore_location): + """"add test for get scales from genofile where file is found""" + mock_ingore_location.return_value = True + geno_file = """ + #sample line with no @scales:other\n + #sample line @scales and :separated by semicolon\n + This attempts to check whether\n + """ + + geno_file_string = "@line start with @ and has @scale:morgan" + + file_location = "~/data/file.geno" + + mock_open_geno_file = mock.mock_open(read_data=geno_file) + with mock.patch("builtins.open", mock_open_geno_file): + results = get_scales_from_genofile(file_location) + self.assertEqual(results, [["morgan", "cM"]]) + + mock_open_string = mock.mock_open(read_data=geno_file_string) + + with mock.patch("builtins.open", mock_open_string): + result2 = get_scales_from_genofile(file_location) + self.assertEqual([['morgan', 'cM']], result2) + + @mock.patch("wqflask.show_trait.show_trait.locate_ignore_error") + def test_get_scales_from_genofile_not_found(self, mock_location_ignore): + mock_location_ignore.return_value = False + + expected_results = [["physic", "Mb"]] + results = get_scales_from_genofile("~/data/file") + mock_location_ignore.assert_called_once_with("~/data/file", "genotype") + self.assertEqual(results, expected_results) -- cgit v1.2.3 From 162e3e1acc1fea2548f7caa71fa3fc425c0a4ccd Mon Sep 17 00:00:00 2001 From: Alexanderlacuna Date: Thu, 5 Nov 2020 22:47:30 +0300 Subject: remove duplicates --- wqflask/tests/wqflask/show_trait/test_show_trait.py | 19 ------------------- 1 file changed, 19 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/wqflask/show_trait/test_show_trait.py b/wqflask/tests/wqflask/show_trait/test_show_trait.py index b1a91bbe..600baefb 100644 --- a/wqflask/tests/wqflask/show_trait/test_show_trait.py +++ b/wqflask/tests/wqflask/show_trait/test_show_trait.py @@ -242,25 +242,6 @@ class TestTraits(unittest.TestCase): self.assertEqual(get_genotype_scales(file_location), expected_results) mock_get_scales.assert_called_once_with(file_location) - @mock.patch("wqflask.show_trait.show_trait.locate_ignore_error") - def test_get_scales_from_genofile_found(self, mock_location_ignore): - # test no complete to be continued with - # a .geno file - mock_location_ignore.return_value = True - mock_file_with_one_line = mock.mock_open( - read_data="Some data from opened file") - - mock_file = """#@scale and random data:is here_returned\n - This is second with spaced with tabs\n """ - mock_file_result = mock.mock_open(read_data=mock_file) - - with mock.patch("builtins.open", mock_file_with_one_line): - result = get_scales_from_genofile("~/data/file") - self.assertEqual(result, [['morgan', 'cM']]) - - with mock.patch("builtins.open", mock_file_result): - results = get_scales_from_genofile("~data/file_geno") - self.assertEqual(results, [['physic', 'Mb']]) @mock.patch("wqflask.show_trait.show_trait.locate_ignore_error") def test_get_scales_from_genofile_found(self, mock_ingore_location): -- cgit v1.2.3 From 7078bd8a2d9d3a2ab8f31e102deeece8bc0e5fcf Mon Sep 17 00:00:00 2001 From: Alexanderlacuna Date: Fri, 6 Nov 2020 00:45:50 +0300 Subject: fix typo --- wqflask/tests/wqflask/show_trait/test_show_trait.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/wqflask/show_trait/test_show_trait.py b/wqflask/tests/wqflask/show_trait/test_show_trait.py index 600baefb..8c866874 100644 --- a/wqflask/tests/wqflask/show_trait/test_show_trait.py +++ b/wqflask/tests/wqflask/show_trait/test_show_trait.py @@ -244,9 +244,9 @@ class TestTraits(unittest.TestCase): @mock.patch("wqflask.show_trait.show_trait.locate_ignore_error") - def test_get_scales_from_genofile_found(self, mock_ingore_location): + def test_get_scales_from_genofile_found(self, mock_ignore_location): """"add test for get scales from genofile where file is found""" - mock_ingore_location.return_value = True + mock_ignore_location.return_value = True geno_file = """ #sample line with no @scales:other\n #sample line @scales and :separated by semicolon\n -- cgit v1.2.3 From 6b23bf4a0698339a1c7672b8d84dfef9b9066a79 Mon Sep 17 00:00:00 2001 From: Alexanderlacuna Date: Fri, 6 Nov 2020 10:59:12 +0300 Subject: modify tests to for changes in the natural sort function --- wqflask/tests/wqflask/show_trait/testSampleList.py | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/wqflask/show_trait/testSampleList.py b/wqflask/tests/wqflask/show_trait/testSampleList.py index 4cc8c4da..34c51e3e 100644 --- a/wqflask/tests/wqflask/show_trait/testSampleList.py +++ b/wqflask/tests/wqflask/show_trait/testSampleList.py @@ -10,9 +10,7 @@ class TestSampleList(unittest.TestCase): characters_list = ["z", "f", "q", "s", "t", "a", "g"] names_list = ["temp1", "publish", "Sample", "Dataset"] - - natural_sort(characters_list) - natural_sort(names_list) - - self.assertEqual(characters_list, ["a", "f", "g", "q", "s", "t", "z"]) - self.assertEqual(names_list, ["Dataset", "Sample", "publish", "temp1"]) + sorted_list_a=natural_sort(characters_list) + sorted_list_b=natural_sort(names_list) + self.assertEqual(sorted_list_a, ["a", "f", "g", "q", "s", "t", "z"]) + self.assertEqual(sorted_list_b,["Dataset", "Sample", "publish", "temp1"]) -- cgit v1.2.3 From 8e55eaf473d98c1d165fcaf60ab0e24abb6acd9e Mon Sep 17 00:00:00 2001 From: Alexanderlacuna Date: Sun, 8 Nov 2020 22:00:40 +0300 Subject: add tests for marker_regression/gemma_mapping --- .../marker_regression/test_gemma_mapping.py | 170 +++++++++++++++++++++ 1 file changed, 170 insertions(+) create mode 100644 wqflask/tests/wqflask/marker_regression/test_gemma_mapping.py (limited to 'wqflask/tests') diff --git a/wqflask/tests/wqflask/marker_regression/test_gemma_mapping.py b/wqflask/tests/wqflask/marker_regression/test_gemma_mapping.py new file mode 100644 index 00000000..4a88509e --- /dev/null +++ b/wqflask/tests/wqflask/marker_regression/test_gemma_mapping.py @@ -0,0 +1,170 @@ +#test for wqflask/marker_regression/gemma_mapping.py +import unittest +import random +from unittest import mock +from wqflask.marker_regression.gemma_mapping import run_gemma +from wqflask.marker_regression.gemma_mapping import gen_pheno_txt_file +from wqflask.marker_regression.gemma_mapping import gen_covariates_file +from wqflask.marker_regression.gemma_mapping import parse_gemma_output +from wqflask.marker_regression.gemma_mapping import parse_loco_output + + +class AttributeSetter: + def __init__(self, obj): + for key, val in obj.items(): + setattr(self, key, val) + + +class MockDatasetGroup(AttributeSetter): + def get_samplelist(self): + return None + + +class TestGemmaMapping(unittest.TestCase): + # def test_fail(self): + # self.assertEqual(2,3) + + @mock.patch("wqflask.marker_regression.gemma_mapping.TEMPDIR", "/home/user/data") + def setUp(self): + pass + + @mock.patch("wqflask.marker_regression.gemma_mapping.gen_pheno_txt_file") + @mock.patch("wqflask.marker_regression.gemma_mapping.os") + def test_run_gemma_first_run_set_true(self, mock_gen_pheno, mock_os): + chromosomes = AttributeSetter({"chromosomes": "SA"}) + covariates = "XI:X2,X4:X3,X6:X7" + dataset_group = MockDatasetGroup({"genofile": "fileX"}) + dataset = AttributeSetter( + {"group": dataset_group, "name": "dataset1_name", "species": chromosomes}) + trait = AttributeSetter({"name": "trait1"}) + mock_gen_pheno.side_effect = None + mock_gen_pheno.return_value = None + mock_os.path.isfile.return_value = True + + @mock.patch("wqflask.marker_regression.gemma_mapping.parse_loco_output") + def test_run_gemma_first_run_loco_set_false(self, mock_parse_loco): + dataset = AttributeSetter( + {"group": AttributeSetter({"genofile": "genofile.geno"})}) + + output_files = "file1" + use_loco = False + mock_parse_loco.side_effect = None + mock_parse_loco.return_value = [] + this_trait = AttributeSetter({"name": "t1"}) + + result = run_gemma(this_trait=this_trait, this_dataset=dataset, samples=[], vals=[ + ], covariates="", use_loco=True, first_run=False, output_files=output_files) + + expected_results = ([], "file1") + self.assertEqual(expected_results, result) + + @mock.patch("wqflask.marker_regression.gemma_mapping.TEMPDIR", "/home/user/data") + def test_gen_pheno_txt_file(self): + with mock.patch("builtins.open", mock.mock_open())as mock_open: + gen_pheno_txt_file(this_dataset={}, genofile_name="", vals=[ + "x", "w", "q", "we", "R"], trait_filename="fitr.re") + + mock_open.assert_called_once_with( + '/home/user/data/gn2/fitr.re.txt', 'w') + filehandler = mock_open() + values = ["x", "w", "q", "we", "R"] + write_calls = [mock.call('NA\n'), mock.call('w\n'), mock.call( + 'q\n'), mock.call('we\n'), mock.call('R\n')] + + filehandler.write.assert_has_calls(write_calls) + + @mock.patch("wqflask.marker_regression.gemma_mapping.flat_files") + @mock.patch("wqflask.marker_regression.gemma_mapping.create_trait") + @mock.patch("wqflask.marker_regression.gemma_mapping.create_dataset") + def test_gen_covariates_file(self, create_dataset, create_trait, flat_files): + covariates = "X1:X2,Y1:Y2,M1:M3,V1:V2" + samplelist = ["X1", "X2", "X3", "X4"] + create_dataset_side_effect = [] + create_trait_side_effect = [] + + for i in range(4): + create_dataset_side_effect.append(AttributeSetter({"name": f'name_{i}'})) + create_trait_side_effect.append( + AttributeSetter({"data": [f'data_{i}']})) + + create_dataset.side_effect = create_trait_side_effect + create_trait.side_effect = create_trait_side_effect + + group = MockDatasetGroup({"name": "group_X", "samplelist": samplelist}) + this_dataset = AttributeSetter({"group": group}) + flat_files.return_value = "Home/Genenetwork" + + with mock.patch("builtins.open", mock.mock_open())as mock_open: + gen_covariates_file(this_dataset=this_dataset, covariates=covariates, + samples=["x1", "x2", "X3"]) + # test mocked methods + + create_dataset.assert_has_calls( + [mock.call('X2'), mock.call('Y2'), mock.call('M3'), mock.call('V2')]) + mock_calls = [] + trait_names = ["X1", "Y1", "M1", "V1"] + + for i, trait in enumerate(create_trait_side_effect): + mock_calls.append( + mock.call(dataset=trait, name=trait_names[i], cellid=None)) + + create_trait.assert_has_calls(mock_calls) + + # test writing of covariates.txt + + flat_files.assert_called_once_with('mapping') + mock_open.assert_called_once_with( + 'Home/Genenetwork/group_X_covariates.txt', 'w') + filehandler = mock_open() + # expected all-9 + filehandler.write.assert_has_calls([mock.call( + '-9\t'), mock.call('-9\t'), mock.call('-9\t'), mock.call('-9\t'), mock.call('\n')]) + + @mock.patch("wqflask.marker_regression.gemma_mapping.webqtlConfig.GENERATED_IMAGE_DIR", "/home/user/img/") + def test_parse_gemma_output_obj_returned(self): + file = """X/Y\t gn2\t21\tQ\tE\tA\tP\tMMB\tCDE\t0.5 +X/Y\tgn2\t21322\tQ\tE\tA\tP\tMMB\tCDE\t0.5 +chr\tgn1\t12312\tQ\tE\tA\tP\tMMB\tCDE\t0.7 +X\tgn7\t2324424\tQ\tE\tA\tP\tMMB\tCDE\t0.4 +125\tgn9\t433575\tQ\tE\tA\tP\tMMB\tCDE\t0.67 +""" + with mock.patch("builtins.open", mock.mock_open(read_data=file)) as mock_open: + results = parse_gemma_output(genofile_name="gema_file") + expected = [{'name': ' gn2', 'chr': 'X/Y', 'Mb': 2.1e-05, 'p_value': 0.5, 'lod_score': 0.3010299956639812}, {'name': 'gn2', 'chr': 'X/Y', 'Mb': 0.021322, 'p_value': 0.5, 'lod_score': 0.3010299956639812}, {'name': 'gn7', 'chr': 'X', 'Mb': 2.324424, 'p_value': 0.4, 'lod_score': 0.3979400086720376}, {'name': 'gn9', 'chr': 125, 'Mb': 0.433575, 'p_value': 0.67, 'lod_score': 0.17392519729917352}] + + mock_open.assert_called_once_with( + "/home/user/img/gema_file_output.assoc.txt") + + self.assertEqual(results, expected) + + @mock.patch("wqflask.marker_regression.gemma_mapping.webqtlConfig.GENERATED_IMAGE_DIR", "/home/user/img") + def test_xparse_gemma_output_empty_return(self): + output_file_results = """chr\t today""" + with mock.patch("builtins.open", mock.mock_open(read_data=output_file_results)) as mock_open: + results = parse_gemma_output(genofile_name="gema_file") + self.assertEqual(results, []) + + @mock.patch("builtins.open", mock.mock_open(read_data="chr\t")) + def test_parse_gemma_output_empty_return(self): + #duplicate + string_read = parse_gemma_output(genofile_name="hdf") + # print(string_read) + + @mock.patch("wqflask.marker_regression.gemma_mapping.TEMPDIR", "/home/tmp") + @mock.patch("wqflask.marker_regression.gemma_mapping.os") + def test_parse_loco_output_file_found(self, mock_os): + mock_os.path.isfile.return_value = False + file_to_write = """{"files":["file_1","file_2"]}""" + + + @mock.patch("wqflask.marker_regression.gemma_mapping.TEMPDIR", "/home/tmp") + @mock.patch("wqflask.marker_regression.gemma_mapping.os") + def test_parse_loco_output_file_not_found(self, mock_os): + + mock_os.path.isfile.return_value = False + file_to_write = """{"files":["file_1","file_2"]}""" + + with mock.patch("builtins.open", mock.mock_open(read_data=file_to_write)) as mock_open: + results = parse_loco_output( + this_dataset={}, gwa_output_filename=".xw/") + self.assertEqual(results, []) -- cgit v1.2.3 From 5e50e19a014efdfcf0ce1397025879d4ada4d271 Mon Sep 17 00:00:00 2001 From: Alexanderlacuna Date: Sun, 8 Nov 2020 22:04:52 +0300 Subject: add tests for marker_regression/plink_mapping.py --- .../marker_regression/test_plink_mapping.py | 83 ++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 wqflask/tests/wqflask/marker_regression/test_plink_mapping.py (limited to 'wqflask/tests') diff --git a/wqflask/tests/wqflask/marker_regression/test_plink_mapping.py b/wqflask/tests/wqflask/marker_regression/test_plink_mapping.py new file mode 100644 index 00000000..b827fd0f --- /dev/null +++ b/wqflask/tests/wqflask/marker_regression/test_plink_mapping.py @@ -0,0 +1,83 @@ +# test for wqflask/marker_regression/plink_mapping.py +import unittest +from unittest import mock +from wqflask.marker_regression.plink_mapping import build_line_list +from wqflask.marker_regression.plink_mapping import get_samples_from_ped_file +from wqflask.marker_regression.plink_mapping import flat_files +from wqflask.marker_regression.plink_mapping import gen_pheno_txt_file_plink +from wqflask.marker_regression.plink_mapping import parse_plink_output + + +class AttributeSetter: + def __init__(self, obj): + for key, val in obj.items(): + setattr(self, key, val) + + +class TestPlinkMapping(unittest.TestCase): + + def test_build_line_list(self): + line_1 = "this is line one test" + irregular_line = " this is an, irregular line " + exp_line1 = ["this", "is", "line", "one", "test"] + + results = build_line_list(irregular_line) + self.assertEqual(exp_line1, build_line_list(line_1)) + self.assertEqual([], build_line_list()) + self.assertEqual(["this", "is", "an,", "irregular", "line"], results) + + @mock.patch("wqflask.marker_regression.plink_mapping.flat_files") + def test_get_samples_from_ped_file(self, mock_flat_files): + dataset = AttributeSetter({"group": AttributeSetter({"name": "n_1"})}) + file_sample = """Expected_1\tline test +Expected_2\there + Expected_3\tthree""" + mock_flat_files.return_value = "/home/user/" + with mock.patch("builtins.open", mock.mock_open(read_data=file_sample)) as mock_open: + results = get_samples_from_ped_file(dataset) + mock_flat_files.assert_called_once_with("mapping") + mock_open.assert_called_once_with("/home/user/n_1.ped", "r") + self.assertEqual( + ["Expected_1", "Expected_2", "Expected_3"], results) + + @mock.patch("wqflask.marker_regression.plink_mapping.TMPDIR", "/home/user/data/") + @mock.patch("wqflask.marker_regression.plink_mapping.get_samples_from_ped_file") + def test_gen_pheno_txt_file_plink(self, mock_samples): + mock_samples.return_value = ["Expected_1", "Expected_2", "Expected_3"] + + trait = AttributeSetter({"name": "TX"}) + dataset = AttributeSetter({"group": AttributeSetter({"name": "n_1"})}) + vals = ["value=K1", "value=K2", "value=K3"] + with mock.patch("builtins.open", mock.mock_open()) as mock_open: + results = gen_pheno_txt_file_plink(this_trait=trait, dataset=dataset, + vals=vals, pheno_filename="ph_file") + mock_open.assert_called_once_with( + "/home/user/data/ph_file.txt", "wb") + filehandler = mock_open() + calls_expected = [mock.call('FID\tIID\tTX\n'), + mock.call('Expected_1\tExpected_1\tK1\nExpected_2\tExpected_2\tK2\nExpected_3\tExpected_3\tK3\n')] + + filehandler.write.assert_has_calls(calls_expected) + + filehandler.close.assert_called_once() + + @mock.patch("wqflask.marker_regression.plink_mapping.TMPDIR", "/home/user/data/") + @mock.patch("wqflask.marker_regression.plink_mapping.build_line_list") + def test_parse_plink_output(self, mock_line_list): + chromosomes = [0, 34, 110, 89, 123, 23, 2] + species = AttributeSetter( + {"name": "S1", "chromosomes": AttributeSetter({"chromosomes": chromosomes})}) + + fake_file = """0 AACCAT T98.6 0.89\n2 AATA B45 0.3\n121 ACG B56.4 NA""" + + mock_line_list.side_effect = [["0", "AACCAT", "T98.6", "0.89"], [ + "2", "AATA", "B45", "0.3"], ["121", "ACG", "B56.4", "NA"]] + # print("sdfsfdf",species.chromosomes) + with mock.patch("builtins.open", mock.mock_open(read_data=fake_file)) as mock_open: + parse_results = parse_plink_output( + output_filename="P1_file", species=species) + mock_open.assert_called_once_with( + "/home/user/data/P1_file.qassoc", "rb") + expected = (2, {'AACCAT': 0.89, 'AATA': 0.3}) + + self.assertEqual(parse_results, expected) -- cgit v1.2.3 From 919763173289e523d5b3c9015fc6f1117ad59581 Mon Sep 17 00:00:00 2001 From: Alexanderlacuna Date: Mon, 9 Nov 2020 13:31:42 +0300 Subject: add test for run_gemma function in marker_regression/gemma_mapping.py --- .../marker_regression/test_gemma_mapping.py | 70 +++++++++++++++++----- 1 file changed, 55 insertions(+), 15 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/wqflask/marker_regression/test_gemma_mapping.py b/wqflask/tests/wqflask/marker_regression/test_gemma_mapping.py index 4a88509e..1b09afd6 100644 --- a/wqflask/tests/wqflask/marker_regression/test_gemma_mapping.py +++ b/wqflask/tests/wqflask/marker_regression/test_gemma_mapping.py @@ -1,4 +1,4 @@ -#test for wqflask/marker_regression/gemma_mapping.py +# test for wqflask/marker_regression/gemma_mapping.py import unittest import random from unittest import mock @@ -24,22 +24,62 @@ class TestGemmaMapping(unittest.TestCase): # def test_fail(self): # self.assertEqual(2,3) - @mock.patch("wqflask.marker_regression.gemma_mapping.TEMPDIR", "/home/user/data") def setUp(self): - pass + pass - @mock.patch("wqflask.marker_regression.gemma_mapping.gen_pheno_txt_file") + @mock.patch("wqflask.marker_regression.gemma_mapping.webqtlConfig.GENERATED_IMAGE_DIR", "/home/user/img") + @mock.patch("wqflask.marker_regression.gemma_mapping.GEMMAOPTS", "-debug") + @mock.patch("wqflask.marker_regression.gemma_mapping.GEMMA_WRAPPER_COMMAND", "ghc") + @mock.patch("wqflask.marker_regression.gemma_mapping.TEMPDIR", "/home/user/data/") + @mock.patch("wqflask.marker_regression.gemma_mapping.parse_loco_output") + @mock.patch("wqflask.marker_regression.gemma_mapping.flat_files") + @mock.patch("wqflask.marker_regression.gemma_mapping.gen_covariates_file") + @mock.patch("wqflask.marker_regression.gemma_mapping.string.ascii_uppercase", "R") + @mock.patch("wqflask.marker_regression.gemma_mapping.string.digits", "R") @mock.patch("wqflask.marker_regression.gemma_mapping.os") - def test_run_gemma_first_run_set_true(self, mock_gen_pheno, mock_os): - chromosomes = AttributeSetter({"chromosomes": "SA"}) - covariates = "XI:X2,X4:X3,X6:X7" - dataset_group = MockDatasetGroup({"genofile": "fileX"}) - dataset = AttributeSetter( - {"group": dataset_group, "name": "dataset1_name", "species": chromosomes}) + @mock.patch("wqflask.marker_regression.gemma_mapping.gen_pheno_txt_file") + def test_run_gemma_first_run_set_true(self, mock_gen_pheno_txt, mock_os, mock_gen_covar, mock_flat_files, mock_parse_loco): + + chromosomes = [] + for i in range(1, 5): + chromosomes.append(AttributeSetter({"name": f"CH{i}"})) + + chromo = AttributeSetter({"chromosomes": chromosomes}) + + dataset_group = MockDatasetGroup( + {"name": "GP1", "genofile": "file_geno"}) + + dataset = AttributeSetter({"group": dataset_group, "name": "dataset1_name", + "species": AttributeSetter({"chromosomes": chromo})}) + trait = AttributeSetter({"name": "trait1"}) - mock_gen_pheno.side_effect = None - mock_gen_pheno.return_value = None + samples = [] + mock_gen_pheno_txt.side_effect = None + mock_gen_pheno_txt.return_value = None mock_os.path.isfile.return_value = True + mock_os.system.return_value = None + mock_os.system.side_effect = None + mock_gen_covar.side_effect = None + mock_gen_covar.return_value = None + mock_flat_files.return_value = "/home/genotype/bimbam" + mock_parse_loco.side_effect = None + mock_parse_loco.return_value = [] + results = run_gemma(this_trait=trait, this_dataset=dataset, samples=[ + ], vals=[], covariates="", use_loco=True) + # check results + self.assertEqual(results, ([], "GP1_GWA_RRRRRR")) + mock_gen_pheno_txt.assert_called_once() + self.assertEqual(mock_flat_files.call_count, 4) + + system_calls = [mock.call('ghc --json -- -debug -g /home/genotype/bimbam/file_geno.txt -p /home/user/data//gn2/trait1_dataset1_name_pheno.txt -a /home/genotype/bimbam/file_snps.txt -gk > /home/user/data//gn2/GP1_K_RRRRRR.json'), + mock.call('ghc --json --input /home/user/data//gn2/GP1_K_RRRRRR.json -- -debug -a /home/genotype/bimbam/file_snps.txt -lmm 2 -g /home/genotype/bimbam/file_geno.txt -p /home/user/data//gn2/trait1_dataset1_name_pheno.txt > /home/user/data//gn2/GP1_GWA_RRRRRR.json')] + + mock_os.system.assert_has_calls(system_calls) + + mock_os.path.isfile.assert_called_once_with(('/home/user/imgfile_output.assoc.txt') + ) + + mock_parse_loco.assert_called_once_with(dataset,"GP1_GWA_RRRRRR") @mock.patch("wqflask.marker_regression.gemma_mapping.parse_loco_output") def test_run_gemma_first_run_loco_set_false(self, mock_parse_loco): @@ -130,7 +170,8 @@ X\tgn7\t2324424\tQ\tE\tA\tP\tMMB\tCDE\t0.4 """ with mock.patch("builtins.open", mock.mock_open(read_data=file)) as mock_open: results = parse_gemma_output(genofile_name="gema_file") - expected = [{'name': ' gn2', 'chr': 'X/Y', 'Mb': 2.1e-05, 'p_value': 0.5, 'lod_score': 0.3010299956639812}, {'name': 'gn2', 'chr': 'X/Y', 'Mb': 0.021322, 'p_value': 0.5, 'lod_score': 0.3010299956639812}, {'name': 'gn7', 'chr': 'X', 'Mb': 2.324424, 'p_value': 0.4, 'lod_score': 0.3979400086720376}, {'name': 'gn9', 'chr': 125, 'Mb': 0.433575, 'p_value': 0.67, 'lod_score': 0.17392519729917352}] + expected = [{'name': ' gn2', 'chr': 'X/Y', 'Mb': 2.1e-05, 'p_value': 0.5, 'lod_score': 0.3010299956639812}, {'name': 'gn2', 'chr': 'X/Y', 'Mb': 0.021322, 'p_value': 0.5, 'lod_score': 0.3010299956639812}, + {'name': 'gn7', 'chr': 'X', 'Mb': 2.324424, 'p_value': 0.4, 'lod_score': 0.3979400086720376}, {'name': 'gn9', 'chr': 125, 'Mb': 0.433575, 'p_value': 0.67, 'lod_score': 0.17392519729917352}] mock_open.assert_called_once_with( "/home/user/img/gema_file_output.assoc.txt") @@ -146,7 +187,7 @@ X\tgn7\t2324424\tQ\tE\tA\tP\tMMB\tCDE\t0.4 @mock.patch("builtins.open", mock.mock_open(read_data="chr\t")) def test_parse_gemma_output_empty_return(self): - #duplicate + # duplicate string_read = parse_gemma_output(genofile_name="hdf") # print(string_read) @@ -156,7 +197,6 @@ X\tgn7\t2324424\tQ\tE\tA\tP\tMMB\tCDE\t0.4 mock_os.path.isfile.return_value = False file_to_write = """{"files":["file_1","file_2"]}""" - @mock.patch("wqflask.marker_regression.gemma_mapping.TEMPDIR", "/home/tmp") @mock.patch("wqflask.marker_regression.gemma_mapping.os") def test_parse_loco_output_file_not_found(self, mock_os): -- cgit v1.2.3 From 74c65eb99be3f9854bd774dae15877af7c8aa4f5 Mon Sep 17 00:00:00 2001 From: Alexanderlacuna Date: Mon, 9 Nov 2020 14:03:08 +0300 Subject: mock logger in marker_regression/gemma_mapping.py --- .../marker_regression/test_gemma_mapping.py | 47 +++++++++++++--------- 1 file changed, 27 insertions(+), 20 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/wqflask/marker_regression/test_gemma_mapping.py b/wqflask/tests/wqflask/marker_regression/test_gemma_mapping.py index 1b09afd6..fd45fd65 100644 --- a/wqflask/tests/wqflask/marker_regression/test_gemma_mapping.py +++ b/wqflask/tests/wqflask/marker_regression/test_gemma_mapping.py @@ -27,18 +27,39 @@ class TestGemmaMapping(unittest.TestCase): def setUp(self): pass + + + @mock.patch("wqflask.marker_regression.gemma_mapping.parse_loco_output") + def test_run_gemma_first_run_loco_set_false(self, mock_parse_loco): + dataset = AttributeSetter( + {"group": AttributeSetter({"genofile": "genofile.geno"})}) + + output_files = "file1" + use_loco = False + mock_parse_loco.side_effect = None + mock_parse_loco.return_value = [] + this_trait = AttributeSetter({"name": "t1"}) + + result = run_gemma(this_trait=this_trait, this_dataset=dataset, samples=[], vals=[ + ], covariates="", use_loco=True, first_run=False, output_files=output_files) + + expected_results = ([], "file1") + self.assertEqual(expected_results, result) + + @mock.patch("wqflask.marker_regression.gemma_mapping.webqtlConfig.GENERATED_IMAGE_DIR", "/home/user/img") @mock.patch("wqflask.marker_regression.gemma_mapping.GEMMAOPTS", "-debug") @mock.patch("wqflask.marker_regression.gemma_mapping.GEMMA_WRAPPER_COMMAND", "ghc") @mock.patch("wqflask.marker_regression.gemma_mapping.TEMPDIR", "/home/user/data/") @mock.patch("wqflask.marker_regression.gemma_mapping.parse_loco_output") + @mock.patch("wqflask.marker_regression.gemma_mapping.logger") @mock.patch("wqflask.marker_regression.gemma_mapping.flat_files") @mock.patch("wqflask.marker_regression.gemma_mapping.gen_covariates_file") @mock.patch("wqflask.marker_regression.gemma_mapping.string.ascii_uppercase", "R") @mock.patch("wqflask.marker_regression.gemma_mapping.string.digits", "R") @mock.patch("wqflask.marker_regression.gemma_mapping.os") @mock.patch("wqflask.marker_regression.gemma_mapping.gen_pheno_txt_file") - def test_run_gemma_first_run_set_true(self, mock_gen_pheno_txt, mock_os, mock_gen_covar, mock_flat_files, mock_parse_loco): + def test_run_gemma_first_run_set_true(self, mock_gen_pheno_txt, mock_os, mock_gen_covar, mock_flat_files,mock_logger,mock_parse_loco): chromosomes = [] for i in range(1, 5): @@ -71,32 +92,18 @@ class TestGemmaMapping(unittest.TestCase): mock_gen_pheno_txt.assert_called_once() self.assertEqual(mock_flat_files.call_count, 4) + system_calls = [mock.call('ghc --json -- -debug -g /home/genotype/bimbam/file_geno.txt -p /home/user/data//gn2/trait1_dataset1_name_pheno.txt -a /home/genotype/bimbam/file_snps.txt -gk > /home/user/data//gn2/GP1_K_RRRRRR.json'), mock.call('ghc --json --input /home/user/data//gn2/GP1_K_RRRRRR.json -- -debug -a /home/genotype/bimbam/file_snps.txt -lmm 2 -g /home/genotype/bimbam/file_geno.txt -p /home/user/data//gn2/trait1_dataset1_name_pheno.txt > /home/user/data//gn2/GP1_GWA_RRRRRR.json')] mock_os.system.assert_has_calls(system_calls) - mock_os.path.isfile.assert_called_once_with(('/home/user/imgfile_output.assoc.txt') - ) - - mock_parse_loco.assert_called_once_with(dataset,"GP1_GWA_RRRRRR") + mock_os.path.isfile.assert_called_once_with(('/home/user/imgfile_output.assoc.txt')) - @mock.patch("wqflask.marker_regression.gemma_mapping.parse_loco_output") - def test_run_gemma_first_run_loco_set_false(self, mock_parse_loco): - dataset = AttributeSetter( - {"group": AttributeSetter({"genofile": "genofile.geno"})}) + self.assertEqual(mock_logger.debug.call_count,2) + - output_files = "file1" - use_loco = False - mock_parse_loco.side_effect = None - mock_parse_loco.return_value = [] - this_trait = AttributeSetter({"name": "t1"}) - - result = run_gemma(this_trait=this_trait, this_dataset=dataset, samples=[], vals=[ - ], covariates="", use_loco=True, first_run=False, output_files=output_files) - - expected_results = ([], "file1") - self.assertEqual(expected_results, result) + mock_parse_loco.assert_called_once_with(dataset,"GP1_GWA_RRRRRR") @mock.patch("wqflask.marker_regression.gemma_mapping.TEMPDIR", "/home/user/data") def test_gen_pheno_txt_file(self): -- cgit v1.2.3 From 986b20363cc84be1822588dd7cc935fca7ef7f48 Mon Sep 17 00:00:00 2001 From: Alexanderlacuna Date: Mon, 9 Nov 2020 16:53:12 +0300 Subject: add test for get_genofile_samplelist in marker_regression/run_mapping.py --- .../wqflask/marker_regression/test_run_mapping.py | 36 ++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 wqflask/tests/wqflask/marker_regression/test_run_mapping.py (limited to 'wqflask/tests') diff --git a/wqflask/tests/wqflask/marker_regression/test_run_mapping.py b/wqflask/tests/wqflask/marker_regression/test_run_mapping.py new file mode 100644 index 00000000..0a5bc565 --- /dev/null +++ b/wqflask/tests/wqflask/marker_regression/test_run_mapping.py @@ -0,0 +1,36 @@ +import unittest +from unittest import mock +from wqflask.marker_regression.run_mapping import get_genofile_samplelist + + +class AttributeSetter: + def __init__(self,obj): + for k,v in obj.items(): + setattr(self,k,v) + + +class MockDataSetGroup(AttributeSetter): + + def get_genofiles(self): + return [{"location":"~/genofiles/g1_file","sample_list":["S1","S2","S3","S4"]}] +class TestRunMapping(unittest.TestCase): + def setUp(self): + self.group=MockDataSetGroup({"genofile":"~/genofiles/g1_file"}) + self.dataset=AttributeSetter({"group":self.group}) + + def tearDown(self): + self.dataset=AttributeSetter({"group":{"location":"~/genofiles/g1_file"}}) + + + def test_get_genofile_samplelist(self): + #location true and sample list true + + results_1=get_genofile_samplelist(self.dataset) + self.assertEqual(results_1,["S1","S2","S3","S4"]) + #return empty array + self.group.genofile="~/genofiles/g2_file" + result_2=get_genofile_samplelist(self.dataset) + self.assertEqual(result_2,[]) + + + -- cgit v1.2.3 From e660984015e1bc6d48e9ccee5fe59691c4acd911 Mon Sep 17 00:00:00 2001 From: Alexanderlacuna Date: Mon, 9 Nov 2020 17:22:27 +0300 Subject: add tests for geno_db_exists in marker_regression/run_mapping.py --- .../wqflask/marker_regression/test_run_mapping.py | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/wqflask/marker_regression/test_run_mapping.py b/wqflask/tests/wqflask/marker_regression/test_run_mapping.py index 0a5bc565..61bc8a1d 100644 --- a/wqflask/tests/wqflask/marker_regression/test_run_mapping.py +++ b/wqflask/tests/wqflask/marker_regression/test_run_mapping.py @@ -1,7 +1,7 @@ import unittest from unittest import mock from wqflask.marker_regression.run_mapping import get_genofile_samplelist - +from wqflask.marker_regression.run_mapping import geno_db_exists class AttributeSetter: def __init__(self,obj): @@ -15,7 +15,7 @@ class MockDataSetGroup(AttributeSetter): return [{"location":"~/genofiles/g1_file","sample_list":["S1","S2","S3","S4"]}] class TestRunMapping(unittest.TestCase): def setUp(self): - self.group=MockDataSetGroup({"genofile":"~/genofiles/g1_file"}) + self.group=MockDataSetGroup({"genofile":"~/genofiles/g1_file","name":"GP1_"}) self.dataset=AttributeSetter({"group":self.group}) def tearDown(self): @@ -32,5 +32,21 @@ class TestRunMapping(unittest.TestCase): result_2=get_genofile_samplelist(self.dataset) self.assertEqual(result_2,[]) + @mock.patch("wqflask.marker_regression.run_mapping.data_set") + def test_geno_db_exists(self,mock_data_set): + # mock_data_set.create_dataset_side_effect=None + mock_data_set.create_dataset.side_effect=[AttributeSetter({}),Exception()] + results_no_error=geno_db_exists(self.dataset) + results_with_error=geno_db_exists(self.dataset) + + self.assertEqual(mock_data_set.create_dataset.call_count,2) + self.assertEqual(results_with_error,"False") + self.assertEqual(results_no_error,"True") + + + + + + -- cgit v1.2.3 From c9c06e3e2df6d9290a7b65607dd819f68290712e Mon Sep 17 00:00:00 2001 From: Alexanderlacuna Date: Mon, 9 Nov 2020 20:10:21 +0300 Subject: remove unnecessary side_effect set to None --- .../marker_regression/test_gemma_mapping.py | 43 +++++----------------- 1 file changed, 9 insertions(+), 34 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/wqflask/marker_regression/test_gemma_mapping.py b/wqflask/tests/wqflask/marker_regression/test_gemma_mapping.py index fd45fd65..963c131f 100644 --- a/wqflask/tests/wqflask/marker_regression/test_gemma_mapping.py +++ b/wqflask/tests/wqflask/marker_regression/test_gemma_mapping.py @@ -21,13 +21,6 @@ class MockDatasetGroup(AttributeSetter): class TestGemmaMapping(unittest.TestCase): - # def test_fail(self): - # self.assertEqual(2,3) - - def setUp(self): - pass - - @mock.patch("wqflask.marker_regression.gemma_mapping.parse_loco_output") def test_run_gemma_first_run_loco_set_false(self, mock_parse_loco): @@ -36,7 +29,6 @@ class TestGemmaMapping(unittest.TestCase): output_files = "file1" use_loco = False - mock_parse_loco.side_effect = None mock_parse_loco.return_value = [] this_trait = AttributeSetter({"name": "t1"}) @@ -46,7 +38,6 @@ class TestGemmaMapping(unittest.TestCase): expected_results = ([], "file1") self.assertEqual(expected_results, result) - @mock.patch("wqflask.marker_regression.gemma_mapping.webqtlConfig.GENERATED_IMAGE_DIR", "/home/user/img") @mock.patch("wqflask.marker_regression.gemma_mapping.GEMMAOPTS", "-debug") @mock.patch("wqflask.marker_regression.gemma_mapping.GEMMA_WRAPPER_COMMAND", "ghc") @@ -59,7 +50,7 @@ class TestGemmaMapping(unittest.TestCase): @mock.patch("wqflask.marker_regression.gemma_mapping.string.digits", "R") @mock.patch("wqflask.marker_regression.gemma_mapping.os") @mock.patch("wqflask.marker_regression.gemma_mapping.gen_pheno_txt_file") - def test_run_gemma_first_run_set_true(self, mock_gen_pheno_txt, mock_os, mock_gen_covar, mock_flat_files,mock_logger,mock_parse_loco): + def test_run_gemma_first_run_set_true(self, mock_gen_pheno_txt, mock_os, mock_gen_covar, mock_flat_files, mock_logger, mock_parse_loco): chromosomes = [] for i in range(1, 5): @@ -75,35 +66,28 @@ class TestGemmaMapping(unittest.TestCase): trait = AttributeSetter({"name": "trait1"}) samples = [] - mock_gen_pheno_txt.side_effect = None + mock_gen_pheno_txt.return_value = None mock_os.path.isfile.return_value = True - mock_os.system.return_value = None - mock_os.system.side_effect = None - mock_gen_covar.side_effect = None mock_gen_covar.return_value = None mock_flat_files.return_value = "/home/genotype/bimbam" - mock_parse_loco.side_effect = None mock_parse_loco.return_value = [] results = run_gemma(this_trait=trait, this_dataset=dataset, samples=[ ], vals=[], covariates="", use_loco=True) - # check results self.assertEqual(results, ([], "GP1_GWA_RRRRRR")) mock_gen_pheno_txt.assert_called_once() self.assertEqual(mock_flat_files.call_count, 4) - - system_calls = [mock.call('ghc --json -- -debug -g /home/genotype/bimbam/file_geno.txt -p /home/user/data//gn2/trait1_dataset1_name_pheno.txt -a /home/genotype/bimbam/file_snps.txt -gk > /home/user/data//gn2/GP1_K_RRRRRR.json'), mock.call('ghc --json --input /home/user/data//gn2/GP1_K_RRRRRR.json -- -debug -a /home/genotype/bimbam/file_snps.txt -lmm 2 -g /home/genotype/bimbam/file_geno.txt -p /home/user/data//gn2/trait1_dataset1_name_pheno.txt > /home/user/data//gn2/GP1_GWA_RRRRRR.json')] mock_os.system.assert_has_calls(system_calls) - mock_os.path.isfile.assert_called_once_with(('/home/user/imgfile_output.assoc.txt')) + mock_os.path.isfile.assert_called_once_with( + ('/home/user/imgfile_output.assoc.txt')) - self.assertEqual(mock_logger.debug.call_count,2) - + self.assertEqual(mock_logger.debug.call_count, 2) - mock_parse_loco.assert_called_once_with(dataset,"GP1_GWA_RRRRRR") + mock_parse_loco.assert_called_once_with(dataset, "GP1_GWA_RRRRRR") @mock.patch("wqflask.marker_regression.gemma_mapping.TEMPDIR", "/home/user/data") def test_gen_pheno_txt_file(self): @@ -144,7 +128,6 @@ class TestGemmaMapping(unittest.TestCase): with mock.patch("builtins.open", mock.mock_open())as mock_open: gen_covariates_file(this_dataset=this_dataset, covariates=covariates, samples=["x1", "x2", "X3"]) - # test mocked methods create_dataset.assert_has_calls( [mock.call('X2'), mock.call('Y2'), mock.call('M3'), mock.call('V2')]) @@ -157,13 +140,10 @@ class TestGemmaMapping(unittest.TestCase): create_trait.assert_has_calls(mock_calls) - # test writing of covariates.txt - flat_files.assert_called_once_with('mapping') mock_open.assert_called_once_with( 'Home/Genenetwork/group_X_covariates.txt', 'w') filehandler = mock_open() - # expected all-9 filehandler.write.assert_has_calls([mock.call( '-9\t'), mock.call('-9\t'), mock.call('-9\t'), mock.call('-9\t'), mock.call('\n')]) @@ -186,23 +166,18 @@ X\tgn7\t2324424\tQ\tE\tA\tP\tMMB\tCDE\t0.4 self.assertEqual(results, expected) @mock.patch("wqflask.marker_regression.gemma_mapping.webqtlConfig.GENERATED_IMAGE_DIR", "/home/user/img") - def test_xparse_gemma_output_empty_return(self): + def test_parse_gemma_output_empty_return(self): output_file_results = """chr\t today""" with mock.patch("builtins.open", mock.mock_open(read_data=output_file_results)) as mock_open: results = parse_gemma_output(genofile_name="gema_file") self.assertEqual(results, []) - @mock.patch("builtins.open", mock.mock_open(read_data="chr\t")) - def test_parse_gemma_output_empty_return(self): - # duplicate - string_read = parse_gemma_output(genofile_name="hdf") - # print(string_read) - @mock.patch("wqflask.marker_regression.gemma_mapping.TEMPDIR", "/home/tmp") @mock.patch("wqflask.marker_regression.gemma_mapping.os") def test_parse_loco_output_file_found(self, mock_os): - mock_os.path.isfile.return_value = False + mock_os.path.isfile.return_value = True file_to_write = """{"files":["file_1","file_2"]}""" + #incomplete @mock.patch("wqflask.marker_regression.gemma_mapping.TEMPDIR", "/home/tmp") @mock.patch("wqflask.marker_regression.gemma_mapping.os") -- cgit v1.2.3 From bf22cc3fbb37147b5e6c3012658fe5e43b696637 Mon Sep 17 00:00:00 2001 From: Alexanderlacuna Date: Mon, 9 Nov 2020 20:26:21 +0300 Subject: remove whitespace in marker_regression --- wqflask/tests/wqflask/marker_regression/test_plink_mapping.py | 3 --- wqflask/tests/wqflask/marker_regression/test_run_mapping.py | 9 +-------- 2 files changed, 1 insertion(+), 11 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/wqflask/marker_regression/test_plink_mapping.py b/wqflask/tests/wqflask/marker_regression/test_plink_mapping.py index b827fd0f..a5fa0c04 100644 --- a/wqflask/tests/wqflask/marker_regression/test_plink_mapping.py +++ b/wqflask/tests/wqflask/marker_regression/test_plink_mapping.py @@ -12,8 +12,6 @@ class AttributeSetter: def __init__(self, obj): for key, val in obj.items(): setattr(self, key, val) - - class TestPlinkMapping(unittest.TestCase): def test_build_line_list(self): @@ -72,7 +70,6 @@ Expected_2\there mock_line_list.side_effect = [["0", "AACCAT", "T98.6", "0.89"], [ "2", "AATA", "B45", "0.3"], ["121", "ACG", "B56.4", "NA"]] - # print("sdfsfdf",species.chromosomes) with mock.patch("builtins.open", mock.mock_open(read_data=fake_file)) as mock_open: parse_results = parse_plink_output( output_filename="P1_file", species=species) diff --git a/wqflask/tests/wqflask/marker_regression/test_run_mapping.py b/wqflask/tests/wqflask/marker_regression/test_run_mapping.py index 61bc8a1d..bba9de05 100644 --- a/wqflask/tests/wqflask/marker_regression/test_run_mapping.py +++ b/wqflask/tests/wqflask/marker_regression/test_run_mapping.py @@ -2,6 +2,7 @@ import unittest from unittest import mock from wqflask.marker_regression.run_mapping import get_genofile_samplelist from wqflask.marker_regression.run_mapping import geno_db_exists +from wqflask.marker_regression.run_mapping import write_input_for_browser class AttributeSetter: def __init__(self,obj): @@ -21,20 +22,16 @@ class TestRunMapping(unittest.TestCase): def tearDown(self): self.dataset=AttributeSetter({"group":{"location":"~/genofiles/g1_file"}}) - def test_get_genofile_samplelist(self): - #location true and sample list true results_1=get_genofile_samplelist(self.dataset) self.assertEqual(results_1,["S1","S2","S3","S4"]) - #return empty array self.group.genofile="~/genofiles/g2_file" result_2=get_genofile_samplelist(self.dataset) self.assertEqual(result_2,[]) @mock.patch("wqflask.marker_regression.run_mapping.data_set") def test_geno_db_exists(self,mock_data_set): - # mock_data_set.create_dataset_side_effect=None mock_data_set.create_dataset.side_effect=[AttributeSetter({}),Exception()] results_no_error=geno_db_exists(self.dataset) results_with_error=geno_db_exists(self.dataset) @@ -46,7 +43,3 @@ class TestRunMapping(unittest.TestCase): - - - - -- cgit v1.2.3 From 3ccc964fc466467c1c65f000fa7b43a38e10987a Mon Sep 17 00:00:00 2001 From: Alexanderlacuna Date: Mon, 9 Nov 2020 21:15:24 +0300 Subject: refactor test_run_gemma function --- wqflask/tests/wqflask/marker_regression/test_gemma_mapping.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/wqflask/marker_regression/test_gemma_mapping.py b/wqflask/tests/wqflask/marker_regression/test_gemma_mapping.py index 963c131f..bc0cb4e0 100644 --- a/wqflask/tests/wqflask/marker_regression/test_gemma_mapping.py +++ b/wqflask/tests/wqflask/marker_regression/test_gemma_mapping.py @@ -46,11 +46,10 @@ class TestGemmaMapping(unittest.TestCase): @mock.patch("wqflask.marker_regression.gemma_mapping.logger") @mock.patch("wqflask.marker_regression.gemma_mapping.flat_files") @mock.patch("wqflask.marker_regression.gemma_mapping.gen_covariates_file") - @mock.patch("wqflask.marker_regression.gemma_mapping.string.ascii_uppercase", "R") - @mock.patch("wqflask.marker_regression.gemma_mapping.string.digits", "R") + @mock.patch("wqflask.marker_regression.run_mapping.random.choice") @mock.patch("wqflask.marker_regression.gemma_mapping.os") @mock.patch("wqflask.marker_regression.gemma_mapping.gen_pheno_txt_file") - def test_run_gemma_first_run_set_true(self, mock_gen_pheno_txt, mock_os, mock_gen_covar, mock_flat_files, mock_logger, mock_parse_loco): + def test_run_gemma_first_run_set_true(self, mock_gen_pheno_txt, mock_os,mock_choice,mock_gen_covar, mock_flat_files, mock_logger, mock_parse_loco): chromosomes = [] for i in range(1, 5): @@ -70,6 +69,7 @@ class TestGemmaMapping(unittest.TestCase): mock_gen_pheno_txt.return_value = None mock_os.path.isfile.return_value = True mock_gen_covar.return_value = None + mock_choice.return_value="R" mock_flat_files.return_value = "/home/genotype/bimbam" mock_parse_loco.return_value = [] results = run_gemma(this_trait=trait, this_dataset=dataset, samples=[ @@ -177,7 +177,7 @@ X\tgn7\t2324424\tQ\tE\tA\tP\tMMB\tCDE\t0.4 def test_parse_loco_output_file_found(self, mock_os): mock_os.path.isfile.return_value = True file_to_write = """{"files":["file_1","file_2"]}""" - #incomplete + # incomplete @mock.patch("wqflask.marker_regression.gemma_mapping.TEMPDIR", "/home/tmp") @mock.patch("wqflask.marker_regression.gemma_mapping.os") -- cgit v1.2.3 From ba065fa885841dc39681d0e420ac06df1ea846ae Mon Sep 17 00:00:00 2001 From: Alexanderlacuna Date: Mon, 9 Nov 2020 21:27:54 +0300 Subject: correct typo and variable naming --- .../marker_regression/test_gemma_mapping.py | 30 +++++----------------- 1 file changed, 7 insertions(+), 23 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/wqflask/marker_regression/test_gemma_mapping.py b/wqflask/tests/wqflask/marker_regression/test_gemma_mapping.py index bc0cb4e0..06ce55d8 100644 --- a/wqflask/tests/wqflask/marker_regression/test_gemma_mapping.py +++ b/wqflask/tests/wqflask/marker_regression/test_gemma_mapping.py @@ -49,52 +49,41 @@ class TestGemmaMapping(unittest.TestCase): @mock.patch("wqflask.marker_regression.run_mapping.random.choice") @mock.patch("wqflask.marker_regression.gemma_mapping.os") @mock.patch("wqflask.marker_regression.gemma_mapping.gen_pheno_txt_file") - def test_run_gemma_first_run_set_true(self, mock_gen_pheno_txt, mock_os,mock_choice,mock_gen_covar, mock_flat_files, mock_logger, mock_parse_loco): - + def test_run_gemma_first_run_set_true(self, mock_gen_pheno_txt, mock_os, mock_choice, mock_gen_covar, mock_flat_files, mock_logger, mock_parse_loco): chromosomes = [] for i in range(1, 5): chromosomes.append(AttributeSetter({"name": f"CH{i}"})) - chromo = AttributeSetter({"chromosomes": chromosomes}) - dataset_group = MockDatasetGroup( {"name": "GP1", "genofile": "file_geno"}) - dataset = AttributeSetter({"group": dataset_group, "name": "dataset1_name", "species": AttributeSetter({"chromosomes": chromo})}) - trait = AttributeSetter({"name": "trait1"}) samples = [] - mock_gen_pheno_txt.return_value = None mock_os.path.isfile.return_value = True mock_gen_covar.return_value = None - mock_choice.return_value="R" + mock_choice.return_value = "R" mock_flat_files.return_value = "/home/genotype/bimbam" mock_parse_loco.return_value = [] results = run_gemma(this_trait=trait, this_dataset=dataset, samples=[ ], vals=[], covariates="", use_loco=True) - self.assertEqual(results, ([], "GP1_GWA_RRRRRR")) - mock_gen_pheno_txt.assert_called_once() - self.assertEqual(mock_flat_files.call_count, 4) system_calls = [mock.call('ghc --json -- -debug -g /home/genotype/bimbam/file_geno.txt -p /home/user/data//gn2/trait1_dataset1_name_pheno.txt -a /home/genotype/bimbam/file_snps.txt -gk > /home/user/data//gn2/GP1_K_RRRRRR.json'), mock.call('ghc --json --input /home/user/data//gn2/GP1_K_RRRRRR.json -- -debug -a /home/genotype/bimbam/file_snps.txt -lmm 2 -g /home/genotype/bimbam/file_geno.txt -p /home/user/data//gn2/trait1_dataset1_name_pheno.txt > /home/user/data//gn2/GP1_GWA_RRRRRR.json')] - mock_os.system.assert_has_calls(system_calls) - + mock_gen_pheno_txt.assert_called_once() + mock_parse_loco.assert_called_once_with(dataset, "GP1_GWA_RRRRRR") mock_os.path.isfile.assert_called_once_with( ('/home/user/imgfile_output.assoc.txt')) - self.assertEqual(mock_logger.debug.call_count, 2) - - mock_parse_loco.assert_called_once_with(dataset, "GP1_GWA_RRRRRR") + self.assertEqual(mock_flat_files.call_count, 4) + self.assertEqual(results, ([], "GP1_GWA_RRRRRR")) @mock.patch("wqflask.marker_regression.gemma_mapping.TEMPDIR", "/home/user/data") def test_gen_pheno_txt_file(self): with mock.patch("builtins.open", mock.mock_open())as mock_open: gen_pheno_txt_file(this_dataset={}, genofile_name="", vals=[ "x", "w", "q", "we", "R"], trait_filename="fitr.re") - mock_open.assert_called_once_with( '/home/user/data/gn2/fitr.re.txt', 'w') filehandler = mock_open() @@ -159,26 +148,21 @@ X\tgn7\t2324424\tQ\tE\tA\tP\tMMB\tCDE\t0.4 results = parse_gemma_output(genofile_name="gema_file") expected = [{'name': ' gn2', 'chr': 'X/Y', 'Mb': 2.1e-05, 'p_value': 0.5, 'lod_score': 0.3010299956639812}, {'name': 'gn2', 'chr': 'X/Y', 'Mb': 0.021322, 'p_value': 0.5, 'lod_score': 0.3010299956639812}, {'name': 'gn7', 'chr': 'X', 'Mb': 2.324424, 'p_value': 0.4, 'lod_score': 0.3979400086720376}, {'name': 'gn9', 'chr': 125, 'Mb': 0.433575, 'p_value': 0.67, 'lod_score': 0.17392519729917352}] - mock_open.assert_called_once_with( "/home/user/img/gema_file_output.assoc.txt") - self.assertEqual(results, expected) - @mock.patch("wqflask.marker_regression.gemma_mapping.webqtlConfig.GENERATED_IMAGE_DIR", "/home/user/img") def test_parse_gemma_output_empty_return(self): output_file_results = """chr\t today""" with mock.patch("builtins.open", mock.mock_open(read_data=output_file_results)) as mock_open: results = parse_gemma_output(genofile_name="gema_file") self.assertEqual(results, []) - @mock.patch("wqflask.marker_regression.gemma_mapping.TEMPDIR", "/home/tmp") @mock.patch("wqflask.marker_regression.gemma_mapping.os") def test_parse_loco_output_file_found(self, mock_os): mock_os.path.isfile.return_value = True file_to_write = """{"files":["file_1","file_2"]}""" - # incomplete - + pass @mock.patch("wqflask.marker_regression.gemma_mapping.TEMPDIR", "/home/tmp") @mock.patch("wqflask.marker_regression.gemma_mapping.os") def test_parse_loco_output_file_not_found(self, mock_os): -- cgit v1.2.3 From 137dff191dd8b78e8207e6c5adc4e1c421a75ff0 Mon Sep 17 00:00:00 2001 From: Alexanderlacuna Date: Tue, 10 Nov 2020 13:57:24 +0300 Subject: add tests for export_mapping_results in marker_regression/run_mapping.py --- .../wqflask/marker_regression/test_run_mapping.py | 192 ++++++++++++++++++--- 1 file changed, 167 insertions(+), 25 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/wqflask/marker_regression/test_run_mapping.py b/wqflask/tests/wqflask/marker_regression/test_run_mapping.py index bba9de05..e925ad28 100644 --- a/wqflask/tests/wqflask/marker_regression/test_run_mapping.py +++ b/wqflask/tests/wqflask/marker_regression/test_run_mapping.py @@ -1,45 +1,187 @@ import unittest +import datetime from unittest import mock + from wqflask.marker_regression.run_mapping import get_genofile_samplelist from wqflask.marker_regression.run_mapping import geno_db_exists from wqflask.marker_regression.run_mapping import write_input_for_browser +from wqflask.marker_regression.run_mapping import export_mapping_results +from wqflask.marker_regression.run_mapping import trim_markers_for_figure + class AttributeSetter: - def __init__(self,obj): - for k,v in obj.items(): - setattr(self,k,v) + def __init__(self, obj): + for k, v in obj.items(): + setattr(self, k, v) class MockDataSetGroup(AttributeSetter): - - def get_genofiles(self): - return [{"location":"~/genofiles/g1_file","sample_list":["S1","S2","S3","S4"]}] + + def get_genofiles(self): + return [{"location": "~/genofiles/g1_file", "sample_list": ["S1", "S2", "S3", "S4"]}] + + class TestRunMapping(unittest.TestCase): - def setUp(self): - self.group=MockDataSetGroup({"genofile":"~/genofiles/g1_file","name":"GP1_"}) - self.dataset=AttributeSetter({"group":self.group}) + def setUp(self): + self.group = MockDataSetGroup( + {"genofile": "~/genofiles/g1_file", "name": "GP1_","species":"Human"}) + self.dataset = AttributeSetter({"fullname":"dataser_1","group": self.group,"type":"ProbeSet"}) + self.trait=AttributeSetter({"symbol":"IGFI","chr":"X1","mb":123313}) + + def tearDown(self): + self.dataset = AttributeSetter( + {"group": {"location": "~/genofiles/g1_file"}}) + + def test_get_genofile_samplelist(self): + + results_1 = get_genofile_samplelist(self.dataset) + self.assertEqual(results_1, ["S1", "S2", "S3", "S4"]) + self.group.genofile = "~/genofiles/g2_file" + result_2 = get_genofile_samplelist(self.dataset) + self.assertEqual(result_2, []) + + @mock.patch("wqflask.marker_regression.run_mapping.data_set") + def test_geno_db_exists(self, mock_data_set): + mock_data_set.create_dataset.side_effect = [ + AttributeSetter({}), Exception()] + results_no_error = geno_db_exists(self.dataset) + results_with_error = geno_db_exists(self.dataset) + + self.assertEqual(mock_data_set.create_dataset.call_count, 2) + self.assertEqual(results_with_error, "False") + self.assertEqual(results_no_error, "True") + + + def test_trim_markers_for_figure(self): - def tearDown(self): - self.dataset=AttributeSetter({"group":{"location":"~/genofiles/g1_file"}}) - def test_get_genofile_samplelist(self): + markers=[{ + "name":"MK1", + "chr":"C1", + "cM":"1", + "Mb":"12000", + "genotypes":[], + "dominance":"TT", + "additive":"VA", + "lod_score":0.5 + }, + { + "name":"MK2", + "chr":"C2", + "cM":"15", + "Mb":"10000", + "genotypes":[], + "lod_score":0.7 + }, + { + "name":"MK1", + "chr":"C3", + "cM":"45", + "Mb":"1", + "genotypes":[], + "dominance":"Tt", + "additive":"VE", + "lod_score":1 + }] - results_1=get_genofile_samplelist(self.dataset) - self.assertEqual(results_1,["S1","S2","S3","S4"]) - self.group.genofile="~/genofiles/g2_file" - result_2=get_genofile_samplelist(self.dataset) - self.assertEqual(result_2,[]) + marker_2=[{ + "name":"MK1", + "chr":"C1", + "cM":"1", + "Mb":"12000", + "genotypes":[], + "dominance":"TT", + "additive":"VA", + "p_wald":4.6 + }] + results=trim_markers_for_figure(markers) + result_2=trim_markers_for_figure(marker_2) + expected=[ + { + "name":"MK1", + "chr":"C1", + "cM":"1", + "Mb":"12000", + "genotypes":[], + "dominance":"TT", + "additive":"VA", + "lod_score":0.5 + }, + { + "name":"MK1", + "chr":"C3", + "cM":"45", + "Mb":"1", + "genotypes":[], + "dominance":"Tt", + "additive":"VE", + "lod_score":1 + } - @mock.patch("wqflask.marker_regression.run_mapping.data_set") - def test_geno_db_exists(self,mock_data_set): - mock_data_set.create_dataset.side_effect=[AttributeSetter({}),Exception()] - results_no_error=geno_db_exists(self.dataset) - results_with_error=geno_db_exists(self.dataset) + ] + self.assertEqual(results,expected) + self.assertEqual(result_2,marker_2) - self.assertEqual(mock_data_set.create_dataset.call_count,2) - self.assertEqual(results_with_error,"False") - self.assertEqual(results_no_error,"True") + def test_export_mapping_results(self): + datetime_mock=mock.Mock(wraps=datetime.datetime) + datetime_mock.now.return_value=datetime.datetime(2019,9,1,10,12,12) + markers=[{ + "name":"MK1", + "chr":"C1", + "cM":"1", + "Mb":"12000", + "genotypes":[], + "dominance":"TT", + "additive":"VA", + "lod_score":3 + }, + { + "name":"MK2", + "chr":"C2", + "cM":"15", + "Mb":"10000", + "genotypes":[], + "lod_score":7 + }, + { + "name":"MK1", + "chr":"C3", + "cM":"45", + "Mb":"1", + "genotypes":[], + "dominance":"Tt", + "additive":"VE", + "lod_score":7 + }] + with mock.patch("builtins.open", mock.mock_open()) as mock_open: + + # mock_open.assert_called_once_with("~/results","w+") + # filehandler=mock_open() + with mock.patch("wqflask.marker_regression.run_mapping.datetime.datetime",new=datetime_mock): + export_mapping_results(dataset=self.dataset,trait=self.trait,markers=markers,results_path="~/results",mapping_scale="physic",score_type="-log(p)") + + write_calls=[ + mock.call('Time/Date: 09/01/19 / 10:12:12\n'), + mock.call('Population: Human GP1_\n'),mock.call('Data Set: dataser_1\n'), + mock.call('Gene Symbol: IGFI\n'), mock.call('Location: X1 @ 123313 Mb\n'), + mock.call('\n'), mock.call('Name,Chr,'), + mock.call('Mb,-log(p)'), mock.call('Cm,-log(p)'), + mock.call(',Additive'),mock.call(',Dominance'), + mock.call('\n'),mock.call('MK1,C1,'), + mock.call('12000,'), mock.call('1,'), + mock.call('3'), mock.call(',VA'), + mock.call(',TT'),mock.call('\n'), + mock.call('MK2,C2,'),mock.call('10000,'), + mock.call('15,'), mock.call('7'), + mock.call('\n'), mock.call('MK1,C3,'), + mock.call('1,'),mock.call('45,'), + mock.call('7'), mock.call(',VE'), + mock.call(',Tt') + ] + mock_open.assert_called_once_with("~/results","w+") + filehandler=mock_open() + filehandler.write.assert_has_calls(write_calls) \ No newline at end of file -- cgit v1.2.3 From 96dd0a10f0bfe66afab9701dd028f169d63cdae5 Mon Sep 17 00:00:00 2001 From: Alexanderlacuna Date: Tue, 10 Nov 2020 19:56:07 +0300 Subject: add tests for write input for browser in marker_regression/run_mapping.py --- .../wqflask/marker_regression/test_run_mapping.py | 277 +++++++++++---------- 1 file changed, 144 insertions(+), 133 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/wqflask/marker_regression/test_run_mapping.py b/wqflask/tests/wqflask/marker_regression/test_run_mapping.py index e925ad28..6521c41d 100644 --- a/wqflask/tests/wqflask/marker_regression/test_run_mapping.py +++ b/wqflask/tests/wqflask/marker_regression/test_run_mapping.py @@ -24,9 +24,11 @@ class MockDataSetGroup(AttributeSetter): class TestRunMapping(unittest.TestCase): def setUp(self): self.group = MockDataSetGroup( - {"genofile": "~/genofiles/g1_file", "name": "GP1_","species":"Human"}) - self.dataset = AttributeSetter({"fullname":"dataser_1","group": self.group,"type":"ProbeSet"}) - self.trait=AttributeSetter({"symbol":"IGFI","chr":"X1","mb":123313}) + {"genofile": "~/genofiles/g1_file", "name": "GP1_", "species": "Human"}) + self.dataset = AttributeSetter( + {"fullname": "dataser_1", "group": self.group, "type": "ProbeSet"}) + self.trait = AttributeSetter( + {"symbol": "IGFI", "chr": "X1", "mb": 123313}) def tearDown(self): self.dataset = AttributeSetter( @@ -51,137 +53,146 @@ class TestRunMapping(unittest.TestCase): self.assertEqual(results_with_error, "False") self.assertEqual(results_no_error, "True") - def test_trim_markers_for_figure(self): - - markers=[{ - "name":"MK1", - "chr":"C1", - "cM":"1", - "Mb":"12000", - "genotypes":[], - "dominance":"TT", - "additive":"VA", - "lod_score":0.5 - }, - { - "name":"MK2", - "chr":"C2", - "cM":"15", - "Mb":"10000", - "genotypes":[], - "lod_score":0.7 - }, - { - "name":"MK1", - "chr":"C3", - "cM":"45", - "Mb":"1", - "genotypes":[], - "dominance":"Tt", - "additive":"VE", - "lod_score":1 - }] - - marker_2=[{ - "name":"MK1", - "chr":"C1", - "cM":"1", - "Mb":"12000", - "genotypes":[], - "dominance":"TT", - "additive":"VA", - "p_wald":4.6 - }] - results=trim_markers_for_figure(markers) - result_2=trim_markers_for_figure(marker_2) - expected=[ - { - "name":"MK1", - "chr":"C1", - "cM":"1", - "Mb":"12000", - "genotypes":[], - "dominance":"TT", - "additive":"VA", - "lod_score":0.5 - }, - { - "name":"MK1", - "chr":"C3", - "cM":"45", - "Mb":"1", - "genotypes":[], - "dominance":"Tt", - "additive":"VE", - "lod_score":1 - } - - ] - self.assertEqual(results,expected) - self.assertEqual(result_2,marker_2) + markers = [{ + "name": "MK1", + "chr": "C1", + "cM": "1", + "Mb": "12000", + "genotypes": [], + "dominance":"TT", + "additive":"VA", + "lod_score":0.5 + }, + { + "name": "MK2", + "chr": "C2", + "cM": "15", + "Mb": "10000", + "genotypes": [], + "lod_score":0.7 + }, + { + "name": "MK1", + "chr": "C3", + "cM": "45", + "Mb": "1", + "genotypes": [], + "dominance":"Tt", + "additive":"VE", + "lod_score":1 + }] + + marker_2 = [{ + "name": "MK1", + "chr": "C1", + "cM": "1", + "Mb": "12000", + "genotypes": [], + "dominance":"TT", + "additive":"VA", + "p_wald":4.6 + }] + results = trim_markers_for_figure(markers) + result_2 = trim_markers_for_figure(marker_2) + expected = [ + { + "name": "MK1", + "chr": "C1", + "cM": "1", + "Mb": "12000", + "genotypes": [], + "dominance":"TT", + "additive":"VA", + "lod_score":0.5 + }, + { + "name": "MK1", + "chr": "C3", + "cM": "45", + "Mb": "1", + "genotypes": [], + "dominance":"Tt", + "additive":"VE", + "lod_score":1 + } + + ] + self.assertEqual(results, expected) + self.assertEqual(result_2, marker_2) def test_export_mapping_results(self): - datetime_mock=mock.Mock(wraps=datetime.datetime) - datetime_mock.now.return_value=datetime.datetime(2019,9,1,10,12,12) - - markers=[{ - "name":"MK1", - "chr":"C1", - "cM":"1", - "Mb":"12000", - "genotypes":[], - "dominance":"TT", - "additive":"VA", - "lod_score":3 - }, - { - "name":"MK2", - "chr":"C2", - "cM":"15", - "Mb":"10000", - "genotypes":[], - "lod_score":7 - }, - { - "name":"MK1", - "chr":"C3", - "cM":"45", - "Mb":"1", - "genotypes":[], - "dominance":"Tt", - "additive":"VE", - "lod_score":7 - }] - - with mock.patch("builtins.open", mock.mock_open()) as mock_open: - - # mock_open.assert_called_once_with("~/results","w+") - # filehandler=mock_open() - with mock.patch("wqflask.marker_regression.run_mapping.datetime.datetime",new=datetime_mock): - export_mapping_results(dataset=self.dataset,trait=self.trait,markers=markers,results_path="~/results",mapping_scale="physic",score_type="-log(p)") - - - write_calls=[ - mock.call('Time/Date: 09/01/19 / 10:12:12\n'), - mock.call('Population: Human GP1_\n'),mock.call('Data Set: dataser_1\n'), - mock.call('Gene Symbol: IGFI\n'), mock.call('Location: X1 @ 123313 Mb\n'), - mock.call('\n'), mock.call('Name,Chr,'), - mock.call('Mb,-log(p)'), mock.call('Cm,-log(p)'), - mock.call(',Additive'),mock.call(',Dominance'), - mock.call('\n'),mock.call('MK1,C1,'), - mock.call('12000,'), mock.call('1,'), - mock.call('3'), mock.call(',VA'), - mock.call(',TT'),mock.call('\n'), - mock.call('MK2,C2,'),mock.call('10000,'), - mock.call('15,'), mock.call('7'), - mock.call('\n'), mock.call('MK1,C3,'), - mock.call('1,'),mock.call('45,'), - mock.call('7'), mock.call(',VE'), - mock.call(',Tt') - - ] - mock_open.assert_called_once_with("~/results","w+") - filehandler=mock_open() - filehandler.write.assert_has_calls(write_calls) \ No newline at end of file + datetime_mock = mock.Mock(wraps=datetime.datetime) + datetime_mock.now.return_value = datetime.datetime( + 2019, 9, 1, 10, 12, 12) + + markers = [{ + "name": "MK1", + "chr": "C1", + "cM": "1", + "Mb": "12000", + "genotypes": [], + "dominance":"TT", + "additive":"VA", + "lod_score":3 + }, + { + "name": "MK2", + "chr": "C2", + "cM": "15", + "Mb": "10000", + "genotypes": [], + "lod_score":7 + }, + { + "name": "MK1", + "chr": "C3", + "cM": "45", + "Mb": "1", + "genotypes": [], + "dominance":"Tt", + "additive":"VE", + "lod_score":7 + }] + + with mock.patch("builtins.open", mock.mock_open()) as mock_open: + + with mock.patch("wqflask.marker_regression.run_mapping.datetime.datetime", new=datetime_mock): + export_mapping_results(dataset=self.dataset, trait=self.trait, markers=markers, + results_path="~/results", mapping_scale="physic", score_type="-log(p)") + + write_calls = [ + mock.call('Time/Date: 09/01/19 / 10:12:12\n'), + mock.call('Population: Human GP1_\n'), mock.call( + 'Data Set: dataser_1\n'), + mock.call('Gene Symbol: IGFI\n'), mock.call( + 'Location: X1 @ 123313 Mb\n'), + mock.call('\n'), mock.call('Name,Chr,'), + mock.call('Mb,-log(p)'), mock.call('Cm,-log(p)'), + mock.call(',Additive'), mock.call(',Dominance'), + mock.call('\n'), mock.call('MK1,C1,'), + mock.call('12000,'), mock.call('1,'), + mock.call('3'), mock.call(',VA'), + mock.call(',TT'), mock.call('\n'), + mock.call('MK2,C2,'), mock.call('10000,'), + mock.call('15,'), mock.call('7'), + mock.call('\n'), mock.call('MK1,C3,'), + mock.call('1,'), mock.call('45,'), + mock.call('7'), mock.call(',VE'), + mock.call(',Tt') + + ] + mock_open.assert_called_once_with("~/results", "w+") + filehandler = mock_open() + filehandler.write.assert_has_calls(write_calls) + + + @mock.patch("wqflask.marker_regression.run_mapping.random.choice") + def test_write_input_for_browser(self,mock_choice): + mock_choice.side_effect=["F","i","l","e","s","x"] + with mock.patch("builtins.open",mock.mock_open()) as mock_open: + expected=['GP1__Filesx_GWAS', 'GP1__Filesx_ANNOT'] + + results=write_input_for_browser(this_dataset=self.dataset,gwas_results={},annotations={}) + self.assertEqual(results,expected) -- cgit v1.2.3 From 424f44c0656da8f99dce0fa0a00bd5e6ba9bace3 Mon Sep 17 00:00:00 2001 From: Alexanderlacuna Date: Wed, 11 Nov 2020 23:05:17 +0300 Subject: add tests for marker_regression/gemma_mapping.py --- wqflask/tests/wqflask/marker_regression/test_gemma_mapping.py | 3 +++ 1 file changed, 3 insertions(+) (limited to 'wqflask/tests') diff --git a/wqflask/tests/wqflask/marker_regression/test_gemma_mapping.py b/wqflask/tests/wqflask/marker_regression/test_gemma_mapping.py index 06ce55d8..ed72cb33 100644 --- a/wqflask/tests/wqflask/marker_regression/test_gemma_mapping.py +++ b/wqflask/tests/wqflask/marker_regression/test_gemma_mapping.py @@ -151,18 +151,21 @@ X\tgn7\t2324424\tQ\tE\tA\tP\tMMB\tCDE\t0.4 mock_open.assert_called_once_with( "/home/user/img/gema_file_output.assoc.txt") self.assertEqual(results, expected) + @mock.patch("wqflask.marker_regression.gemma_mapping.webqtlConfig.GENERATED_IMAGE_DIR", "/home/user/img") def test_parse_gemma_output_empty_return(self): output_file_results = """chr\t today""" with mock.patch("builtins.open", mock.mock_open(read_data=output_file_results)) as mock_open: results = parse_gemma_output(genofile_name="gema_file") self.assertEqual(results, []) + @mock.patch("wqflask.marker_regression.gemma_mapping.TEMPDIR", "/home/tmp") @mock.patch("wqflask.marker_regression.gemma_mapping.os") def test_parse_loco_output_file_found(self, mock_os): mock_os.path.isfile.return_value = True file_to_write = """{"files":["file_1","file_2"]}""" pass + @mock.patch("wqflask.marker_regression.gemma_mapping.TEMPDIR", "/home/tmp") @mock.patch("wqflask.marker_regression.gemma_mapping.os") def test_parse_loco_output_file_not_found(self, mock_os): -- cgit v1.2.3 From 3396e1f008f3605439b38837f7a50407588d1f9b Mon Sep 17 00:00:00 2001 From: Alexanderlacuna Date: Wed, 11 Nov 2020 23:06:27 +0300 Subject: add tests for marker_regression/run_mapping.py --- .../wqflask/marker_regression/test_run_mapping.py | 85 ++++++++++++++++++++++ 1 file changed, 85 insertions(+) (limited to 'wqflask/tests') diff --git a/wqflask/tests/wqflask/marker_regression/test_run_mapping.py b/wqflask/tests/wqflask/marker_regression/test_run_mapping.py index 6521c41d..be6e6e48 100644 --- a/wqflask/tests/wqflask/marker_regression/test_run_mapping.py +++ b/wqflask/tests/wqflask/marker_regression/test_run_mapping.py @@ -7,6 +7,8 @@ from wqflask.marker_regression.run_mapping import geno_db_exists from wqflask.marker_regression.run_mapping import write_input_for_browser from wqflask.marker_regression.run_mapping import export_mapping_results from wqflask.marker_regression.run_mapping import trim_markers_for_figure +from wqflask.marker_regression.run_mapping import get_perm_strata +from wqflask.marker_regression.run_mapping import get_chr_lengths class AttributeSetter: @@ -23,10 +25,27 @@ class MockDataSetGroup(AttributeSetter): class TestRunMapping(unittest.TestCase): def setUp(self): + self.group = MockDataSetGroup( {"genofile": "~/genofiles/g1_file", "name": "GP1_", "species": "Human"}) + chromosomes={ + "3":AttributeSetter({ + "name":"C1", + "length":"0.04" + }), + "4":AttributeSetter({ + "name":"C2", + "length":"0.03" + }), + "5":AttributeSetter({ + "name":"C4", + "length":"0.01" + }) + } self.dataset = AttributeSetter( {"fullname": "dataser_1", "group": self.group, "type": "ProbeSet"}) + + self.chromosomes=AttributeSetter({"chromosomes":chromosomes}) self.trait = AttributeSetter( {"symbol": "IGFI", "chr": "X1", "mb": 123313}) @@ -196,3 +215,69 @@ class TestRunMapping(unittest.TestCase): results=write_input_for_browser(this_dataset=self.dataset,gwas_results={},annotations={}) self.assertEqual(results,expected) + + + def test_get_perm_strata(self): + categorical_vars=["C1","C2","W1"] + used_samples=["S1","S2"] + sample_list=AttributeSetter({"sample_attribute_values":{ + "S1":{ + "C1":"c1_value", + "C2":"c2_value", + "W1":"w1_value" + + }, + "S2":{ + "W1":"w2_value", + "W2":"w2_value" + + }, + "S3":{ + + "C1":"c1_value", + "C2":"c2_value" + + }, + + }}) + + results=get_perm_strata(this_trait={},sample_list=sample_list,categorical_vars=categorical_vars,used_samples=used_samples) + self.assertEqual(results,[2,1]) + + + def test_get_chr_length(self): + chromosomes=AttributeSetter({"chromosomes":self.chromosomes}) + dataset=AttributeSetter({"species":chromosomes}) + results=get_chr_lengths(mapping_scale="physic",mapping_method="reaper",dataset=dataset,qtl_results=[]) + chr_lengths=[] + for key,chromo in self.chromosomes.chromosomes.items(): + chr_lengths.append({"chr":chromo.name,"size":chromo.length}) + + self.assertEqual(chr_lengths,results) + + qtl_results=[{ + "chr":"16", + "cM":"0.2" + }, + { + "chr":"12", + "cM":"0.5" + }, + { + "chr":"18", + "cM":"0.1" + }, + { + "chr":"22", + "cM":"0.4" + }, + ] + + + + result_with_other_mapping_scale=get_chr_lengths(mapping_scale="other",mapping_method="reaper",dataset=dataset,qtl_results=qtl_results) + expected_value= [{'chr': '1', 'size': '0'}, {'chr': '16', 'size': '500000.0'}, {'chr': '18', 'size': '400000.0'}] + + self.assertEqual(result_with_other_mapping_scale,expected_value) + + -- cgit v1.2.3 From 8f85c96b2094a9ce722b93a0e375ec3de90c959a Mon Sep 17 00:00:00 2001 From: Alexanderlacuna Date: Wed, 11 Nov 2020 23:08:14 +0300 Subject: add tests for marker_regression/qtlreaper_mapping.py --- .../marker_regression/test_qtlreaper_mapping.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 wqflask/tests/wqflask/marker_regression/test_qtlreaper_mapping.py (limited to 'wqflask/tests') diff --git a/wqflask/tests/wqflask/marker_regression/test_qtlreaper_mapping.py b/wqflask/tests/wqflask/marker_regression/test_qtlreaper_mapping.py new file mode 100644 index 00000000..7ece663a --- /dev/null +++ b/wqflask/tests/wqflask/marker_regression/test_qtlreaper_mapping.py @@ -0,0 +1,22 @@ +import unittest +from unittest import mock +from wqflask.marker_regression.qtlreaper_mapping import gen_pheno_txt_file +from wqflask.marker_regression.qtlreaper_mapping import natural_sort + +#issues some methods in genofile object are not defined +#modify samples should equal to vals +class TestQtlReaperMapping(unittest.TestCase): + @mock.patch("wqflask.marker_regression.qtlreaper_mapping.TEMPDIR", "/home/user/data") + def test_gen_pheno_txt_file(self): + vals=["V1","x","V4","V3","x"] + samples=["S1","S2","S3","S4","S5"] + trait_filename="trait_file" + with mock.patch("builtins.open", mock.mock_open())as mock_open: + gen_pheno_txt_file(samples=samples,vals=vals,trait_filename=trait_filename) + mock_open.assert_called_once_with("/home/user/data/gn2/trait_file.txt","w") + filehandler=mock_open() + write_calls= [mock.call('Trait\t'),mock.call('S1\tS3\tS4\n'),mock.call('T1\t'),mock.call('V1\tV4\tV3')] + + filehandler.write.assert_has_calls(write_calls) + + -- cgit v1.2.3 From e63e85868ed7b63bbe784368b3c1babf0d1f2088 Mon Sep 17 00:00:00 2001 From: Alexanderlacuna Date: Wed, 11 Nov 2020 23:09:01 +0300 Subject: add tests for marker_regression/rqtl_mapping.py --- .../wqflask/marker_regression/test_rqtl_mapping.py | 55 ++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 wqflask/tests/wqflask/marker_regression/test_rqtl_mapping.py (limited to 'wqflask/tests') diff --git a/wqflask/tests/wqflask/marker_regression/test_rqtl_mapping.py b/wqflask/tests/wqflask/marker_regression/test_rqtl_mapping.py new file mode 100644 index 00000000..641644cc --- /dev/null +++ b/wqflask/tests/wqflask/marker_regression/test_rqtl_mapping.py @@ -0,0 +1,55 @@ +import unittest +from unittest import mock +from wqflask import app +from wqflask.marker_regression.rqtl_mapping import get_trait_data_type +from wqflask.marker_regression.rqtl_mapping import sanitize_rqtl_phenotype +from wqflask.marker_regression.rqtl_mapping import sanitize_rqtl_names + +class TestRqtlMapping(unittest.TestCase): + + def setUp(self): + self.app_context=app.app_context() + self.app_context.push() + + def tearDown(self): + self.app_context.pop() + + + @mock.patch("wqflask.marker_regression.rqtl_mapping.g") + @mock.patch("wqflask.marker_regression.rqtl_mapping.logger") + def test_get_trait_data_type_found(self,mock_logger,mock_db): + caller_value="""SELECT value FROM TraitMetadata WHERE type='trait_data_type'""" + mock_db.db.execute.return_value.fetchone.return_value=["""{"type":"trait_data_type","name":"T1","traid_id":"fer434f"}"""] + results=get_trait_data_type("traid_id") + mock_db.db.execute.assert_called_with(caller_value) + self.assertEqual(results,"fer434f") + + + @mock.patch("wqflask.marker_regression.rqtl_mapping.g") + @mock.patch("wqflask.marker_regression.rqtl_mapping.logger") + def test_get_trait_data_type_not_found(self,mock_logger,mock_db): + caller_value="""SELECT value FROM TraitMetadata WHERE type='trait_data_type'""" + mock_db.db.execute.return_value.fetchone.return_value=["""{"type":"trait_data_type","name":"T1","traid_id":"fer434f"}"""] + results=get_trait_data_type("other") + mock_db.db.execute.assert_called_with(caller_value) + self.assertEqual(results,"numeric") + + def test_sanitize_rqtl_phenotype(self): + vals=['f',"x","r","x","x"] + results=sanitize_rqtl_phenotype(vals) + expected_phenotype_string='c(f,NA,r,NA,NA)' + + self.assertEqual(results,expected_phenotype_string) + + def test_sanitize_rqtl_names(self): + vals=['f',"x","r","x","x"] + expected_sanitized_name="c('f',NA,'r',NA,NA)" + results=sanitize_rqtl_names(vals) + self.assertEqual(expected_sanitized_name,results) + + + + + + + -- cgit v1.2.3 From f4dbdc51102d942079c7159ac48071282ec995ea Mon Sep 17 00:00:00 2001 From: Alexanderlacuna Date: Thu, 12 Nov 2020 00:45:03 +0300 Subject: modify tests for marker regression --- .../marker_regression/test_gemma_mapping.py | 8 ++ .../marker_regression/test_plink_mapping.py | 4 + .../marker_regression/test_qtlreaper_mapping.py | 3 +- .../wqflask/marker_regression/test_rqtl_mapping.py | 13 +- .../wqflask/marker_regression/test_run_mapping.py | 153 +++++++++++---------- 5 files changed, 93 insertions(+), 88 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/wqflask/marker_regression/test_gemma_mapping.py b/wqflask/tests/wqflask/marker_regression/test_gemma_mapping.py index ed72cb33..e47c8335 100644 --- a/wqflask/tests/wqflask/marker_regression/test_gemma_mapping.py +++ b/wqflask/tests/wqflask/marker_regression/test_gemma_mapping.py @@ -24,6 +24,7 @@ class TestGemmaMapping(unittest.TestCase): @mock.patch("wqflask.marker_regression.gemma_mapping.parse_loco_output") def test_run_gemma_first_run_loco_set_false(self, mock_parse_loco): + """add tests for gemma function where first run is set to false""" dataset = AttributeSetter( {"group": AttributeSetter({"genofile": "genofile.geno"})}) @@ -50,6 +51,7 @@ class TestGemmaMapping(unittest.TestCase): @mock.patch("wqflask.marker_regression.gemma_mapping.os") @mock.patch("wqflask.marker_regression.gemma_mapping.gen_pheno_txt_file") def test_run_gemma_first_run_set_true(self, mock_gen_pheno_txt, mock_os, mock_choice, mock_gen_covar, mock_flat_files, mock_logger, mock_parse_loco): + """add tests for run_gemma where first run is set to true""" chromosomes = [] for i in range(1, 5): chromosomes.append(AttributeSetter({"name": f"CH{i}"})) @@ -81,6 +83,7 @@ class TestGemmaMapping(unittest.TestCase): @mock.patch("wqflask.marker_regression.gemma_mapping.TEMPDIR", "/home/user/data") def test_gen_pheno_txt_file(self): + """add tests for generating pheno txt file""" with mock.patch("builtins.open", mock.mock_open())as mock_open: gen_pheno_txt_file(this_dataset={}, genofile_name="", vals=[ "x", "w", "q", "we", "R"], trait_filename="fitr.re") @@ -97,6 +100,7 @@ class TestGemmaMapping(unittest.TestCase): @mock.patch("wqflask.marker_regression.gemma_mapping.create_trait") @mock.patch("wqflask.marker_regression.gemma_mapping.create_dataset") def test_gen_covariates_file(self, create_dataset, create_trait, flat_files): + """add tests for generating covariates files""" covariates = "X1:X2,Y1:Y2,M1:M3,V1:V2" samplelist = ["X1", "X2", "X3", "X4"] create_dataset_side_effect = [] @@ -138,6 +142,7 @@ class TestGemmaMapping(unittest.TestCase): @mock.patch("wqflask.marker_regression.gemma_mapping.webqtlConfig.GENERATED_IMAGE_DIR", "/home/user/img/") def test_parse_gemma_output_obj_returned(self): + """add test for generating gemma output with obj returned""" file = """X/Y\t gn2\t21\tQ\tE\tA\tP\tMMB\tCDE\t0.5 X/Y\tgn2\t21322\tQ\tE\tA\tP\tMMB\tCDE\t0.5 chr\tgn1\t12312\tQ\tE\tA\tP\tMMB\tCDE\t0.7 @@ -154,6 +159,7 @@ X\tgn7\t2324424\tQ\tE\tA\tP\tMMB\tCDE\t0.4 @mock.patch("wqflask.marker_regression.gemma_mapping.webqtlConfig.GENERATED_IMAGE_DIR", "/home/user/img") def test_parse_gemma_output_empty_return(self): + """add tests for parse gemma output where nothing returned""" output_file_results = """chr\t today""" with mock.patch("builtins.open", mock.mock_open(read_data=output_file_results)) as mock_open: results = parse_gemma_output(genofile_name="gema_file") @@ -162,6 +168,7 @@ X\tgn7\t2324424\tQ\tE\tA\tP\tMMB\tCDE\t0.4 @mock.patch("wqflask.marker_regression.gemma_mapping.TEMPDIR", "/home/tmp") @mock.patch("wqflask.marker_regression.gemma_mapping.os") def test_parse_loco_output_file_found(self, mock_os): + """add tests for parse loco output file found""" mock_os.path.isfile.return_value = True file_to_write = """{"files":["file_1","file_2"]}""" pass @@ -169,6 +176,7 @@ X\tgn7\t2324424\tQ\tE\tA\tP\tMMB\tCDE\t0.4 @mock.patch("wqflask.marker_regression.gemma_mapping.TEMPDIR", "/home/tmp") @mock.patch("wqflask.marker_regression.gemma_mapping.os") def test_parse_loco_output_file_not_found(self, mock_os): + """add tests for parse loco output file not found""" mock_os.path.isfile.return_value = False file_to_write = """{"files":["file_1","file_2"]}""" diff --git a/wqflask/tests/wqflask/marker_regression/test_plink_mapping.py b/wqflask/tests/wqflask/marker_regression/test_plink_mapping.py index a5fa0c04..428f45b9 100644 --- a/wqflask/tests/wqflask/marker_regression/test_plink_mapping.py +++ b/wqflask/tests/wqflask/marker_regression/test_plink_mapping.py @@ -15,6 +15,7 @@ class AttributeSetter: class TestPlinkMapping(unittest.TestCase): def test_build_line_list(self): + """testing for building line list""" line_1 = "this is line one test" irregular_line = " this is an, irregular line " exp_line1 = ["this", "is", "line", "one", "test"] @@ -26,6 +27,7 @@ class TestPlinkMapping(unittest.TestCase): @mock.patch("wqflask.marker_regression.plink_mapping.flat_files") def test_get_samples_from_ped_file(self, mock_flat_files): + """test for getting samples from ped file""" dataset = AttributeSetter({"group": AttributeSetter({"name": "n_1"})}) file_sample = """Expected_1\tline test Expected_2\there @@ -41,6 +43,7 @@ Expected_2\there @mock.patch("wqflask.marker_regression.plink_mapping.TMPDIR", "/home/user/data/") @mock.patch("wqflask.marker_regression.plink_mapping.get_samples_from_ped_file") def test_gen_pheno_txt_file_plink(self, mock_samples): + """test for getting gen_pheno txt file""" mock_samples.return_value = ["Expected_1", "Expected_2", "Expected_3"] trait = AttributeSetter({"name": "TX"}) @@ -62,6 +65,7 @@ Expected_2\there @mock.patch("wqflask.marker_regression.plink_mapping.TMPDIR", "/home/user/data/") @mock.patch("wqflask.marker_regression.plink_mapping.build_line_list") def test_parse_plink_output(self, mock_line_list): + """test for parsing plink output""" chromosomes = [0, 34, 110, 89, 123, 23, 2] species = AttributeSetter( {"name": "S1", "chromosomes": AttributeSetter({"chromosomes": chromosomes})}) diff --git a/wqflask/tests/wqflask/marker_regression/test_qtlreaper_mapping.py b/wqflask/tests/wqflask/marker_regression/test_qtlreaper_mapping.py index 7ece663a..b47f877a 100644 --- a/wqflask/tests/wqflask/marker_regression/test_qtlreaper_mapping.py +++ b/wqflask/tests/wqflask/marker_regression/test_qtlreaper_mapping.py @@ -1,13 +1,12 @@ import unittest from unittest import mock from wqflask.marker_regression.qtlreaper_mapping import gen_pheno_txt_file -from wqflask.marker_regression.qtlreaper_mapping import natural_sort #issues some methods in genofile object are not defined #modify samples should equal to vals class TestQtlReaperMapping(unittest.TestCase): @mock.patch("wqflask.marker_regression.qtlreaper_mapping.TEMPDIR", "/home/user/data") - def test_gen_pheno_txt_file(self): + def test_gen_pheno_txt_file(self): vals=["V1","x","V4","V3","x"] samples=["S1","S2","S3","S4","S5"] trait_filename="trait_file" diff --git a/wqflask/tests/wqflask/marker_regression/test_rqtl_mapping.py b/wqflask/tests/wqflask/marker_regression/test_rqtl_mapping.py index 641644cc..9fd32a30 100644 --- a/wqflask/tests/wqflask/marker_regression/test_rqtl_mapping.py +++ b/wqflask/tests/wqflask/marker_regression/test_rqtl_mapping.py @@ -18,23 +18,15 @@ class TestRqtlMapping(unittest.TestCase): @mock.patch("wqflask.marker_regression.rqtl_mapping.g") @mock.patch("wqflask.marker_regression.rqtl_mapping.logger") def test_get_trait_data_type_found(self,mock_logger,mock_db): + """test for getting trait data_type return True""" caller_value="""SELECT value FROM TraitMetadata WHERE type='trait_data_type'""" mock_db.db.execute.return_value.fetchone.return_value=["""{"type":"trait_data_type","name":"T1","traid_id":"fer434f"}"""] results=get_trait_data_type("traid_id") mock_db.db.execute.assert_called_with(caller_value) self.assertEqual(results,"fer434f") - - @mock.patch("wqflask.marker_regression.rqtl_mapping.g") - @mock.patch("wqflask.marker_regression.rqtl_mapping.logger") - def test_get_trait_data_type_not_found(self,mock_logger,mock_db): - caller_value="""SELECT value FROM TraitMetadata WHERE type='trait_data_type'""" - mock_db.db.execute.return_value.fetchone.return_value=["""{"type":"trait_data_type","name":"T1","traid_id":"fer434f"}"""] - results=get_trait_data_type("other") - mock_db.db.execute.assert_called_with(caller_value) - self.assertEqual(results,"numeric") - def test_sanitize_rqtl_phenotype(self): + """test for sanitizing rqtl phenotype""" vals=['f',"x","r","x","x"] results=sanitize_rqtl_phenotype(vals) expected_phenotype_string='c(f,NA,r,NA,NA)' @@ -42,6 +34,7 @@ class TestRqtlMapping(unittest.TestCase): self.assertEqual(results,expected_phenotype_string) def test_sanitize_rqtl_names(self): + """test for sanitzing rqtl names""" vals=['f',"x","r","x","x"] expected_sanitized_name="c('f',NA,'r',NA,NA)" results=sanitize_rqtl_names(vals) diff --git a/wqflask/tests/wqflask/marker_regression/test_run_mapping.py b/wqflask/tests/wqflask/marker_regression/test_run_mapping.py index be6e6e48..2af4c3e3 100644 --- a/wqflask/tests/wqflask/marker_regression/test_run_mapping.py +++ b/wqflask/tests/wqflask/marker_regression/test_run_mapping.py @@ -28,24 +28,24 @@ class TestRunMapping(unittest.TestCase): self.group = MockDataSetGroup( {"genofile": "~/genofiles/g1_file", "name": "GP1_", "species": "Human"}) - chromosomes={ - "3":AttributeSetter({ - "name":"C1", - "length":"0.04" - }), - "4":AttributeSetter({ - "name":"C2", - "length":"0.03" - }), - "5":AttributeSetter({ - "name":"C4", - "length":"0.01" - }) - } + chromosomes = { + "3": AttributeSetter({ + "name": "C1", + "length": "0.04" + }), + "4": AttributeSetter({ + "name": "C2", + "length": "0.03" + }), + "5": AttributeSetter({ + "name": "C4", + "length": "0.01" + }) + } self.dataset = AttributeSetter( {"fullname": "dataser_1", "group": self.group, "type": "ProbeSet"}) - self.chromosomes=AttributeSetter({"chromosomes":chromosomes}) + self.chromosomes = AttributeSetter({"chromosomes": chromosomes}) self.trait = AttributeSetter( {"symbol": "IGFI", "chr": "X1", "mb": 123313}) @@ -142,6 +142,7 @@ class TestRunMapping(unittest.TestCase): self.assertEqual(result_2, marker_2) def test_export_mapping_results(self): + """test for exporting mapping results""" datetime_mock = mock.Mock(wraps=datetime.datetime) datetime_mock.now.return_value = datetime.datetime( 2019, 9, 1, 10, 12, 12) @@ -206,78 +207,78 @@ class TestRunMapping(unittest.TestCase): filehandler = mock_open() filehandler.write.assert_has_calls(write_calls) - @mock.patch("wqflask.marker_regression.run_mapping.random.choice") - def test_write_input_for_browser(self,mock_choice): - mock_choice.side_effect=["F","i","l","e","s","x"] - with mock.patch("builtins.open",mock.mock_open()) as mock_open: - expected=['GP1__Filesx_GWAS', 'GP1__Filesx_ANNOT'] - - results=write_input_for_browser(this_dataset=self.dataset,gwas_results={},annotations={}) - self.assertEqual(results,expected) + def test_write_input_for_browser(self, mock_choice): + """test for writing input for browser""" + mock_choice.side_effect = ["F", "i", "l", "e", "s", "x"] + with mock.patch("builtins.open", mock.mock_open()) as mock_open: + expected = ['GP1__Filesx_GWAS', 'GP1__Filesx_ANNOT'] + results = write_input_for_browser( + this_dataset=self.dataset, gwas_results={}, annotations={}) + self.assertEqual(results, expected) def test_get_perm_strata(self): - categorical_vars=["C1","C2","W1"] - used_samples=["S1","S2"] - sample_list=AttributeSetter({"sample_attribute_values":{ - "S1":{ - "C1":"c1_value", - "C2":"c2_value", - "W1":"w1_value" + categorical_vars = ["C1", "C2", "W1"] + used_samples = ["S1", "S2"] + sample_list = AttributeSetter({"sample_attribute_values": { + "S1": { + "C1": "c1_value", + "C2": "c2_value", + "W1": "w1_value" - }, - "S2":{ - "W1":"w2_value", - "W2":"w2_value" + }, + "S2": { + "W1": "w2_value", + "W2": "w2_value" - }, - "S3":{ + }, + "S3": { - "C1":"c1_value", - "C2":"c2_value" + "C1": "c1_value", + "C2": "c2_value" - }, - - }}) + }, - results=get_perm_strata(this_trait={},sample_list=sample_list,categorical_vars=categorical_vars,used_samples=used_samples) - self.assertEqual(results,[2,1]) + }}) + results = get_perm_strata(this_trait={}, sample_list=sample_list, + categorical_vars=categorical_vars, used_samples=used_samples) + self.assertEqual(results, [2, 1]) def test_get_chr_length(self): - chromosomes=AttributeSetter({"chromosomes":self.chromosomes}) - dataset=AttributeSetter({"species":chromosomes}) - results=get_chr_lengths(mapping_scale="physic",mapping_method="reaper",dataset=dataset,qtl_results=[]) - chr_lengths=[] - for key,chromo in self.chromosomes.chromosomes.items(): - chr_lengths.append({"chr":chromo.name,"size":chromo.length}) - - self.assertEqual(chr_lengths,results) - - qtl_results=[{ - "chr":"16", - "cM":"0.2" - }, - { - "chr":"12", - "cM":"0.5" - }, - { - "chr":"18", - "cM":"0.1" - }, - { - "chr":"22", - "cM":"0.4" - }, - ] - - - - result_with_other_mapping_scale=get_chr_lengths(mapping_scale="other",mapping_method="reaper",dataset=dataset,qtl_results=qtl_results) - expected_value= [{'chr': '1', 'size': '0'}, {'chr': '16', 'size': '500000.0'}, {'chr': '18', 'size': '400000.0'}] - - self.assertEqual(result_with_other_mapping_scale,expected_value) + """test for getting chromosome length""" + chromosomes = AttributeSetter({"chromosomes": self.chromosomes}) + dataset = AttributeSetter({"species": chromosomes}) + results = get_chr_lengths( + mapping_scale="physic", mapping_method="reaper", dataset=dataset, qtl_results=[]) + chr_lengths = [] + for key, chromo in self.chromosomes.chromosomes.items(): + chr_lengths.append({"chr": chromo.name, "size": chromo.length}) + + self.assertEqual(chr_lengths, results) + + qtl_results = [{ + "chr": "16", + "cM": "0.2" + }, + { + "chr": "12", + "cM": "0.5" + }, + { + "chr": "18", + "cM": "0.1" + }, + { + "chr": "22", + "cM": "0.4" + }, + ] + result_with_other_mapping_scale = get_chr_lengths( + mapping_scale="other", mapping_method="reaper", dataset=dataset, qtl_results=qtl_results) + expected_value = [{'chr': '1', 'size': '0'}, { + 'chr': '16', 'size': '500000.0'}, {'chr': '18', 'size': '400000.0'}] + self.assertEqual(result_with_other_mapping_scale, expected_value) -- cgit v1.2.3 From a48e8d5e652551eb2d57953304ea0ec3587217ce Mon Sep 17 00:00:00 2001 From: Alexanderlacuna Date: Thu, 12 Nov 2020 21:11:28 +0300 Subject: add test for parse gemma output in marker_regression/gemma_mapping.py --- .../marker_regression/test_gemma_mapping.py | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/wqflask/marker_regression/test_gemma_mapping.py b/wqflask/tests/wqflask/marker_regression/test_gemma_mapping.py index e47c8335..bcc5dab9 100644 --- a/wqflask/tests/wqflask/marker_regression/test_gemma_mapping.py +++ b/wqflask/tests/wqflask/marker_regression/test_gemma_mapping.py @@ -167,11 +167,29 @@ X\tgn7\t2324424\tQ\tE\tA\tP\tMMB\tCDE\t0.4 @mock.patch("wqflask.marker_regression.gemma_mapping.TEMPDIR", "/home/tmp") @mock.patch("wqflask.marker_regression.gemma_mapping.os") - def test_parse_loco_output_file_found(self, mock_os): + @mock.patch("wqflask.marker_regression.gemma_mapping.json") + def test_parse_loco_output_file_found(self,mock_json,mock_os): """add tests for parse loco output file found""" + mock_json.load.return_value={ + "files":[["file_name","user","~/file1"], + ["file_name","user","~/file2"]] + } + return_file_1="""X/Y\t L1\t21\tQ\tE\tA\tP\tMMB\tCDE\t0.5 +X/Y\tL2\t21322\tQ\tE\tA\tP\tMMB\tCDE\t0.5 +chr\tL3\t12312\tQ\tE\tA\tP\tMMB\tCDE\t0.7""" + return_file_2="""chr\tother\t21322\tQ\tE\tA\tP\tMMB\tCDE\t0.5""" mock_os.path.isfile.return_value = True file_to_write = """{"files":["file_1","file_2"]}""" - pass + with mock.patch("builtins.open") as mock_open: + + handles=(mock.mock_open(read_data="gwas").return_value,mock.mock_open(read_data=return_file_1).return_value,mock.mock_open(read_data=return_file_2).return_value) + mock_open.side_effect=handles + results = parse_loco_output( + this_dataset={}, gwa_output_filename=".xw/") + expected_results= [{'name': ' L1', 'chr': 'X/Y', 'Mb': 2.1e-05, 'p_value': 0.5, 'lod_score': 0.3010299956639812}, {'name': 'L2', 'chr': 'X/Y', 'Mb': 0.021322, 'p_value': 0.5, 'lod_score': 0.3010299956639812}] + + self.assertEqual(expected_results,results) + @mock.patch("wqflask.marker_regression.gemma_mapping.TEMPDIR", "/home/tmp") @mock.patch("wqflask.marker_regression.gemma_mapping.os") -- cgit v1.2.3 From da794df7cf9094fc81edbcf007149db86bf68d01 Mon Sep 17 00:00:00 2001 From: Alexanderlacuna Date: Thu, 12 Nov 2020 21:12:48 +0300 Subject: add pep8 fixes in marker_regression/gemma_mapping.py --- .../marker_regression/test_gemma_mapping.py | 23 +++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/wqflask/marker_regression/test_gemma_mapping.py b/wqflask/tests/wqflask/marker_regression/test_gemma_mapping.py index bcc5dab9..a44ccb00 100644 --- a/wqflask/tests/wqflask/marker_regression/test_gemma_mapping.py +++ b/wqflask/tests/wqflask/marker_regression/test_gemma_mapping.py @@ -168,28 +168,29 @@ X\tgn7\t2324424\tQ\tE\tA\tP\tMMB\tCDE\t0.4 @mock.patch("wqflask.marker_regression.gemma_mapping.TEMPDIR", "/home/tmp") @mock.patch("wqflask.marker_regression.gemma_mapping.os") @mock.patch("wqflask.marker_regression.gemma_mapping.json") - def test_parse_loco_output_file_found(self,mock_json,mock_os): + def test_parse_loco_output_file_found(self, mock_json, mock_os): """add tests for parse loco output file found""" - mock_json.load.return_value={ - "files":[["file_name","user","~/file1"], - ["file_name","user","~/file2"]] + mock_json.load.return_value = { + "files": [["file_name", "user", "~/file1"], + ["file_name", "user", "~/file2"]] } - return_file_1="""X/Y\t L1\t21\tQ\tE\tA\tP\tMMB\tCDE\t0.5 + return_file_1 = """X/Y\t L1\t21\tQ\tE\tA\tP\tMMB\tCDE\t0.5 X/Y\tL2\t21322\tQ\tE\tA\tP\tMMB\tCDE\t0.5 chr\tL3\t12312\tQ\tE\tA\tP\tMMB\tCDE\t0.7""" - return_file_2="""chr\tother\t21322\tQ\tE\tA\tP\tMMB\tCDE\t0.5""" + return_file_2 = """chr\tother\t21322\tQ\tE\tA\tP\tMMB\tCDE\t0.5""" mock_os.path.isfile.return_value = True file_to_write = """{"files":["file_1","file_2"]}""" with mock.patch("builtins.open") as mock_open: - handles=(mock.mock_open(read_data="gwas").return_value,mock.mock_open(read_data=return_file_1).return_value,mock.mock_open(read_data=return_file_2).return_value) - mock_open.side_effect=handles + handles = (mock.mock_open(read_data="gwas").return_value, mock.mock_open( + read_data=return_file_1).return_value, mock.mock_open(read_data=return_file_2).return_value) + mock_open.side_effect = handles results = parse_loco_output( this_dataset={}, gwa_output_filename=".xw/") - expected_results= [{'name': ' L1', 'chr': 'X/Y', 'Mb': 2.1e-05, 'p_value': 0.5, 'lod_score': 0.3010299956639812}, {'name': 'L2', 'chr': 'X/Y', 'Mb': 0.021322, 'p_value': 0.5, 'lod_score': 0.3010299956639812}] - - self.assertEqual(expected_results,results) + expected_results = [{'name': ' L1', 'chr': 'X/Y', 'Mb': 2.1e-05, 'p_value': 0.5, 'lod_score': 0.3010299956639812}, { + 'name': 'L2', 'chr': 'X/Y', 'Mb': 0.021322, 'p_value': 0.5, 'lod_score': 0.3010299956639812}] + self.assertEqual(expected_results, results) @mock.patch("wqflask.marker_regression.gemma_mapping.TEMPDIR", "/home/tmp") @mock.patch("wqflask.marker_regression.gemma_mapping.os") -- cgit v1.2.3 From d4b3e8f43c4f4b10fb9614d80cb9d4e2a723c879 Mon Sep 17 00:00:00 2001 From: Alexanderlacuna Date: Thu, 12 Nov 2020 21:40:49 +0300 Subject: refactor code --- wqflask/tests/wqflask/marker_regression/test_gemma_mapping.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/wqflask/marker_regression/test_gemma_mapping.py b/wqflask/tests/wqflask/marker_regression/test_gemma_mapping.py index a44ccb00..af20c1b8 100644 --- a/wqflask/tests/wqflask/marker_regression/test_gemma_mapping.py +++ b/wqflask/tests/wqflask/marker_regression/test_gemma_mapping.py @@ -28,13 +28,12 @@ class TestGemmaMapping(unittest.TestCase): dataset = AttributeSetter( {"group": AttributeSetter({"genofile": "genofile.geno"})}) - output_files = "file1" - use_loco = False + output_file = "file1" mock_parse_loco.return_value = [] this_trait = AttributeSetter({"name": "t1"}) result = run_gemma(this_trait=this_trait, this_dataset=dataset, samples=[], vals=[ - ], covariates="", use_loco=True, first_run=False, output_files=output_files) + ], covariates="", use_loco=True, first_run=False, output_files=output_file) expected_results = ([], "file1") self.assertEqual(expected_results, result) -- cgit v1.2.3 From ceeae6fd087d91637c5007e0433ce347048fa96d Mon Sep 17 00:00:00 2001 From: Alexanderlacuna Date: Tue, 17 Nov 2020 22:31:10 +0300 Subject: use better function names --- .../tests/wqflask/marker_regression/test_gemma_mapping.py | 14 +++++++------- .../tests/wqflask/marker_regression/test_rqtl_mapping.py | 2 +- .../tests/wqflask/marker_regression/test_run_mapping.py | 2 +- 3 files changed, 9 insertions(+), 9 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/wqflask/marker_regression/test_gemma_mapping.py b/wqflask/tests/wqflask/marker_regression/test_gemma_mapping.py index af20c1b8..4fafd95a 100644 --- a/wqflask/tests/wqflask/marker_regression/test_gemma_mapping.py +++ b/wqflask/tests/wqflask/marker_regression/test_gemma_mapping.py @@ -23,7 +23,7 @@ class MockDatasetGroup(AttributeSetter): class TestGemmaMapping(unittest.TestCase): @mock.patch("wqflask.marker_regression.gemma_mapping.parse_loco_output") - def test_run_gemma_first_run_loco_set_false(self, mock_parse_loco): + def test_run_gemma_firstrun_set_false(self, mock_parse_loco): """add tests for gemma function where first run is set to false""" dataset = AttributeSetter( {"group": AttributeSetter({"genofile": "genofile.geno"})}) @@ -49,7 +49,7 @@ class TestGemmaMapping(unittest.TestCase): @mock.patch("wqflask.marker_regression.run_mapping.random.choice") @mock.patch("wqflask.marker_regression.gemma_mapping.os") @mock.patch("wqflask.marker_regression.gemma_mapping.gen_pheno_txt_file") - def test_run_gemma_first_run_set_true(self, mock_gen_pheno_txt, mock_os, mock_choice, mock_gen_covar, mock_flat_files, mock_logger, mock_parse_loco): + def test_run_gemma_firstrun_set_true(self, mock_gen_pheno_txt, mock_os, mock_choice, mock_gen_covar, mock_flat_files, mock_logger, mock_parse_loco): """add tests for run_gemma where first run is set to true""" chromosomes = [] for i in range(1, 5): @@ -140,7 +140,7 @@ class TestGemmaMapping(unittest.TestCase): '-9\t'), mock.call('-9\t'), mock.call('-9\t'), mock.call('-9\t'), mock.call('\n')]) @mock.patch("wqflask.marker_regression.gemma_mapping.webqtlConfig.GENERATED_IMAGE_DIR", "/home/user/img/") - def test_parse_gemma_output_obj_returned(self): + def test_parse_gemma_output(self): """add test for generating gemma output with obj returned""" file = """X/Y\t gn2\t21\tQ\tE\tA\tP\tMMB\tCDE\t0.5 X/Y\tgn2\t21322\tQ\tE\tA\tP\tMMB\tCDE\t0.5 @@ -157,7 +157,7 @@ X\tgn7\t2324424\tQ\tE\tA\tP\tMMB\tCDE\t0.4 self.assertEqual(results, expected) @mock.patch("wqflask.marker_regression.gemma_mapping.webqtlConfig.GENERATED_IMAGE_DIR", "/home/user/img") - def test_parse_gemma_output_empty_return(self): + def test_parse_gemma_output_with_empty_return(self): """add tests for parse gemma output where nothing returned""" output_file_results = """chr\t today""" with mock.patch("builtins.open", mock.mock_open(read_data=output_file_results)) as mock_open: @@ -167,7 +167,7 @@ X\tgn7\t2324424\tQ\tE\tA\tP\tMMB\tCDE\t0.4 @mock.patch("wqflask.marker_regression.gemma_mapping.TEMPDIR", "/home/tmp") @mock.patch("wqflask.marker_regression.gemma_mapping.os") @mock.patch("wqflask.marker_regression.gemma_mapping.json") - def test_parse_loco_output_file_found(self, mock_json, mock_os): + def test_parse_loco_outputfile_found(self, mock_json, mock_os): """add tests for parse loco output file found""" mock_json.load.return_value = { "files": [["file_name", "user", "~/file1"], @@ -193,8 +193,8 @@ chr\tL3\t12312\tQ\tE\tA\tP\tMMB\tCDE\t0.7""" @mock.patch("wqflask.marker_regression.gemma_mapping.TEMPDIR", "/home/tmp") @mock.patch("wqflask.marker_regression.gemma_mapping.os") - def test_parse_loco_output_file_not_found(self, mock_os): - """add tests for parse loco output file not found""" + def test_parse_loco_outputfile_not_found(self, mock_os): + """add tests for parse loco output where output file not found""" mock_os.path.isfile.return_value = False file_to_write = """{"files":["file_1","file_2"]}""" diff --git a/wqflask/tests/wqflask/marker_regression/test_rqtl_mapping.py b/wqflask/tests/wqflask/marker_regression/test_rqtl_mapping.py index 9fd32a30..69f53721 100644 --- a/wqflask/tests/wqflask/marker_regression/test_rqtl_mapping.py +++ b/wqflask/tests/wqflask/marker_regression/test_rqtl_mapping.py @@ -17,7 +17,7 @@ class TestRqtlMapping(unittest.TestCase): @mock.patch("wqflask.marker_regression.rqtl_mapping.g") @mock.patch("wqflask.marker_regression.rqtl_mapping.logger") - def test_get_trait_data_type_found(self,mock_logger,mock_db): + def test_get_trait_data(self,mock_logger,mock_db): """test for getting trait data_type return True""" caller_value="""SELECT value FROM TraitMetadata WHERE type='trait_data_type'""" mock_db.db.execute.return_value.fetchone.return_value=["""{"type":"trait_data_type","name":"T1","traid_id":"fer434f"}"""] diff --git a/wqflask/tests/wqflask/marker_regression/test_run_mapping.py b/wqflask/tests/wqflask/marker_regression/test_run_mapping.py index 2af4c3e3..a134f551 100644 --- a/wqflask/tests/wqflask/marker_regression/test_run_mapping.py +++ b/wqflask/tests/wqflask/marker_regression/test_run_mapping.py @@ -62,7 +62,7 @@ class TestRunMapping(unittest.TestCase): self.assertEqual(result_2, []) @mock.patch("wqflask.marker_regression.run_mapping.data_set") - def test_geno_db_exists(self, mock_data_set): + def test_if_geno_db_exists(self, mock_data_set): mock_data_set.create_dataset.side_effect = [ AttributeSetter({}), Exception()] results_no_error = geno_db_exists(self.dataset) -- cgit v1.2.3 From e323c52889cfbab7f152e4969f6e2b528768587a Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Fri, 20 Nov 2020 20:00:29 +0300 Subject: Update tests to use new gn2-docs url --- wqflask/tests/unit/wqflask/test_markdown_routes.py | 24 ++++++++++------------ 1 file changed, 11 insertions(+), 13 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/unit/wqflask/test_markdown_routes.py b/wqflask/tests/unit/wqflask/test_markdown_routes.py index 3adf63e5..2d403d04 100644 --- a/wqflask/tests/unit/wqflask/test_markdown_routes.py +++ b/wqflask/tests/unit/wqflask/test_markdown_routes.py @@ -23,8 +23,7 @@ class MockRequests200: This is some content ## Sub-heading -This is another sub-heading - """ +This is another sub-heading""" class TestMarkdownRoutesFunctions(unittest.TestCase): """Test cases for functions in markdown_routes""" @@ -32,27 +31,26 @@ class TestMarkdownRoutesFunctions(unittest.TestCase): @mock.patch('wqflask.markdown_routes.requests.get') def test_render_markdown_when_fetching_locally(self, requests_mock): requests_mock.return_value = MockRequests404() - markdown_content = render_markdown("glossary.md") + markdown_content = render_markdown("general/glossary/glossary.md") requests_mock.assert_called_with( "https://raw.githubusercontent.com" - "/genenetwork/genenetwork2/" - "wqflask/wqflask/static/" - "glossary.md") + "/genenetwork/gn-docs/" + "master/general/" + "glossary/glossary.md") self.assertRegexpMatches(markdown_content, - "Glossary of Terms and Features") + "Content for general/glossary/glossary.md not available.") @mock.patch('wqflask.markdown_routes.requests.get') def test_render_markdown_when_fetching_remotely(self, requests_mock): requests_mock.return_value = MockRequests200() - markdown_content = render_markdown("glossary.md") + markdown_content = render_markdown("general/glossary/glossary.md") requests_mock.assert_called_with( "https://raw.githubusercontent.com" - "/genenetwork/genenetwork2/" - "wqflask/wqflask/static/" - "glossary.md") + "/genenetwork/gn-docs/" + "master/general/" + "glossary/glossary.md") self.assertEqual("""

Glossary

This is some content

Sub-heading

-

This is another sub-heading

-""", +

This is another sub-heading

""", markdown_content) -- cgit v1.2.3 From 8fc58655c9b98e816f31e4a4f99b6879fe304bca Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Fri, 20 Nov 2020 20:03:23 +0300 Subject: Replace mockobject with dataclasses * wqflask/tests/unit/wqflask/test_markdown_routes.py (MockRequests404): Use dataclasses. (MockRequests200): Ditto. --- wqflask/tests/unit/wqflask/test_markdown_routes.py | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/unit/wqflask/test_markdown_routes.py b/wqflask/tests/unit/wqflask/test_markdown_routes.py index 2d403d04..90e0f17c 100644 --- a/wqflask/tests/unit/wqflask/test_markdown_routes.py +++ b/wqflask/tests/unit/wqflask/test_markdown_routes.py @@ -3,28 +3,26 @@ import unittest from unittest import mock +from dataclasses import dataclass from wqflask.markdown_routes import render_markdown +@dataclass class MockRequests404: - @property - def status_code(self): - return 404 + status_code: int = 404 -class MockRequests200: - @property - def status_code(self): - return 200 - @property - def content(self): - return b""" +@dataclass +class MockRequests200: + status_code: int = 200 + content: str = b""" # Glossary This is some content ## Sub-heading This is another sub-heading""" + class TestMarkdownRoutesFunctions(unittest.TestCase): """Test cases for functions in markdown_routes""" -- cgit v1.2.3 From 7f35213b64707e7c61affb6fa376f561200ac1d6 Mon Sep 17 00:00:00 2001 From: Alexander Kabui Date: Fri, 27 Nov 2020 19:59:17 +0300 Subject: move tests to unit folder --- .../marker_regression/test_gemma_mapping.py | 205 +++++++++++++++ .../marker_regression/test_plink_mapping.py | 84 ++++++ .../marker_regression/test_qtlreaper_mapping.py | 21 ++ .../wqflask/marker_regression/test_rqtl_mapping.py | 48 ++++ .../wqflask/marker_regression/test_run_mapping.py | 284 +++++++++++++++++++++ .../marker_regression/test_gemma_mapping.py | 205 --------------- .../marker_regression/test_plink_mapping.py | 84 ------ .../marker_regression/test_qtlreaper_mapping.py | 21 -- .../wqflask/marker_regression/test_rqtl_mapping.py | 48 ---- .../wqflask/marker_regression/test_run_mapping.py | 284 --------------------- 10 files changed, 642 insertions(+), 642 deletions(-) create mode 100644 wqflask/tests/unit/wqflask/marker_regression/test_gemma_mapping.py create mode 100644 wqflask/tests/unit/wqflask/marker_regression/test_plink_mapping.py create mode 100644 wqflask/tests/unit/wqflask/marker_regression/test_qtlreaper_mapping.py create mode 100644 wqflask/tests/unit/wqflask/marker_regression/test_rqtl_mapping.py create mode 100644 wqflask/tests/unit/wqflask/marker_regression/test_run_mapping.py delete mode 100644 wqflask/tests/wqflask/marker_regression/test_gemma_mapping.py delete mode 100644 wqflask/tests/wqflask/marker_regression/test_plink_mapping.py delete mode 100644 wqflask/tests/wqflask/marker_regression/test_qtlreaper_mapping.py delete mode 100644 wqflask/tests/wqflask/marker_regression/test_rqtl_mapping.py delete mode 100644 wqflask/tests/wqflask/marker_regression/test_run_mapping.py (limited to 'wqflask/tests') diff --git a/wqflask/tests/unit/wqflask/marker_regression/test_gemma_mapping.py b/wqflask/tests/unit/wqflask/marker_regression/test_gemma_mapping.py new file mode 100644 index 00000000..5b621264 --- /dev/null +++ b/wqflask/tests/unit/wqflask/marker_regression/test_gemma_mapping.py @@ -0,0 +1,205 @@ +# test for wqflask/marker_regression/gemma_mapping.py +import unittest +import random +from unittest import mock +from wqflask.marker_regression.gemma_mapping import run_gemma +from wqflask.marker_regression.gemma_mapping import gen_pheno_txt_file +from wqflask.marker_regression.gemma_mapping import gen_covariates_file +from wqflask.marker_regression.gemma_mapping import parse_gemma_output +from wqflask.marker_regression.gemma_mapping import parse_loco_output + + +class AttributeSetter: + def __init__(self, obj): + for key, val in obj.items(): + setattr(self, key, val) + + +class MockGroup(AttributeSetter): + def get_samplelist(self): + return None + + +class TestGemmaMapping(unittest.TestCase): + + @mock.patch("wqflask.marker_regression.gemma_mapping.parse_loco_output") + def test_run_gemma_firstrun_set_false(self, mock_parse_loco): + """add tests for gemma function where first run is set to false""" + dataset = AttributeSetter( + {"group": AttributeSetter({"genofile": "genofile.geno"})}) + + output_file = "file1" + mock_parse_loco.return_value = [] + this_trait = AttributeSetter({"name": "t1"}) + + result = run_gemma(this_trait=this_trait, this_dataset=dataset, samples=[], vals=[ + ], covariates="", use_loco=True, first_run=False, output_files=output_file) + + expected_results = ([], "file1") + self.assertEqual(expected_results, result) + + @mock.patch("wqflask.marker_regression.gemma_mapping.webqtlConfig.GENERATED_IMAGE_DIR", "/home/user/img") + @mock.patch("wqflask.marker_regression.gemma_mapping.GEMMAOPTS", "-debug") + @mock.patch("wqflask.marker_regression.gemma_mapping.GEMMA_WRAPPER_COMMAND", "ghc") + @mock.patch("wqflask.marker_regression.gemma_mapping.TEMPDIR", "/home/user/data/") + @mock.patch("wqflask.marker_regression.gemma_mapping.parse_loco_output") + @mock.patch("wqflask.marker_regression.gemma_mapping.logger") + @mock.patch("wqflask.marker_regression.gemma_mapping.flat_files") + @mock.patch("wqflask.marker_regression.gemma_mapping.gen_covariates_file") + @mock.patch("wqflask.marker_regression.run_mapping.random.choice") + @mock.patch("wqflask.marker_regression.gemma_mapping.os") + @mock.patch("wqflask.marker_regression.gemma_mapping.gen_pheno_txt_file") + def test_run_gemma_firstrun_set_true(self, mock_gen_pheno_txt, mock_os, mock_choice, mock_gen_covar, mock_flat_files, mock_logger, mock_parse_loco): + """add tests for run_gemma where first run is set to true""" + chromosomes = [] + for i in range(1, 5): + chromosomes.append(AttributeSetter({"name": f"CH{i}"})) + chromo = AttributeSetter({"chromosomes": chromosomes}) + dataset_group = MockGroup( + {"name": "GP1", "genofile": "file_geno"}) + dataset = AttributeSetter({"group": dataset_group, "name": "dataset1_name", + "species": AttributeSetter({"chromosomes": chromo})}) + trait = AttributeSetter({"name": "trait1"}) + samples = [] + mock_gen_pheno_txt.return_value = None + mock_os.path.isfile.return_value = True + mock_gen_covar.return_value = None + mock_choice.return_value = "R" + mock_flat_files.return_value = "/home/genotype/bimbam" + mock_parse_loco.return_value = [] + results = run_gemma(this_trait=trait, this_dataset=dataset, samples=[ + ], vals=[], covariates="", use_loco=True) + system_calls = [mock.call('ghc --json -- -debug -g /home/genotype/bimbam/file_geno.txt -p /home/user/data//gn2/trait1_dataset1_name_pheno.txt -a /home/genotype/bimbam/file_snps.txt -gk > /home/user/data//gn2/GP1_K_RRRRRR.json'), + mock.call('ghc --json --input /home/user/data//gn2/GP1_K_RRRRRR.json -- -debug -a /home/genotype/bimbam/file_snps.txt -lmm 2 -g /home/genotype/bimbam/file_geno.txt -p /home/user/data//gn2/trait1_dataset1_name_pheno.txt > /home/user/data//gn2/GP1_GWA_RRRRRR.json')] + mock_os.system.assert_has_calls(system_calls) + mock_gen_pheno_txt.assert_called_once() + mock_parse_loco.assert_called_once_with(dataset, "GP1_GWA_RRRRRR") + mock_os.path.isfile.assert_called_once_with( + ('/home/user/imgfile_output.assoc.txt')) + self.assertEqual(mock_logger.debug.call_count, 2) + self.assertEqual(mock_flat_files.call_count, 4) + self.assertEqual(results, ([], "GP1_GWA_RRRRRR")) + + @mock.patch("wqflask.marker_regression.gemma_mapping.TEMPDIR", "/home/user/data") + def test_gen_pheno_txt_file(self): + """add tests for generating pheno txt file""" + with mock.patch("builtins.open", mock.mock_open())as mock_open: + gen_pheno_txt_file(this_dataset={}, genofile_name="", vals=[ + "x", "w", "q", "we", "R"], trait_filename="fitr.re") + mock_open.assert_called_once_with( + '/home/user/data/gn2/fitr.re.txt', 'w') + filehandler = mock_open() + values = ["x", "w", "q", "we", "R"] + write_calls = [mock.call('NA\n'), mock.call('w\n'), mock.call( + 'q\n'), mock.call('we\n'), mock.call('R\n')] + + filehandler.write.assert_has_calls(write_calls) + + @mock.patch("wqflask.marker_regression.gemma_mapping.flat_files") + @mock.patch("wqflask.marker_regression.gemma_mapping.create_trait") + @mock.patch("wqflask.marker_regression.gemma_mapping.create_dataset") + def test_gen_covariates_file(self, create_dataset, create_trait, flat_files): + """add tests for generating covariates files""" + covariates = "X1:X2,Y1:Y2,M1:M3,V1:V2" + samplelist = ["X1", "X2", "X3", "X4"] + create_dataset_side_effect = [] + create_trait_side_effect = [] + + for i in range(4): + create_dataset_side_effect.append(AttributeSetter({"name": f'name_{i}'})) + create_trait_side_effect.append( + AttributeSetter({"data": [f'data_{i}']})) + + create_dataset.side_effect = create_trait_side_effect + create_trait.side_effect = create_trait_side_effect + + group = MockGroup({"name": "group_X", "samplelist": samplelist}) + this_dataset = AttributeSetter({"group": group}) + flat_files.return_value = "Home/Genenetwork" + + with mock.patch("builtins.open", mock.mock_open())as mock_open: + gen_covariates_file(this_dataset=this_dataset, covariates=covariates, + samples=["x1", "x2", "X3"]) + + create_dataset.assert_has_calls( + [mock.call('X2'), mock.call('Y2'), mock.call('M3'), mock.call('V2')]) + mock_calls = [] + trait_names = ["X1", "Y1", "M1", "V1"] + + for i, trait in enumerate(create_trait_side_effect): + mock_calls.append( + mock.call(dataset=trait, name=trait_names[i], cellid=None)) + + create_trait.assert_has_calls(mock_calls) + + flat_files.assert_called_once_with('mapping') + mock_open.assert_called_once_with( + 'Home/Genenetwork/group_X_covariates.txt', 'w') + filehandler = mock_open() + filehandler.write.assert_has_calls([mock.call( + '-9\t'), mock.call('-9\t'), mock.call('-9\t'), mock.call('-9\t'), mock.call('\n')]) + + @mock.patch("wqflask.marker_regression.gemma_mapping.webqtlConfig.GENERATED_IMAGE_DIR", "/home/user/img/") + def test_parse_gemma_output(self): + """add test for generating gemma output with obj returned""" + file = """X/Y\t gn2\t21\tQ\tE\tA\tP\tMMB\tCDE\t0.5 +X/Y\tgn2\t21322\tQ\tE\tA\tP\tMMB\tCDE\t0.5 +chr\tgn1\t12312\tQ\tE\tA\tP\tMMB\tCDE\t0.7 +X\tgn7\t2324424\tQ\tE\tA\tP\tMMB\tCDE\t0.4 +125\tgn9\t433575\tQ\tE\tA\tP\tMMB\tCDE\t0.67 +""" + with mock.patch("builtins.open", mock.mock_open(read_data=file)) as mock_open: + results = parse_gemma_output(genofile_name="gema_file") + expected = [{'name': ' gn2', 'chr': 'X/Y', 'Mb': 2.1e-05, 'p_value': 0.5, 'lod_score': 0.3010299956639812}, {'name': 'gn2', 'chr': 'X/Y', 'Mb': 0.021322, 'p_value': 0.5, 'lod_score': 0.3010299956639812}, + {'name': 'gn7', 'chr': 'X', 'Mb': 2.324424, 'p_value': 0.4, 'lod_score': 0.3979400086720376}, {'name': 'gn9', 'chr': 125, 'Mb': 0.433575, 'p_value': 0.67, 'lod_score': 0.17392519729917352}] + mock_open.assert_called_once_with( + "/home/user/img/gema_file_output.assoc.txt") + self.assertEqual(results, expected) + + @mock.patch("wqflask.marker_regression.gemma_mapping.webqtlConfig.GENERATED_IMAGE_DIR", "/home/user/img") + def test_parse_gemma_output_with_empty_return(self): + """add tests for parse gemma output where nothing returned""" + output_file_results = """chr\t today""" + with mock.patch("builtins.open", mock.mock_open(read_data=output_file_results)) as mock_open: + results = parse_gemma_output(genofile_name="gema_file") + self.assertEqual(results, []) + + @mock.patch("wqflask.marker_regression.gemma_mapping.TEMPDIR", "/home/tmp") + @mock.patch("wqflask.marker_regression.gemma_mapping.os") + @mock.patch("wqflask.marker_regression.gemma_mapping.json") + def test_parse_loco_outputfile_found(self, mock_json, mock_os): + """add tests for parse loco output file found""" + mock_json.load.return_value = { + "files": [["file_name", "user", "~/file1"], + ["file_name", "user", "~/file2"]] + } + return_file_1 = """X/Y\t L1\t21\tQ\tE\tA\tP\tMMB\tCDE\t0.5 +X/Y\tL2\t21322\tQ\tE\tA\tP\tMMB\tCDE\t0.5 +chr\tL3\t12312\tQ\tE\tA\tP\tMMB\tCDE\t0.7""" + return_file_2 = """chr\tother\t21322\tQ\tE\tA\tP\tMMB\tCDE\t0.5""" + mock_os.path.isfile.return_value = True + file_to_write = """{"files":["file_1","file_2"]}""" + with mock.patch("builtins.open") as mock_open: + + handles = (mock.mock_open(read_data="gwas").return_value, mock.mock_open( + read_data=return_file_1).return_value, mock.mock_open(read_data=return_file_2).return_value) + mock_open.side_effect = handles + results = parse_loco_output( + this_dataset={}, gwa_output_filename=".xw/") + expected_results = [{'name': ' L1', 'chr': 'X/Y', 'Mb': 2.1e-05, 'p_value': 0.5, 'lod_score': 0.3010299956639812}, { + 'name': 'L2', 'chr': 'X/Y', 'Mb': 0.021322, 'p_value': 0.5, 'lod_score': 0.3010299956639812}] + + self.assertEqual(expected_results, results) + + @mock.patch("wqflask.marker_regression.gemma_mapping.TEMPDIR", "/home/tmp") + @mock.patch("wqflask.marker_regression.gemma_mapping.os") + def test_parse_loco_outputfile_not_found(self, mock_os): + """add tests for parse loco output where output file not found""" + + mock_os.path.isfile.return_value = False + file_to_write = """{"files":["file_1","file_2"]}""" + + with mock.patch("builtins.open", mock.mock_open(read_data=file_to_write)) as mock_open: + results = parse_loco_output( + this_dataset={}, gwa_output_filename=".xw/") + self.assertEqual(results, []) diff --git a/wqflask/tests/unit/wqflask/marker_regression/test_plink_mapping.py b/wqflask/tests/unit/wqflask/marker_regression/test_plink_mapping.py new file mode 100644 index 00000000..428f45b9 --- /dev/null +++ b/wqflask/tests/unit/wqflask/marker_regression/test_plink_mapping.py @@ -0,0 +1,84 @@ +# test for wqflask/marker_regression/plink_mapping.py +import unittest +from unittest import mock +from wqflask.marker_regression.plink_mapping import build_line_list +from wqflask.marker_regression.plink_mapping import get_samples_from_ped_file +from wqflask.marker_regression.plink_mapping import flat_files +from wqflask.marker_regression.plink_mapping import gen_pheno_txt_file_plink +from wqflask.marker_regression.plink_mapping import parse_plink_output + + +class AttributeSetter: + def __init__(self, obj): + for key, val in obj.items(): + setattr(self, key, val) +class TestPlinkMapping(unittest.TestCase): + + def test_build_line_list(self): + """testing for building line list""" + line_1 = "this is line one test" + irregular_line = " this is an, irregular line " + exp_line1 = ["this", "is", "line", "one", "test"] + + results = build_line_list(irregular_line) + self.assertEqual(exp_line1, build_line_list(line_1)) + self.assertEqual([], build_line_list()) + self.assertEqual(["this", "is", "an,", "irregular", "line"], results) + + @mock.patch("wqflask.marker_regression.plink_mapping.flat_files") + def test_get_samples_from_ped_file(self, mock_flat_files): + """test for getting samples from ped file""" + dataset = AttributeSetter({"group": AttributeSetter({"name": "n_1"})}) + file_sample = """Expected_1\tline test +Expected_2\there + Expected_3\tthree""" + mock_flat_files.return_value = "/home/user/" + with mock.patch("builtins.open", mock.mock_open(read_data=file_sample)) as mock_open: + results = get_samples_from_ped_file(dataset) + mock_flat_files.assert_called_once_with("mapping") + mock_open.assert_called_once_with("/home/user/n_1.ped", "r") + self.assertEqual( + ["Expected_1", "Expected_2", "Expected_3"], results) + + @mock.patch("wqflask.marker_regression.plink_mapping.TMPDIR", "/home/user/data/") + @mock.patch("wqflask.marker_regression.plink_mapping.get_samples_from_ped_file") + def test_gen_pheno_txt_file_plink(self, mock_samples): + """test for getting gen_pheno txt file""" + mock_samples.return_value = ["Expected_1", "Expected_2", "Expected_3"] + + trait = AttributeSetter({"name": "TX"}) + dataset = AttributeSetter({"group": AttributeSetter({"name": "n_1"})}) + vals = ["value=K1", "value=K2", "value=K3"] + with mock.patch("builtins.open", mock.mock_open()) as mock_open: + results = gen_pheno_txt_file_plink(this_trait=trait, dataset=dataset, + vals=vals, pheno_filename="ph_file") + mock_open.assert_called_once_with( + "/home/user/data/ph_file.txt", "wb") + filehandler = mock_open() + calls_expected = [mock.call('FID\tIID\tTX\n'), + mock.call('Expected_1\tExpected_1\tK1\nExpected_2\tExpected_2\tK2\nExpected_3\tExpected_3\tK3\n')] + + filehandler.write.assert_has_calls(calls_expected) + + filehandler.close.assert_called_once() + + @mock.patch("wqflask.marker_regression.plink_mapping.TMPDIR", "/home/user/data/") + @mock.patch("wqflask.marker_regression.plink_mapping.build_line_list") + def test_parse_plink_output(self, mock_line_list): + """test for parsing plink output""" + chromosomes = [0, 34, 110, 89, 123, 23, 2] + species = AttributeSetter( + {"name": "S1", "chromosomes": AttributeSetter({"chromosomes": chromosomes})}) + + fake_file = """0 AACCAT T98.6 0.89\n2 AATA B45 0.3\n121 ACG B56.4 NA""" + + mock_line_list.side_effect = [["0", "AACCAT", "T98.6", "0.89"], [ + "2", "AATA", "B45", "0.3"], ["121", "ACG", "B56.4", "NA"]] + with mock.patch("builtins.open", mock.mock_open(read_data=fake_file)) as mock_open: + parse_results = parse_plink_output( + output_filename="P1_file", species=species) + mock_open.assert_called_once_with( + "/home/user/data/P1_file.qassoc", "rb") + expected = (2, {'AACCAT': 0.89, 'AATA': 0.3}) + + self.assertEqual(parse_results, expected) diff --git a/wqflask/tests/unit/wqflask/marker_regression/test_qtlreaper_mapping.py b/wqflask/tests/unit/wqflask/marker_regression/test_qtlreaper_mapping.py new file mode 100644 index 00000000..b47f877a --- /dev/null +++ b/wqflask/tests/unit/wqflask/marker_regression/test_qtlreaper_mapping.py @@ -0,0 +1,21 @@ +import unittest +from unittest import mock +from wqflask.marker_regression.qtlreaper_mapping import gen_pheno_txt_file + +#issues some methods in genofile object are not defined +#modify samples should equal to vals +class TestQtlReaperMapping(unittest.TestCase): + @mock.patch("wqflask.marker_regression.qtlreaper_mapping.TEMPDIR", "/home/user/data") + def test_gen_pheno_txt_file(self): + vals=["V1","x","V4","V3","x"] + samples=["S1","S2","S3","S4","S5"] + trait_filename="trait_file" + with mock.patch("builtins.open", mock.mock_open())as mock_open: + gen_pheno_txt_file(samples=samples,vals=vals,trait_filename=trait_filename) + mock_open.assert_called_once_with("/home/user/data/gn2/trait_file.txt","w") + filehandler=mock_open() + write_calls= [mock.call('Trait\t'),mock.call('S1\tS3\tS4\n'),mock.call('T1\t'),mock.call('V1\tV4\tV3')] + + filehandler.write.assert_has_calls(write_calls) + + diff --git a/wqflask/tests/unit/wqflask/marker_regression/test_rqtl_mapping.py b/wqflask/tests/unit/wqflask/marker_regression/test_rqtl_mapping.py new file mode 100644 index 00000000..69f53721 --- /dev/null +++ b/wqflask/tests/unit/wqflask/marker_regression/test_rqtl_mapping.py @@ -0,0 +1,48 @@ +import unittest +from unittest import mock +from wqflask import app +from wqflask.marker_regression.rqtl_mapping import get_trait_data_type +from wqflask.marker_regression.rqtl_mapping import sanitize_rqtl_phenotype +from wqflask.marker_regression.rqtl_mapping import sanitize_rqtl_names + +class TestRqtlMapping(unittest.TestCase): + + def setUp(self): + self.app_context=app.app_context() + self.app_context.push() + + def tearDown(self): + self.app_context.pop() + + + @mock.patch("wqflask.marker_regression.rqtl_mapping.g") + @mock.patch("wqflask.marker_regression.rqtl_mapping.logger") + def test_get_trait_data(self,mock_logger,mock_db): + """test for getting trait data_type return True""" + caller_value="""SELECT value FROM TraitMetadata WHERE type='trait_data_type'""" + mock_db.db.execute.return_value.fetchone.return_value=["""{"type":"trait_data_type","name":"T1","traid_id":"fer434f"}"""] + results=get_trait_data_type("traid_id") + mock_db.db.execute.assert_called_with(caller_value) + self.assertEqual(results,"fer434f") + + def test_sanitize_rqtl_phenotype(self): + """test for sanitizing rqtl phenotype""" + vals=['f',"x","r","x","x"] + results=sanitize_rqtl_phenotype(vals) + expected_phenotype_string='c(f,NA,r,NA,NA)' + + self.assertEqual(results,expected_phenotype_string) + + def test_sanitize_rqtl_names(self): + """test for sanitzing rqtl names""" + vals=['f',"x","r","x","x"] + expected_sanitized_name="c('f',NA,'r',NA,NA)" + results=sanitize_rqtl_names(vals) + self.assertEqual(expected_sanitized_name,results) + + + + + + + diff --git a/wqflask/tests/unit/wqflask/marker_regression/test_run_mapping.py b/wqflask/tests/unit/wqflask/marker_regression/test_run_mapping.py new file mode 100644 index 00000000..4129cc0c --- /dev/null +++ b/wqflask/tests/unit/wqflask/marker_regression/test_run_mapping.py @@ -0,0 +1,284 @@ +import unittest +import datetime +from unittest import mock + +from wqflask.marker_regression.run_mapping import get_genofile_samplelist +from wqflask.marker_regression.run_mapping import geno_db_exists +from wqflask.marker_regression.run_mapping import write_input_for_browser +from wqflask.marker_regression.run_mapping import export_mapping_results +from wqflask.marker_regression.run_mapping import trim_markers_for_figure +from wqflask.marker_regression.run_mapping import get_perm_strata +from wqflask.marker_regression.run_mapping import get_chr_lengths + + +class AttributeSetter: + def __init__(self, obj): + for k, v in obj.items(): + setattr(self, k, v) + + +class MockGroup(AttributeSetter): + + def get_genofiles(self): + return [{"location": "~/genofiles/g1_file", "sample_list": ["S1", "S2", "S3", "S4"]}] + + +class TestRunMapping(unittest.TestCase): + def setUp(self): + + self.group = MockGroup( + {"genofile": "~/genofiles/g1_file", "name": "GP1_", "species": "Human"}) + chromosomes = { + "3": AttributeSetter({ + "name": "C1", + "length": "0.04" + }), + "4": AttributeSetter({ + "name": "C2", + "length": "0.03" + }), + "5": AttributeSetter({ + "name": "C4", + "length": "0.01" + }) + } + self.dataset = AttributeSetter( + {"fullname": "dataser_1", "group": self.group, "type": "ProbeSet"}) + + self.chromosomes = AttributeSetter({"chromosomes": chromosomes}) + self.trait = AttributeSetter( + {"symbol": "IGFI", "chr": "X1", "mb": 123313}) + + def tearDown(self): + self.dataset = AttributeSetter( + {"group": {"location": "~/genofiles/g1_file"}}) + + def test_get_genofile_samplelist(self): + + results_1 = get_genofile_samplelist(self.dataset) + self.assertEqual(results_1, ["S1", "S2", "S3", "S4"]) + self.group.genofile = "~/genofiles/g2_file" + result_2 = get_genofile_samplelist(self.dataset) + self.assertEqual(result_2, []) + + @mock.patch("wqflask.marker_regression.run_mapping.data_set") + def test_if_geno_db_exists(self, mock_data_set): + mock_data_set.create_dataset.side_effect = [ + AttributeSetter({}), Exception()] + results_no_error = geno_db_exists(self.dataset) + results_with_error = geno_db_exists(self.dataset) + + self.assertEqual(mock_data_set.create_dataset.call_count, 2) + self.assertEqual(results_with_error, "False") + self.assertEqual(results_no_error, "True") + + def test_trim_markers_for_figure(self): + + markers = [{ + "name": "MK1", + "chr": "C1", + "cM": "1", + "Mb": "12000", + "genotypes": [], + "dominance":"TT", + "additive":"VA", + "lod_score":0.5 + }, + { + "name": "MK2", + "chr": "C2", + "cM": "15", + "Mb": "10000", + "genotypes": [], + "lod_score":0.7 + }, + { + "name": "MK1", + "chr": "C3", + "cM": "45", + "Mb": "1", + "genotypes": [], + "dominance":"Tt", + "additive":"VE", + "lod_score":1 + }] + + marker_2 = [{ + "name": "MK1", + "chr": "C1", + "cM": "1", + "Mb": "12000", + "genotypes": [], + "dominance":"TT", + "additive":"VA", + "p_wald":4.6 + }] + results = trim_markers_for_figure(markers) + result_2 = trim_markers_for_figure(marker_2) + expected = [ + { + "name": "MK1", + "chr": "C1", + "cM": "1", + "Mb": "12000", + "genotypes": [], + "dominance":"TT", + "additive":"VA", + "lod_score":0.5 + }, + { + "name": "MK1", + "chr": "C3", + "cM": "45", + "Mb": "1", + "genotypes": [], + "dominance":"Tt", + "additive":"VE", + "lod_score":1 + } + + ] + self.assertEqual(results, expected) + self.assertEqual(result_2, marker_2) + + def test_export_mapping_results(self): + """test for exporting mapping results""" + datetime_mock = mock.Mock(wraps=datetime.datetime) + datetime_mock.now.return_value = datetime.datetime( + 2019, 9, 1, 10, 12, 12) + + markers = [{ + "name": "MK1", + "chr": "C1", + "cM": "1", + "Mb": "12000", + "genotypes": [], + "dominance":"TT", + "additive":"VA", + "lod_score":3 + }, + { + "name": "MK2", + "chr": "C2", + "cM": "15", + "Mb": "10000", + "genotypes": [], + "lod_score":7 + }, + { + "name": "MK1", + "chr": "C3", + "cM": "45", + "Mb": "1", + "genotypes": [], + "dominance":"Tt", + "additive":"VE", + "lod_score":7 + }] + + with mock.patch("builtins.open", mock.mock_open()) as mock_open: + + with mock.patch("wqflask.marker_regression.run_mapping.datetime.datetime", new=datetime_mock): + export_mapping_results(dataset=self.dataset, trait=self.trait, markers=markers, + results_path="~/results", mapping_scale="physic", score_type="-log(p)") + + write_calls = [ + mock.call('Time/Date: 09/01/19 / 10:12:12\n'), + mock.call('Population: Human GP1_\n'), mock.call( + 'Data Set: dataser_1\n'), + mock.call('Gene Symbol: IGFI\n'), mock.call( + 'Location: X1 @ 123313 Mb\n'), + mock.call('\n'), mock.call('Name,Chr,'), + mock.call('Mb,-log(p)'), mock.call('Cm,-log(p)'), + mock.call(',Additive'), mock.call(',Dominance'), + mock.call('\n'), mock.call('MK1,C1,'), + mock.call('12000,'), mock.call('1,'), + mock.call('3'), mock.call(',VA'), + mock.call(',TT'), mock.call('\n'), + mock.call('MK2,C2,'), mock.call('10000,'), + mock.call('15,'), mock.call('7'), + mock.call('\n'), mock.call('MK1,C3,'), + mock.call('1,'), mock.call('45,'), + mock.call('7'), mock.call(',VE'), + mock.call(',Tt') + + ] + mock_open.assert_called_once_with("~/results", "w+") + filehandler = mock_open() + filehandler.write.assert_has_calls(write_calls) + + @mock.patch("wqflask.marker_regression.run_mapping.random.choice") + def test_write_input_for_browser(self, mock_choice): + """test for writing input for browser""" + mock_choice.side_effect = ["F", "i", "l", "e", "s", "x"] + with mock.patch("builtins.open", mock.mock_open()) as mock_open: + expected = ['GP1__Filesx_GWAS', 'GP1__Filesx_ANNOT'] + + results = write_input_for_browser( + this_dataset=self.dataset, gwas_results={}, annotations={}) + self.assertEqual(results, expected) + + def test_get_perm_strata(self): + categorical_vars = ["C1", "C2", "W1"] + used_samples = ["S1", "S2"] + sample_list = AttributeSetter({"sample_attribute_values": { + "S1": { + "C1": "c1_value", + "C2": "c2_value", + "W1": "w1_value" + + }, + "S2": { + "W1": "w2_value", + "W2": "w2_value" + + }, + "S3": { + + "C1": "c1_value", + "C2": "c2_value" + + }, + + }}) + + results = get_perm_strata(this_trait={}, sample_list=sample_list, + categorical_vars=categorical_vars, used_samples=used_samples) + self.assertEqual(results, [2, 1]) + + def test_get_chr_length(self): + """test for getting chromosome length""" + chromosomes = AttributeSetter({"chromosomes": self.chromosomes}) + dataset = AttributeSetter({"species": chromosomes}) + results = get_chr_lengths( + mapping_scale="physic", mapping_method="reaper", dataset=dataset, qtl_results=[]) + chr_lengths = [] + for key, chromo in self.chromosomes.chromosomes.items(): + chr_lengths.append({"chr": chromo.name, "size": chromo.length}) + + self.assertEqual(chr_lengths, results) + + qtl_results = [{ + "chr": "16", + "cM": "0.2" + }, + { + "chr": "12", + "cM": "0.5" + }, + { + "chr": "18", + "cM": "0.1" + }, + { + "chr": "22", + "cM": "0.4" + }, + ] + + result_with_other_mapping_scale = get_chr_lengths( + mapping_scale="other", mapping_method="reaper", dataset=dataset, qtl_results=qtl_results) + expected_value = [{'chr': '1', 'size': '0'}, { + 'chr': '16', 'size': '500000.0'}, {'chr': '18', 'size': '400000.0'}] + + self.assertEqual(result_with_other_mapping_scale, expected_value) diff --git a/wqflask/tests/wqflask/marker_regression/test_gemma_mapping.py b/wqflask/tests/wqflask/marker_regression/test_gemma_mapping.py deleted file mode 100644 index 4fafd95a..00000000 --- a/wqflask/tests/wqflask/marker_regression/test_gemma_mapping.py +++ /dev/null @@ -1,205 +0,0 @@ -# test for wqflask/marker_regression/gemma_mapping.py -import unittest -import random -from unittest import mock -from wqflask.marker_regression.gemma_mapping import run_gemma -from wqflask.marker_regression.gemma_mapping import gen_pheno_txt_file -from wqflask.marker_regression.gemma_mapping import gen_covariates_file -from wqflask.marker_regression.gemma_mapping import parse_gemma_output -from wqflask.marker_regression.gemma_mapping import parse_loco_output - - -class AttributeSetter: - def __init__(self, obj): - for key, val in obj.items(): - setattr(self, key, val) - - -class MockDatasetGroup(AttributeSetter): - def get_samplelist(self): - return None - - -class TestGemmaMapping(unittest.TestCase): - - @mock.patch("wqflask.marker_regression.gemma_mapping.parse_loco_output") - def test_run_gemma_firstrun_set_false(self, mock_parse_loco): - """add tests for gemma function where first run is set to false""" - dataset = AttributeSetter( - {"group": AttributeSetter({"genofile": "genofile.geno"})}) - - output_file = "file1" - mock_parse_loco.return_value = [] - this_trait = AttributeSetter({"name": "t1"}) - - result = run_gemma(this_trait=this_trait, this_dataset=dataset, samples=[], vals=[ - ], covariates="", use_loco=True, first_run=False, output_files=output_file) - - expected_results = ([], "file1") - self.assertEqual(expected_results, result) - - @mock.patch("wqflask.marker_regression.gemma_mapping.webqtlConfig.GENERATED_IMAGE_DIR", "/home/user/img") - @mock.patch("wqflask.marker_regression.gemma_mapping.GEMMAOPTS", "-debug") - @mock.patch("wqflask.marker_regression.gemma_mapping.GEMMA_WRAPPER_COMMAND", "ghc") - @mock.patch("wqflask.marker_regression.gemma_mapping.TEMPDIR", "/home/user/data/") - @mock.patch("wqflask.marker_regression.gemma_mapping.parse_loco_output") - @mock.patch("wqflask.marker_regression.gemma_mapping.logger") - @mock.patch("wqflask.marker_regression.gemma_mapping.flat_files") - @mock.patch("wqflask.marker_regression.gemma_mapping.gen_covariates_file") - @mock.patch("wqflask.marker_regression.run_mapping.random.choice") - @mock.patch("wqflask.marker_regression.gemma_mapping.os") - @mock.patch("wqflask.marker_regression.gemma_mapping.gen_pheno_txt_file") - def test_run_gemma_firstrun_set_true(self, mock_gen_pheno_txt, mock_os, mock_choice, mock_gen_covar, mock_flat_files, mock_logger, mock_parse_loco): - """add tests for run_gemma where first run is set to true""" - chromosomes = [] - for i in range(1, 5): - chromosomes.append(AttributeSetter({"name": f"CH{i}"})) - chromo = AttributeSetter({"chromosomes": chromosomes}) - dataset_group = MockDatasetGroup( - {"name": "GP1", "genofile": "file_geno"}) - dataset = AttributeSetter({"group": dataset_group, "name": "dataset1_name", - "species": AttributeSetter({"chromosomes": chromo})}) - trait = AttributeSetter({"name": "trait1"}) - samples = [] - mock_gen_pheno_txt.return_value = None - mock_os.path.isfile.return_value = True - mock_gen_covar.return_value = None - mock_choice.return_value = "R" - mock_flat_files.return_value = "/home/genotype/bimbam" - mock_parse_loco.return_value = [] - results = run_gemma(this_trait=trait, this_dataset=dataset, samples=[ - ], vals=[], covariates="", use_loco=True) - system_calls = [mock.call('ghc --json -- -debug -g /home/genotype/bimbam/file_geno.txt -p /home/user/data//gn2/trait1_dataset1_name_pheno.txt -a /home/genotype/bimbam/file_snps.txt -gk > /home/user/data//gn2/GP1_K_RRRRRR.json'), - mock.call('ghc --json --input /home/user/data//gn2/GP1_K_RRRRRR.json -- -debug -a /home/genotype/bimbam/file_snps.txt -lmm 2 -g /home/genotype/bimbam/file_geno.txt -p /home/user/data//gn2/trait1_dataset1_name_pheno.txt > /home/user/data//gn2/GP1_GWA_RRRRRR.json')] - mock_os.system.assert_has_calls(system_calls) - mock_gen_pheno_txt.assert_called_once() - mock_parse_loco.assert_called_once_with(dataset, "GP1_GWA_RRRRRR") - mock_os.path.isfile.assert_called_once_with( - ('/home/user/imgfile_output.assoc.txt')) - self.assertEqual(mock_logger.debug.call_count, 2) - self.assertEqual(mock_flat_files.call_count, 4) - self.assertEqual(results, ([], "GP1_GWA_RRRRRR")) - - @mock.patch("wqflask.marker_regression.gemma_mapping.TEMPDIR", "/home/user/data") - def test_gen_pheno_txt_file(self): - """add tests for generating pheno txt file""" - with mock.patch("builtins.open", mock.mock_open())as mock_open: - gen_pheno_txt_file(this_dataset={}, genofile_name="", vals=[ - "x", "w", "q", "we", "R"], trait_filename="fitr.re") - mock_open.assert_called_once_with( - '/home/user/data/gn2/fitr.re.txt', 'w') - filehandler = mock_open() - values = ["x", "w", "q", "we", "R"] - write_calls = [mock.call('NA\n'), mock.call('w\n'), mock.call( - 'q\n'), mock.call('we\n'), mock.call('R\n')] - - filehandler.write.assert_has_calls(write_calls) - - @mock.patch("wqflask.marker_regression.gemma_mapping.flat_files") - @mock.patch("wqflask.marker_regression.gemma_mapping.create_trait") - @mock.patch("wqflask.marker_regression.gemma_mapping.create_dataset") - def test_gen_covariates_file(self, create_dataset, create_trait, flat_files): - """add tests for generating covariates files""" - covariates = "X1:X2,Y1:Y2,M1:M3,V1:V2" - samplelist = ["X1", "X2", "X3", "X4"] - create_dataset_side_effect = [] - create_trait_side_effect = [] - - for i in range(4): - create_dataset_side_effect.append(AttributeSetter({"name": f'name_{i}'})) - create_trait_side_effect.append( - AttributeSetter({"data": [f'data_{i}']})) - - create_dataset.side_effect = create_trait_side_effect - create_trait.side_effect = create_trait_side_effect - - group = MockDatasetGroup({"name": "group_X", "samplelist": samplelist}) - this_dataset = AttributeSetter({"group": group}) - flat_files.return_value = "Home/Genenetwork" - - with mock.patch("builtins.open", mock.mock_open())as mock_open: - gen_covariates_file(this_dataset=this_dataset, covariates=covariates, - samples=["x1", "x2", "X3"]) - - create_dataset.assert_has_calls( - [mock.call('X2'), mock.call('Y2'), mock.call('M3'), mock.call('V2')]) - mock_calls = [] - trait_names = ["X1", "Y1", "M1", "V1"] - - for i, trait in enumerate(create_trait_side_effect): - mock_calls.append( - mock.call(dataset=trait, name=trait_names[i], cellid=None)) - - create_trait.assert_has_calls(mock_calls) - - flat_files.assert_called_once_with('mapping') - mock_open.assert_called_once_with( - 'Home/Genenetwork/group_X_covariates.txt', 'w') - filehandler = mock_open() - filehandler.write.assert_has_calls([mock.call( - '-9\t'), mock.call('-9\t'), mock.call('-9\t'), mock.call('-9\t'), mock.call('\n')]) - - @mock.patch("wqflask.marker_regression.gemma_mapping.webqtlConfig.GENERATED_IMAGE_DIR", "/home/user/img/") - def test_parse_gemma_output(self): - """add test for generating gemma output with obj returned""" - file = """X/Y\t gn2\t21\tQ\tE\tA\tP\tMMB\tCDE\t0.5 -X/Y\tgn2\t21322\tQ\tE\tA\tP\tMMB\tCDE\t0.5 -chr\tgn1\t12312\tQ\tE\tA\tP\tMMB\tCDE\t0.7 -X\tgn7\t2324424\tQ\tE\tA\tP\tMMB\tCDE\t0.4 -125\tgn9\t433575\tQ\tE\tA\tP\tMMB\tCDE\t0.67 -""" - with mock.patch("builtins.open", mock.mock_open(read_data=file)) as mock_open: - results = parse_gemma_output(genofile_name="gema_file") - expected = [{'name': ' gn2', 'chr': 'X/Y', 'Mb': 2.1e-05, 'p_value': 0.5, 'lod_score': 0.3010299956639812}, {'name': 'gn2', 'chr': 'X/Y', 'Mb': 0.021322, 'p_value': 0.5, 'lod_score': 0.3010299956639812}, - {'name': 'gn7', 'chr': 'X', 'Mb': 2.324424, 'p_value': 0.4, 'lod_score': 0.3979400086720376}, {'name': 'gn9', 'chr': 125, 'Mb': 0.433575, 'p_value': 0.67, 'lod_score': 0.17392519729917352}] - mock_open.assert_called_once_with( - "/home/user/img/gema_file_output.assoc.txt") - self.assertEqual(results, expected) - - @mock.patch("wqflask.marker_regression.gemma_mapping.webqtlConfig.GENERATED_IMAGE_DIR", "/home/user/img") - def test_parse_gemma_output_with_empty_return(self): - """add tests for parse gemma output where nothing returned""" - output_file_results = """chr\t today""" - with mock.patch("builtins.open", mock.mock_open(read_data=output_file_results)) as mock_open: - results = parse_gemma_output(genofile_name="gema_file") - self.assertEqual(results, []) - - @mock.patch("wqflask.marker_regression.gemma_mapping.TEMPDIR", "/home/tmp") - @mock.patch("wqflask.marker_regression.gemma_mapping.os") - @mock.patch("wqflask.marker_regression.gemma_mapping.json") - def test_parse_loco_outputfile_found(self, mock_json, mock_os): - """add tests for parse loco output file found""" - mock_json.load.return_value = { - "files": [["file_name", "user", "~/file1"], - ["file_name", "user", "~/file2"]] - } - return_file_1 = """X/Y\t L1\t21\tQ\tE\tA\tP\tMMB\tCDE\t0.5 -X/Y\tL2\t21322\tQ\tE\tA\tP\tMMB\tCDE\t0.5 -chr\tL3\t12312\tQ\tE\tA\tP\tMMB\tCDE\t0.7""" - return_file_2 = """chr\tother\t21322\tQ\tE\tA\tP\tMMB\tCDE\t0.5""" - mock_os.path.isfile.return_value = True - file_to_write = """{"files":["file_1","file_2"]}""" - with mock.patch("builtins.open") as mock_open: - - handles = (mock.mock_open(read_data="gwas").return_value, mock.mock_open( - read_data=return_file_1).return_value, mock.mock_open(read_data=return_file_2).return_value) - mock_open.side_effect = handles - results = parse_loco_output( - this_dataset={}, gwa_output_filename=".xw/") - expected_results = [{'name': ' L1', 'chr': 'X/Y', 'Mb': 2.1e-05, 'p_value': 0.5, 'lod_score': 0.3010299956639812}, { - 'name': 'L2', 'chr': 'X/Y', 'Mb': 0.021322, 'p_value': 0.5, 'lod_score': 0.3010299956639812}] - - self.assertEqual(expected_results, results) - - @mock.patch("wqflask.marker_regression.gemma_mapping.TEMPDIR", "/home/tmp") - @mock.patch("wqflask.marker_regression.gemma_mapping.os") - def test_parse_loco_outputfile_not_found(self, mock_os): - """add tests for parse loco output where output file not found""" - - mock_os.path.isfile.return_value = False - file_to_write = """{"files":["file_1","file_2"]}""" - - with mock.patch("builtins.open", mock.mock_open(read_data=file_to_write)) as mock_open: - results = parse_loco_output( - this_dataset={}, gwa_output_filename=".xw/") - self.assertEqual(results, []) diff --git a/wqflask/tests/wqflask/marker_regression/test_plink_mapping.py b/wqflask/tests/wqflask/marker_regression/test_plink_mapping.py deleted file mode 100644 index 428f45b9..00000000 --- a/wqflask/tests/wqflask/marker_regression/test_plink_mapping.py +++ /dev/null @@ -1,84 +0,0 @@ -# test for wqflask/marker_regression/plink_mapping.py -import unittest -from unittest import mock -from wqflask.marker_regression.plink_mapping import build_line_list -from wqflask.marker_regression.plink_mapping import get_samples_from_ped_file -from wqflask.marker_regression.plink_mapping import flat_files -from wqflask.marker_regression.plink_mapping import gen_pheno_txt_file_plink -from wqflask.marker_regression.plink_mapping import parse_plink_output - - -class AttributeSetter: - def __init__(self, obj): - for key, val in obj.items(): - setattr(self, key, val) -class TestPlinkMapping(unittest.TestCase): - - def test_build_line_list(self): - """testing for building line list""" - line_1 = "this is line one test" - irregular_line = " this is an, irregular line " - exp_line1 = ["this", "is", "line", "one", "test"] - - results = build_line_list(irregular_line) - self.assertEqual(exp_line1, build_line_list(line_1)) - self.assertEqual([], build_line_list()) - self.assertEqual(["this", "is", "an,", "irregular", "line"], results) - - @mock.patch("wqflask.marker_regression.plink_mapping.flat_files") - def test_get_samples_from_ped_file(self, mock_flat_files): - """test for getting samples from ped file""" - dataset = AttributeSetter({"group": AttributeSetter({"name": "n_1"})}) - file_sample = """Expected_1\tline test -Expected_2\there - Expected_3\tthree""" - mock_flat_files.return_value = "/home/user/" - with mock.patch("builtins.open", mock.mock_open(read_data=file_sample)) as mock_open: - results = get_samples_from_ped_file(dataset) - mock_flat_files.assert_called_once_with("mapping") - mock_open.assert_called_once_with("/home/user/n_1.ped", "r") - self.assertEqual( - ["Expected_1", "Expected_2", "Expected_3"], results) - - @mock.patch("wqflask.marker_regression.plink_mapping.TMPDIR", "/home/user/data/") - @mock.patch("wqflask.marker_regression.plink_mapping.get_samples_from_ped_file") - def test_gen_pheno_txt_file_plink(self, mock_samples): - """test for getting gen_pheno txt file""" - mock_samples.return_value = ["Expected_1", "Expected_2", "Expected_3"] - - trait = AttributeSetter({"name": "TX"}) - dataset = AttributeSetter({"group": AttributeSetter({"name": "n_1"})}) - vals = ["value=K1", "value=K2", "value=K3"] - with mock.patch("builtins.open", mock.mock_open()) as mock_open: - results = gen_pheno_txt_file_plink(this_trait=trait, dataset=dataset, - vals=vals, pheno_filename="ph_file") - mock_open.assert_called_once_with( - "/home/user/data/ph_file.txt", "wb") - filehandler = mock_open() - calls_expected = [mock.call('FID\tIID\tTX\n'), - mock.call('Expected_1\tExpected_1\tK1\nExpected_2\tExpected_2\tK2\nExpected_3\tExpected_3\tK3\n')] - - filehandler.write.assert_has_calls(calls_expected) - - filehandler.close.assert_called_once() - - @mock.patch("wqflask.marker_regression.plink_mapping.TMPDIR", "/home/user/data/") - @mock.patch("wqflask.marker_regression.plink_mapping.build_line_list") - def test_parse_plink_output(self, mock_line_list): - """test for parsing plink output""" - chromosomes = [0, 34, 110, 89, 123, 23, 2] - species = AttributeSetter( - {"name": "S1", "chromosomes": AttributeSetter({"chromosomes": chromosomes})}) - - fake_file = """0 AACCAT T98.6 0.89\n2 AATA B45 0.3\n121 ACG B56.4 NA""" - - mock_line_list.side_effect = [["0", "AACCAT", "T98.6", "0.89"], [ - "2", "AATA", "B45", "0.3"], ["121", "ACG", "B56.4", "NA"]] - with mock.patch("builtins.open", mock.mock_open(read_data=fake_file)) as mock_open: - parse_results = parse_plink_output( - output_filename="P1_file", species=species) - mock_open.assert_called_once_with( - "/home/user/data/P1_file.qassoc", "rb") - expected = (2, {'AACCAT': 0.89, 'AATA': 0.3}) - - self.assertEqual(parse_results, expected) diff --git a/wqflask/tests/wqflask/marker_regression/test_qtlreaper_mapping.py b/wqflask/tests/wqflask/marker_regression/test_qtlreaper_mapping.py deleted file mode 100644 index b47f877a..00000000 --- a/wqflask/tests/wqflask/marker_regression/test_qtlreaper_mapping.py +++ /dev/null @@ -1,21 +0,0 @@ -import unittest -from unittest import mock -from wqflask.marker_regression.qtlreaper_mapping import gen_pheno_txt_file - -#issues some methods in genofile object are not defined -#modify samples should equal to vals -class TestQtlReaperMapping(unittest.TestCase): - @mock.patch("wqflask.marker_regression.qtlreaper_mapping.TEMPDIR", "/home/user/data") - def test_gen_pheno_txt_file(self): - vals=["V1","x","V4","V3","x"] - samples=["S1","S2","S3","S4","S5"] - trait_filename="trait_file" - with mock.patch("builtins.open", mock.mock_open())as mock_open: - gen_pheno_txt_file(samples=samples,vals=vals,trait_filename=trait_filename) - mock_open.assert_called_once_with("/home/user/data/gn2/trait_file.txt","w") - filehandler=mock_open() - write_calls= [mock.call('Trait\t'),mock.call('S1\tS3\tS4\n'),mock.call('T1\t'),mock.call('V1\tV4\tV3')] - - filehandler.write.assert_has_calls(write_calls) - - diff --git a/wqflask/tests/wqflask/marker_regression/test_rqtl_mapping.py b/wqflask/tests/wqflask/marker_regression/test_rqtl_mapping.py deleted file mode 100644 index 69f53721..00000000 --- a/wqflask/tests/wqflask/marker_regression/test_rqtl_mapping.py +++ /dev/null @@ -1,48 +0,0 @@ -import unittest -from unittest import mock -from wqflask import app -from wqflask.marker_regression.rqtl_mapping import get_trait_data_type -from wqflask.marker_regression.rqtl_mapping import sanitize_rqtl_phenotype -from wqflask.marker_regression.rqtl_mapping import sanitize_rqtl_names - -class TestRqtlMapping(unittest.TestCase): - - def setUp(self): - self.app_context=app.app_context() - self.app_context.push() - - def tearDown(self): - self.app_context.pop() - - - @mock.patch("wqflask.marker_regression.rqtl_mapping.g") - @mock.patch("wqflask.marker_regression.rqtl_mapping.logger") - def test_get_trait_data(self,mock_logger,mock_db): - """test for getting trait data_type return True""" - caller_value="""SELECT value FROM TraitMetadata WHERE type='trait_data_type'""" - mock_db.db.execute.return_value.fetchone.return_value=["""{"type":"trait_data_type","name":"T1","traid_id":"fer434f"}"""] - results=get_trait_data_type("traid_id") - mock_db.db.execute.assert_called_with(caller_value) - self.assertEqual(results,"fer434f") - - def test_sanitize_rqtl_phenotype(self): - """test for sanitizing rqtl phenotype""" - vals=['f',"x","r","x","x"] - results=sanitize_rqtl_phenotype(vals) - expected_phenotype_string='c(f,NA,r,NA,NA)' - - self.assertEqual(results,expected_phenotype_string) - - def test_sanitize_rqtl_names(self): - """test for sanitzing rqtl names""" - vals=['f',"x","r","x","x"] - expected_sanitized_name="c('f',NA,'r',NA,NA)" - results=sanitize_rqtl_names(vals) - self.assertEqual(expected_sanitized_name,results) - - - - - - - diff --git a/wqflask/tests/wqflask/marker_regression/test_run_mapping.py b/wqflask/tests/wqflask/marker_regression/test_run_mapping.py deleted file mode 100644 index a134f551..00000000 --- a/wqflask/tests/wqflask/marker_regression/test_run_mapping.py +++ /dev/null @@ -1,284 +0,0 @@ -import unittest -import datetime -from unittest import mock - -from wqflask.marker_regression.run_mapping import get_genofile_samplelist -from wqflask.marker_regression.run_mapping import geno_db_exists -from wqflask.marker_regression.run_mapping import write_input_for_browser -from wqflask.marker_regression.run_mapping import export_mapping_results -from wqflask.marker_regression.run_mapping import trim_markers_for_figure -from wqflask.marker_regression.run_mapping import get_perm_strata -from wqflask.marker_regression.run_mapping import get_chr_lengths - - -class AttributeSetter: - def __init__(self, obj): - for k, v in obj.items(): - setattr(self, k, v) - - -class MockDataSetGroup(AttributeSetter): - - def get_genofiles(self): - return [{"location": "~/genofiles/g1_file", "sample_list": ["S1", "S2", "S3", "S4"]}] - - -class TestRunMapping(unittest.TestCase): - def setUp(self): - - self.group = MockDataSetGroup( - {"genofile": "~/genofiles/g1_file", "name": "GP1_", "species": "Human"}) - chromosomes = { - "3": AttributeSetter({ - "name": "C1", - "length": "0.04" - }), - "4": AttributeSetter({ - "name": "C2", - "length": "0.03" - }), - "5": AttributeSetter({ - "name": "C4", - "length": "0.01" - }) - } - self.dataset = AttributeSetter( - {"fullname": "dataser_1", "group": self.group, "type": "ProbeSet"}) - - self.chromosomes = AttributeSetter({"chromosomes": chromosomes}) - self.trait = AttributeSetter( - {"symbol": "IGFI", "chr": "X1", "mb": 123313}) - - def tearDown(self): - self.dataset = AttributeSetter( - {"group": {"location": "~/genofiles/g1_file"}}) - - def test_get_genofile_samplelist(self): - - results_1 = get_genofile_samplelist(self.dataset) - self.assertEqual(results_1, ["S1", "S2", "S3", "S4"]) - self.group.genofile = "~/genofiles/g2_file" - result_2 = get_genofile_samplelist(self.dataset) - self.assertEqual(result_2, []) - - @mock.patch("wqflask.marker_regression.run_mapping.data_set") - def test_if_geno_db_exists(self, mock_data_set): - mock_data_set.create_dataset.side_effect = [ - AttributeSetter({}), Exception()] - results_no_error = geno_db_exists(self.dataset) - results_with_error = geno_db_exists(self.dataset) - - self.assertEqual(mock_data_set.create_dataset.call_count, 2) - self.assertEqual(results_with_error, "False") - self.assertEqual(results_no_error, "True") - - def test_trim_markers_for_figure(self): - - markers = [{ - "name": "MK1", - "chr": "C1", - "cM": "1", - "Mb": "12000", - "genotypes": [], - "dominance":"TT", - "additive":"VA", - "lod_score":0.5 - }, - { - "name": "MK2", - "chr": "C2", - "cM": "15", - "Mb": "10000", - "genotypes": [], - "lod_score":0.7 - }, - { - "name": "MK1", - "chr": "C3", - "cM": "45", - "Mb": "1", - "genotypes": [], - "dominance":"Tt", - "additive":"VE", - "lod_score":1 - }] - - marker_2 = [{ - "name": "MK1", - "chr": "C1", - "cM": "1", - "Mb": "12000", - "genotypes": [], - "dominance":"TT", - "additive":"VA", - "p_wald":4.6 - }] - results = trim_markers_for_figure(markers) - result_2 = trim_markers_for_figure(marker_2) - expected = [ - { - "name": "MK1", - "chr": "C1", - "cM": "1", - "Mb": "12000", - "genotypes": [], - "dominance":"TT", - "additive":"VA", - "lod_score":0.5 - }, - { - "name": "MK1", - "chr": "C3", - "cM": "45", - "Mb": "1", - "genotypes": [], - "dominance":"Tt", - "additive":"VE", - "lod_score":1 - } - - ] - self.assertEqual(results, expected) - self.assertEqual(result_2, marker_2) - - def test_export_mapping_results(self): - """test for exporting mapping results""" - datetime_mock = mock.Mock(wraps=datetime.datetime) - datetime_mock.now.return_value = datetime.datetime( - 2019, 9, 1, 10, 12, 12) - - markers = [{ - "name": "MK1", - "chr": "C1", - "cM": "1", - "Mb": "12000", - "genotypes": [], - "dominance":"TT", - "additive":"VA", - "lod_score":3 - }, - { - "name": "MK2", - "chr": "C2", - "cM": "15", - "Mb": "10000", - "genotypes": [], - "lod_score":7 - }, - { - "name": "MK1", - "chr": "C3", - "cM": "45", - "Mb": "1", - "genotypes": [], - "dominance":"Tt", - "additive":"VE", - "lod_score":7 - }] - - with mock.patch("builtins.open", mock.mock_open()) as mock_open: - - with mock.patch("wqflask.marker_regression.run_mapping.datetime.datetime", new=datetime_mock): - export_mapping_results(dataset=self.dataset, trait=self.trait, markers=markers, - results_path="~/results", mapping_scale="physic", score_type="-log(p)") - - write_calls = [ - mock.call('Time/Date: 09/01/19 / 10:12:12\n'), - mock.call('Population: Human GP1_\n'), mock.call( - 'Data Set: dataser_1\n'), - mock.call('Gene Symbol: IGFI\n'), mock.call( - 'Location: X1 @ 123313 Mb\n'), - mock.call('\n'), mock.call('Name,Chr,'), - mock.call('Mb,-log(p)'), mock.call('Cm,-log(p)'), - mock.call(',Additive'), mock.call(',Dominance'), - mock.call('\n'), mock.call('MK1,C1,'), - mock.call('12000,'), mock.call('1,'), - mock.call('3'), mock.call(',VA'), - mock.call(',TT'), mock.call('\n'), - mock.call('MK2,C2,'), mock.call('10000,'), - mock.call('15,'), mock.call('7'), - mock.call('\n'), mock.call('MK1,C3,'), - mock.call('1,'), mock.call('45,'), - mock.call('7'), mock.call(',VE'), - mock.call(',Tt') - - ] - mock_open.assert_called_once_with("~/results", "w+") - filehandler = mock_open() - filehandler.write.assert_has_calls(write_calls) - - @mock.patch("wqflask.marker_regression.run_mapping.random.choice") - def test_write_input_for_browser(self, mock_choice): - """test for writing input for browser""" - mock_choice.side_effect = ["F", "i", "l", "e", "s", "x"] - with mock.patch("builtins.open", mock.mock_open()) as mock_open: - expected = ['GP1__Filesx_GWAS', 'GP1__Filesx_ANNOT'] - - results = write_input_for_browser( - this_dataset=self.dataset, gwas_results={}, annotations={}) - self.assertEqual(results, expected) - - def test_get_perm_strata(self): - categorical_vars = ["C1", "C2", "W1"] - used_samples = ["S1", "S2"] - sample_list = AttributeSetter({"sample_attribute_values": { - "S1": { - "C1": "c1_value", - "C2": "c2_value", - "W1": "w1_value" - - }, - "S2": { - "W1": "w2_value", - "W2": "w2_value" - - }, - "S3": { - - "C1": "c1_value", - "C2": "c2_value" - - }, - - }}) - - results = get_perm_strata(this_trait={}, sample_list=sample_list, - categorical_vars=categorical_vars, used_samples=used_samples) - self.assertEqual(results, [2, 1]) - - def test_get_chr_length(self): - """test for getting chromosome length""" - chromosomes = AttributeSetter({"chromosomes": self.chromosomes}) - dataset = AttributeSetter({"species": chromosomes}) - results = get_chr_lengths( - mapping_scale="physic", mapping_method="reaper", dataset=dataset, qtl_results=[]) - chr_lengths = [] - for key, chromo in self.chromosomes.chromosomes.items(): - chr_lengths.append({"chr": chromo.name, "size": chromo.length}) - - self.assertEqual(chr_lengths, results) - - qtl_results = [{ - "chr": "16", - "cM": "0.2" - }, - { - "chr": "12", - "cM": "0.5" - }, - { - "chr": "18", - "cM": "0.1" - }, - { - "chr": "22", - "cM": "0.4" - }, - ] - - result_with_other_mapping_scale = get_chr_lengths( - mapping_scale="other", mapping_method="reaper", dataset=dataset, qtl_results=qtl_results) - expected_value = [{'chr': '1', 'size': '0'}, { - 'chr': '16', 'size': '500000.0'}, {'chr': '18', 'size': '400000.0'}] - - self.assertEqual(result_with_other_mapping_scale, expected_value) -- cgit v1.2.3 From c96c1db5660367f1f86cfa76309c87866e79bf79 Mon Sep 17 00:00:00 2001 From: Alexander Kabui Date: Sat, 28 Nov 2020 16:23:53 +0300 Subject: modify test for plink mapping and rqtl_mapping --- wqflask/tests/unit/wqflask/marker_regression/test_plink_mapping.py | 3 ++- wqflask/tests/unit/wqflask/marker_regression/test_rqtl_mapping.py | 4 ++-- 2 files changed, 4 insertions(+), 3 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/unit/wqflask/marker_regression/test_plink_mapping.py b/wqflask/tests/unit/wqflask/marker_regression/test_plink_mapping.py index 428f45b9..5eec93f1 100644 --- a/wqflask/tests/unit/wqflask/marker_regression/test_plink_mapping.py +++ b/wqflask/tests/unit/wqflask/marker_regression/test_plink_mapping.py @@ -14,8 +14,9 @@ class AttributeSetter: setattr(self, key, val) class TestPlinkMapping(unittest.TestCase): + def test_build_line_list(self): - """testing for building line list""" + """test for building line list""" line_1 = "this is line one test" irregular_line = " this is an, irregular line " exp_line1 = ["this", "is", "line", "one", "test"] diff --git a/wqflask/tests/unit/wqflask/marker_regression/test_rqtl_mapping.py b/wqflask/tests/unit/wqflask/marker_regression/test_rqtl_mapping.py index 69f53721..c585f1df 100644 --- a/wqflask/tests/unit/wqflask/marker_regression/test_rqtl_mapping.py +++ b/wqflask/tests/unit/wqflask/marker_regression/test_rqtl_mapping.py @@ -19,10 +19,10 @@ class TestRqtlMapping(unittest.TestCase): @mock.patch("wqflask.marker_regression.rqtl_mapping.logger") def test_get_trait_data(self,mock_logger,mock_db): """test for getting trait data_type return True""" - caller_value="""SELECT value FROM TraitMetadata WHERE type='trait_data_type'""" + query_value="""SELECT value FROM TraitMetadata WHERE type='trait_data_type'""" mock_db.db.execute.return_value.fetchone.return_value=["""{"type":"trait_data_type","name":"T1","traid_id":"fer434f"}"""] results=get_trait_data_type("traid_id") - mock_db.db.execute.assert_called_with(caller_value) + mock_db.db.execute.assert_called_with(query_value) self.assertEqual(results,"fer434f") def test_sanitize_rqtl_phenotype(self): -- cgit v1.2.3 From 6b885b0b4dcdfed744b1996bd767bb9f20fdf633 Mon Sep 17 00:00:00 2001 From: Alexander Kabui Date: Sat, 5 Dec 2020 13:35:43 +0300 Subject: modify tests for run_gemma --- .../unit/wqflask/marker_regression/test_gemma_mapping.py | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/unit/wqflask/marker_regression/test_gemma_mapping.py b/wqflask/tests/unit/wqflask/marker_regression/test_gemma_mapping.py index 5b621264..3d00dd7c 100644 --- a/wqflask/tests/unit/wqflask/marker_regression/test_gemma_mapping.py +++ b/wqflask/tests/unit/wqflask/marker_regression/test_gemma_mapping.py @@ -43,18 +43,18 @@ class TestGemmaMapping(unittest.TestCase): @mock.patch("wqflask.marker_regression.gemma_mapping.GEMMA_WRAPPER_COMMAND", "ghc") @mock.patch("wqflask.marker_regression.gemma_mapping.TEMPDIR", "/home/user/data/") @mock.patch("wqflask.marker_regression.gemma_mapping.parse_loco_output") - @mock.patch("wqflask.marker_regression.gemma_mapping.logger") @mock.patch("wqflask.marker_regression.gemma_mapping.flat_files") @mock.patch("wqflask.marker_regression.gemma_mapping.gen_covariates_file") @mock.patch("wqflask.marker_regression.run_mapping.random.choice") @mock.patch("wqflask.marker_regression.gemma_mapping.os") @mock.patch("wqflask.marker_regression.gemma_mapping.gen_pheno_txt_file") - def test_run_gemma_firstrun_set_true(self, mock_gen_pheno_txt, mock_os, mock_choice, mock_gen_covar, mock_flat_files, mock_logger, mock_parse_loco): + def test_run_gemma_firstrun_set_true(self, mock_gen_pheno_txt, mock_os, mock_choice, mock_gen_covar, mock_flat_files,mock_parse_loco): """add tests for run_gemma where first run is set to true""" - chromosomes = [] + this_chromosomes={} for i in range(1, 5): - chromosomes.append(AttributeSetter({"name": f"CH{i}"})) - chromo = AttributeSetter({"chromosomes": chromosomes}) + this_chromosomes[f'CH{i}']=(AttributeSetter({"name": f"CH{i}"})) + chromo = AttributeSetter({"chromosomes": this_chromosomes}) + dataset_group = MockGroup( {"name": "GP1", "genofile": "file_geno"}) dataset = AttributeSetter({"group": dataset_group, "name": "dataset1_name", @@ -76,7 +76,6 @@ class TestGemmaMapping(unittest.TestCase): mock_parse_loco.assert_called_once_with(dataset, "GP1_GWA_RRRRRR") mock_os.path.isfile.assert_called_once_with( ('/home/user/imgfile_output.assoc.txt')) - self.assertEqual(mock_logger.debug.call_count, 2) self.assertEqual(mock_flat_files.call_count, 4) self.assertEqual(results, ([], "GP1_GWA_RRRRRR")) -- cgit v1.2.3 From 54fc88f3f0f4966608fccdba76b49871eef50553 Mon Sep 17 00:00:00 2001 From: Alexander Kabui Date: Sat, 5 Dec 2020 13:43:23 +0300 Subject: add pep8 formatting --- wqflask/tests/unit/wqflask/marker_regression/test_gemma_mapping.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/unit/wqflask/marker_regression/test_gemma_mapping.py b/wqflask/tests/unit/wqflask/marker_regression/test_gemma_mapping.py index 3d00dd7c..b8c13ab4 100644 --- a/wqflask/tests/unit/wqflask/marker_regression/test_gemma_mapping.py +++ b/wqflask/tests/unit/wqflask/marker_regression/test_gemma_mapping.py @@ -53,12 +53,12 @@ class TestGemmaMapping(unittest.TestCase): this_chromosomes={} for i in range(1, 5): this_chromosomes[f'CH{i}']=(AttributeSetter({"name": f"CH{i}"})) - chromo = AttributeSetter({"chromosomes": this_chromosomes}) + chromosomes = AttributeSetter({"chromosomes": this_chromosomes}) dataset_group = MockGroup( {"name": "GP1", "genofile": "file_geno"}) dataset = AttributeSetter({"group": dataset_group, "name": "dataset1_name", - "species": AttributeSetter({"chromosomes": chromo})}) + "species": AttributeSetter({"chromosomes": chromosomes})}) trait = AttributeSetter({"name": "trait1"}) samples = [] mock_gen_pheno_txt.return_value = None -- cgit v1.2.3 From d080436fa5640522c45b1d8bb90e9ca20ba06d5d Mon Sep 17 00:00:00 2001 From: Alexander Kabui Date: Thu, 17 Dec 2020 01:26:47 +0300 Subject: remove test for parse_gemma_output and modify run_gemma tests (#533) --- .../marker_regression/test_gemma_mapping.py | 32 ++-------------------- 1 file changed, 2 insertions(+), 30 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/unit/wqflask/marker_regression/test_gemma_mapping.py b/wqflask/tests/unit/wqflask/marker_regression/test_gemma_mapping.py index b8c13ab4..eab6afe6 100644 --- a/wqflask/tests/unit/wqflask/marker_regression/test_gemma_mapping.py +++ b/wqflask/tests/unit/wqflask/marker_regression/test_gemma_mapping.py @@ -5,7 +5,6 @@ from unittest import mock from wqflask.marker_regression.gemma_mapping import run_gemma from wqflask.marker_regression.gemma_mapping import gen_pheno_txt_file from wqflask.marker_regression.gemma_mapping import gen_covariates_file -from wqflask.marker_regression.gemma_mapping import parse_gemma_output from wqflask.marker_regression.gemma_mapping import parse_loco_output @@ -69,11 +68,9 @@ class TestGemmaMapping(unittest.TestCase): mock_parse_loco.return_value = [] results = run_gemma(this_trait=trait, this_dataset=dataset, samples=[ ], vals=[], covariates="", use_loco=True) - system_calls = [mock.call('ghc --json -- -debug -g /home/genotype/bimbam/file_geno.txt -p /home/user/data//gn2/trait1_dataset1_name_pheno.txt -a /home/genotype/bimbam/file_snps.txt -gk > /home/user/data//gn2/GP1_K_RRRRRR.json'), - mock.call('ghc --json --input /home/user/data//gn2/GP1_K_RRRRRR.json -- -debug -a /home/genotype/bimbam/file_snps.txt -lmm 2 -g /home/genotype/bimbam/file_geno.txt -p /home/user/data//gn2/trait1_dataset1_name_pheno.txt > /home/user/data//gn2/GP1_GWA_RRRRRR.json')] - mock_os.system.assert_has_calls(system_calls) + self.assertEqual(mock_os.system.call_count,2) mock_gen_pheno_txt.assert_called_once() - mock_parse_loco.assert_called_once_with(dataset, "GP1_GWA_RRRRRR") + mock_parse_loco.assert_called_once_with(dataset, "GP1_GWA_RRRRRR",True) mock_os.path.isfile.assert_called_once_with( ('/home/user/imgfile_output.assoc.txt')) self.assertEqual(mock_flat_files.call_count, 4) @@ -138,31 +135,6 @@ class TestGemmaMapping(unittest.TestCase): filehandler.write.assert_has_calls([mock.call( '-9\t'), mock.call('-9\t'), mock.call('-9\t'), mock.call('-9\t'), mock.call('\n')]) - @mock.patch("wqflask.marker_regression.gemma_mapping.webqtlConfig.GENERATED_IMAGE_DIR", "/home/user/img/") - def test_parse_gemma_output(self): - """add test for generating gemma output with obj returned""" - file = """X/Y\t gn2\t21\tQ\tE\tA\tP\tMMB\tCDE\t0.5 -X/Y\tgn2\t21322\tQ\tE\tA\tP\tMMB\tCDE\t0.5 -chr\tgn1\t12312\tQ\tE\tA\tP\tMMB\tCDE\t0.7 -X\tgn7\t2324424\tQ\tE\tA\tP\tMMB\tCDE\t0.4 -125\tgn9\t433575\tQ\tE\tA\tP\tMMB\tCDE\t0.67 -""" - with mock.patch("builtins.open", mock.mock_open(read_data=file)) as mock_open: - results = parse_gemma_output(genofile_name="gema_file") - expected = [{'name': ' gn2', 'chr': 'X/Y', 'Mb': 2.1e-05, 'p_value': 0.5, 'lod_score': 0.3010299956639812}, {'name': 'gn2', 'chr': 'X/Y', 'Mb': 0.021322, 'p_value': 0.5, 'lod_score': 0.3010299956639812}, - {'name': 'gn7', 'chr': 'X', 'Mb': 2.324424, 'p_value': 0.4, 'lod_score': 0.3979400086720376}, {'name': 'gn9', 'chr': 125, 'Mb': 0.433575, 'p_value': 0.67, 'lod_score': 0.17392519729917352}] - mock_open.assert_called_once_with( - "/home/user/img/gema_file_output.assoc.txt") - self.assertEqual(results, expected) - - @mock.patch("wqflask.marker_regression.gemma_mapping.webqtlConfig.GENERATED_IMAGE_DIR", "/home/user/img") - def test_parse_gemma_output_with_empty_return(self): - """add tests for parse gemma output where nothing returned""" - output_file_results = """chr\t today""" - with mock.patch("builtins.open", mock.mock_open(read_data=output_file_results)) as mock_open: - results = parse_gemma_output(genofile_name="gema_file") - self.assertEqual(results, []) - @mock.patch("wqflask.marker_regression.gemma_mapping.TEMPDIR", "/home/tmp") @mock.patch("wqflask.marker_regression.gemma_mapping.os") @mock.patch("wqflask.marker_regression.gemma_mapping.json") -- cgit v1.2.3 From dd2c510ea09ea3169cac3685b299640226d5606a Mon Sep 17 00:00:00 2001 From: Alexanderkabui Date: Sun, 27 Dec 2020 23:17:36 +0300 Subject: update tests for run gemma --- .../wqflask/marker_regression/test_gemma_mapping.py | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/unit/wqflask/marker_regression/test_gemma_mapping.py b/wqflask/tests/unit/wqflask/marker_regression/test_gemma_mapping.py index eab6afe6..fe2569b8 100644 --- a/wqflask/tests/unit/wqflask/marker_regression/test_gemma_mapping.py +++ b/wqflask/tests/unit/wqflask/marker_regression/test_gemma_mapping.py @@ -144,21 +144,26 @@ class TestGemmaMapping(unittest.TestCase): "files": [["file_name", "user", "~/file1"], ["file_name", "user", "~/file2"]] } - return_file_1 = """X/Y\t L1\t21\tQ\tE\tA\tP\tMMB\tCDE\t0.5 -X/Y\tL2\t21322\tQ\tE\tA\tP\tMMB\tCDE\t0.5 -chr\tL3\t12312\tQ\tE\tA\tP\tMMB\tCDE\t0.7""" - return_file_2 = """chr\tother\t21322\tQ\tE\tA\tP\tMMB\tCDE\t0.5""" + return_file="""X/Y\tM1\t28.457155\tQ\tE\tA\tMMB\t23.3\tW\t0.9\t0.85\t +chr4\tM2\t12\tQ\tE\tMMB\tR\t24\tW\t0.87\t0.5 +Y\tM4\t12\tQ\tE\tMMB\tR\t11.6\tW\t0.21\t0.7 +X\tM5\t12\tQ\tE\tMMB\tR\t21.1\tW\t0.65\t0.6""" + + return_file_2 = """chr\tother\t21322\tQ\tE\tA\tP\tMMB\tCDE\t0.5\t0.4""" mock_os.path.isfile.return_value = True file_to_write = """{"files":["file_1","file_2"]}""" with mock.patch("builtins.open") as mock_open: handles = (mock.mock_open(read_data="gwas").return_value, mock.mock_open( - read_data=return_file_1).return_value, mock.mock_open(read_data=return_file_2).return_value) + read_data=return_file).return_value, mock.mock_open(read_data=return_file_2).return_value) mock_open.side_effect = handles results = parse_loco_output( this_dataset={}, gwa_output_filename=".xw/") - expected_results = [{'name': ' L1', 'chr': 'X/Y', 'Mb': 2.1e-05, 'p_value': 0.5, 'lod_score': 0.3010299956639812}, { - 'name': 'L2', 'chr': 'X/Y', 'Mb': 0.021322, 'p_value': 0.5, 'lod_score': 0.3010299956639812}] + expected_results= [ + {'name': 'M1', 'chr': 'X/Y', 'Mb': 2.8457155e-05, 'p_value': 0.85, 'additive': 23.3, 'lod_score': 0.07058107428570727}, + {'name': 'M2', 'chr': 4, 'Mb': 1.2e-05, 'p_value': 0.5, 'additive': 24.0, 'lod_score': 0.3010299956639812}, + {'name': 'M4', 'chr': 'Y', 'Mb': 1.2e-05, 'p_value': 0.7, 'additive': 11.6, 'lod_score': 0.1549019599857432}, + {'name': 'M5', 'chr': 'X', 'Mb': 1.2e-05, 'p_value': 0.6, 'additive': 21.1, 'lod_score': 0.22184874961635637}] self.assertEqual(expected_results, results) -- cgit v1.2.3 From 7032f7b05deac0bbd2e868ffd3fe42dd1c97fb7d Mon Sep 17 00:00:00 2001 From: uditgulati Date: Tue, 5 Jan 2021 13:14:08 -0600 Subject: add server side class unit tests --- wqflask/tests/unit/wqflask/test_server_side.py | 31 ++++++++++++++++++++++++++ wqflask/wqflask/server_side.py | 16 ++++++------- 2 files changed, 39 insertions(+), 8 deletions(-) create mode 100644 wqflask/tests/unit/wqflask/test_server_side.py (limited to 'wqflask/tests') diff --git a/wqflask/tests/unit/wqflask/test_server_side.py b/wqflask/tests/unit/wqflask/test_server_side.py new file mode 100644 index 00000000..4f91d8ca --- /dev/null +++ b/wqflask/tests/unit/wqflask/test_server_side.py @@ -0,0 +1,31 @@ +import unittest + +from wqflask.server_side import ServerSideTable + + +class TestServerSideTableTests(unittest.TestCase): + """ + Test the ServerSideTable class + + test table: + first, second, third + 'd', 4, 'zz' + 'b', 2, 'aa' + 'c', 1, 'ss' + """ + + def test_get_page(self): + rows_count = 3 + table_rows = [ + {'first': 'd', 'second': 4, 'third': 'zz'}, + {'first': 'b', 'second': 2, 'third': 'aa'}, + {'first': 'c', 'second': 1, 'third': 'ss'}, + ] + headers = ['first', 'second', 'third'] + request_args = {'sEcho': '1', 'iSortCol_0': '1', 'iSortingCols': '1', 'sSortDir_0': 'asc', 'iDisplayStart': '0', 'iDisplayLength': '3'} + + test_page = ServerSideTable(rows_count, table_rows, headers, request_args).get_page() + self.assertEqual(test_page['sEcho'], '1') + self.assertEqual(test_page['iTotalRecords'], 'nan') + self.assertEqual(test_page['iTotalDisplayRecords'], '3') + self.assertEqual(test_page['data'], [{'first': 'b', 'second': 2, 'third': 'aa'}, {'first': 'c', 'second': 1, 'third': 'ss'}, {'first': 'd', 'second': 4, 'third': 'zz'}]) diff --git a/wqflask/wqflask/server_side.py b/wqflask/wqflask/server_side.py index 824b00aa..5f764767 100644 --- a/wqflask/wqflask/server_side.py +++ b/wqflask/wqflask/server_side.py @@ -3,7 +3,7 @@ class ServerSideTable(object): - ''' + """ This class is used to do server-side processing on the DataTables table such as paginating, sorting, filtering(not implemented) etc. This takes the load off @@ -22,7 +22,7 @@ class ServerSideTable(object): Have a look at snp_browser_table() function in wqflask/wqflask/views.py for reference use. - ''' + """ def __init__(self, rows_count, table_rows, header_data_names, request_values): self.request_values = request_values @@ -36,12 +36,12 @@ class ServerSideTable(object): self.paginate_rows() def sort_rows(self): - ''' + """ Sorts the rows taking in to account the column (or columns) that the user has selected. - ''' + """ def is_reverse(str_direction): - ''' Maps the 'desc' and 'asc' words to True or False. ''' + """ Maps the 'desc' and 'asc' words to True or False. """ return True if str_direction == 'desc' else False if (self.request_values['iSortCol_0'] != "") and (int(self.request_values['iSortingCols']) > 0): @@ -54,12 +54,12 @@ class ServerSideTable(object): reverse=is_reverse(sort_direction)) def paginate_rows(self): - ''' + """ Selects a subset of the filtered and sorted data based on if the table has pagination, the current page and the size of each page. - ''' + """ def requires_pagination(): - ''' Check if the table is going to be paginated ''' + """ Check if the table is going to be paginated """ if self.request_values['iDisplayStart'] != "": if int(self.request_values['iDisplayLength']) != -1: return True -- cgit v1.2.3 From 2bd74f8f4e4e72a11c77d4f3e8532c303503ca11 Mon Sep 17 00:00:00 2001 From: Alexanderlacuna Date: Mon, 16 Nov 2020 13:46:57 +0300 Subject: add unit tests for api/mapping.py --- wqflask/tests/unit/wqflask/api/test_mapping.py | 114 +++++++++++++++++++++++++ 1 file changed, 114 insertions(+) create mode 100644 wqflask/tests/unit/wqflask/api/test_mapping.py (limited to 'wqflask/tests') diff --git a/wqflask/tests/unit/wqflask/api/test_mapping.py b/wqflask/tests/unit/wqflask/api/test_mapping.py new file mode 100644 index 00000000..87b18e84 --- /dev/null +++ b/wqflask/tests/unit/wqflask/api/test_mapping.py @@ -0,0 +1,114 @@ +import unittest +from unittest import mock +from wqflask.api.mapping import initialize_parameters + + +class AttributeSetter: + def __init__(self,obj): + for key,value in obj.items(): + setattr(self,key,value) + +class MockGroup(AttributeSetter): + def get_marker(self): + return None +class TestMock(unittest.TestCase): + + # @mock.patch("wqflask.api.mapping.gemma_mapping") + # @mock.patch("wqflask.api.mapping.nitialize_parameters") + # @mock.patch("wqflask.api.mapping.retrieve_sample_data") + # @mock.patch("wqflask.api.mapping.create_trait") + # @mock.patch("wqflask.api.mapping.data_set") + # def test_do_mapping_for_api(self,mock_dataset,mock_create_trait,mock_retrieve_data,mock_gemma): + + # start_vars={ + # "db":"sql_uri/db_web1", + # "trait_id":"idsui332rh3ui2t", + # "limit_to":32.1, + # } + # group_samplelist=["S1","S2","S3","S4"] + # dataset_group=MockGroup({"samplelist":group_samplelist}) + # dataset=AttributeSetter({"type":"Temp","group":dataset_group}) + + # this_trait_data={ + # "Item1":AttributeSetter({ + # "name":"S1", + # "value":"V1" + # }), + + # "Item2":AttributeSetter({ + # "name":"S2", + # "value":"V2" + # }), + + # "Item3":AttributeSetter({ + # "name":"SX", + # "value":"VX" + # }) + # } + + # this_trait=AttributeSetter({"data":this_trait_data}) + + + # mock_dataset.create_dataset.return_value=dataset + + # mock_create_trait.return_value=this_trait + # mock_retrieve_data.return_value=this_trait + + # mock_initialize_params={ + # "format":"json", + # "limit_to":32.1, + # "mapping_method":"gemma", + # "maf":0.01, + # "use_loco":True, + # "num_perm":0, + # "perm_check":False + + # } + + # mock_gemma.return_value=[ ,"filename"] + # pass + + def test_initialize_parameters(self): + expected_results={ + "format":"json", + "limit_to":False, + "mapping_method":"gemma", + "maf":0.01, + "use_loco":True, + "num_perm":0, + "perm_check":False + } + + results=initialize_parameters(start_vars={},dataset={},this_trait={}) + self.assertEqual(results,expected_results) + + start_vars={ + "format":"F1", + "limit_to":"1", + "mapping_method":"rqtl", + "control_marker":True, + "pair_scan":"true", + "interval_mapping":"true", + "use_loco":"true", + "num_perm":"14" + + } + + results_2=initialize_parameters(start_vars=start_vars,dataset={},this_trait={}) + expected_results={ + "format":"F1", + "limit_to":1, + "mapping_method":"gemma", + "maf":0.01, + "use_loco":True, + "num_perm":14, + "perm_check":"ON" + } + + self.assertEqual(results_2,expected_results) + + + + + + -- cgit v1.2.3 From df2c3f9ee43dd055f7766eedee32d76090ad80b2 Mon Sep 17 00:00:00 2001 From: Alexanderlacuna Date: Mon, 16 Nov 2020 13:47:40 +0300 Subject: add unit testsfor api/correlation.py --- wqflask/tests/unit/wqflask/api/test_correlation.py | 83 ++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 wqflask/tests/unit/wqflask/api/test_correlation.py (limited to 'wqflask/tests') diff --git a/wqflask/tests/unit/wqflask/api/test_correlation.py b/wqflask/tests/unit/wqflask/api/test_correlation.py new file mode 100644 index 00000000..482dec67 --- /dev/null +++ b/wqflask/tests/unit/wqflask/api/test_correlation.py @@ -0,0 +1,83 @@ +import unittest +from unittest import mock +from wqflask import app +from wqflask.api.correlation import init_corr_params +from wqflask.api.correlation import convert_to_mouse_gene_id +from wqflask.api.correlation import do_literature_correlation_for_all_traits + + +class AttributeSetter: + def __init__(self, obj): + for k, v in obj.items(): + setattr(self, k, v) + + +class TestCorrelations(unittest.TestCase): + def setUp(self): + self.app_context = app.app_context() + self.app_context.push() + + def tearDown(self): + self.app_context.pop() + + def test_init_corr_params(self): + start_vars = { + "return_count": "3", + "type": "T1", + "method": "spearman" + } + + corr_params_results = init_corr_params(start_vars=start_vars) + expected_results = { + "return_count": 3, + "type": "T1", + "method": "spearman" + } + + self.assertEqual(corr_params_results, expected_results) + + @mock.patch("wqflask.api.correlation.g") + def test_convert_to_mouse_gene_id(self, mock_db): + + results = convert_to_mouse_gene_id(species="Other", gene_id="") + self.assertEqual(results, None) + + rat_species_results = convert_to_mouse_gene_id( + species="rat", gene_id="GH1") + + mock_db.db.execute.return_value.fetchone.side_effect = [AttributeSetter({"mouse": "MG-1"}),AttributeSetter({"mouse":"MG-2"})] + + self.assertEqual(convert_to_mouse_gene_id( + species="mouse", gene_id="MG-4"), "MG-4") + self.assertEqual(convert_to_mouse_gene_id( + species="rat", gene_id="R1"), "MG-1") + self.assertEqual(convert_to_mouse_gene_id( + species="human", gene_id="H1"), "MG-2") + + + + @mock.patch("wqflask.api.correlation.g") + @mock.patch("wqflask.api.correlation.convert_to_mouse_gene_id") + def test_do_literature_correlation_for_all_traits(self,mock_convert_to_mouse_geneid,mock_db): + mock_convert_to_mouse_geneid.side_effect=["MG-1","MG-2;","MG-3","MG-4"] + + + trait_geneid_dict={ + "TT-1":"GH-1", + "TT-2":"GH-2", + "TT-3":"GH-3" + + } + mock_db.db.execute.return_value.fetchone.side_effect=[AttributeSetter({"value":"V1"}),AttributeSetter({"value":"V2"}),AttributeSetter({"value":"V3"})] + + + this_trait=AttributeSetter({"geneid":"GH-1"}) + + target_dataset=AttributeSetter({"group":AttributeSetter({"species":"rat"})}) + results=do_literature_correlation_for_all_traits(this_trait=this_trait,target_dataset=target_dataset,trait_geneid_dict=trait_geneid_dict,corr_params={}) + + expected_results={'TT-1': ['GH-1', 0], 'TT-2': ['GH-2', 'V1'], 'TT-3': ['GH-3', 'V2']} + self.assertEqual(results,expected_results) + + + -- cgit v1.2.3 From 3eda2b13e10937cbd661d6d411286c5b84bcd7cf Mon Sep 17 00:00:00 2001 From: Alexanderlacuna Date: Sat, 28 Nov 2020 15:00:00 +0300 Subject: add correlation test --- .../correlation/test_correlation_functions.py | 21 +++++ .../wqflask/correlation/test_show_corr_results.py | 95 ++++++++++++++++++++++ 2 files changed, 116 insertions(+) create mode 100644 wqflask/tests/unit/wqflask/correlation/test_correlation_functions.py create mode 100644 wqflask/tests/unit/wqflask/correlation/test_show_corr_results.py (limited to 'wqflask/tests') diff --git a/wqflask/tests/unit/wqflask/correlation/test_correlation_functions.py b/wqflask/tests/unit/wqflask/correlation/test_correlation_functions.py new file mode 100644 index 00000000..db449eb1 --- /dev/null +++ b/wqflask/tests/unit/wqflask/correlation/test_correlation_functions.py @@ -0,0 +1,21 @@ +import unittest +from unittest import mock +from wqflask.correlation.correlation_functions import get_trait_symbol_and_tissue_values +from wqflask.correlation.correlation_functions import cal_zero_order_corr_for_tiss + + +class TestCorrelationFunctions(unittest.TestCase): + + + @mock.patch("wqflask.correlation.correlation_functions.MrnaAssayTissueData") + def test_get_trait_symbol_and_tissue_values(self, mock_class): + """test for getting trait symbol and tissue_values""" + mock_class_instance = mock_class.return_value + mock_class_instance.gene_symbols = ["k1", "k2", "k3"] + mock_class_instance.get_symbol_values_pairs.return_value = { + "k1": ["v1", "v2", "v3"], "k2": ["v2", "v3"], "k3": ["k3"]} + results = get_trait_symbol_and_tissue_values( + symbol_list=["k1", "k2", "k3"]) + mock_class.assert_called_with(gene_symbols=['k1', 'k2', 'k3']) + self.assertEqual({"k1": ["v1", "v2", "v3"], "k2": [ + "v2", "v3"], "k3": ["k3"]}, results) diff --git a/wqflask/tests/unit/wqflask/correlation/test_show_corr_results.py b/wqflask/tests/unit/wqflask/correlation/test_show_corr_results.py new file mode 100644 index 00000000..4e63207e --- /dev/null +++ b/wqflask/tests/unit/wqflask/correlation/test_show_corr_results.py @@ -0,0 +1,95 @@ +import unittest +from unittest import mock +from wqflask.correlation.show_corr_results import get_header_fields +from wqflask.correlation.show_corr_results import generate_corr_json +from wqflask.correlation.show_corr_results import do_bicor + + +class Trait: + def __init__(self,trait_obj): + for key,value in trait_obj.items(): + setattr(self,key,value) + +class TestShowCorrResults(unittest.TestCase): + + def test_process_samples(self): + pass + def test_get_header_fields(self): + expected=[ + ['Index', + 'Record', + 'Symbol', + 'Description', + 'Location', + 'Mean', + 'Sample rho', + 'N', + 'Sample p(rho)', + 'Lit rho', + 'Tissue rho', + 'Tissue p(rho)', + 'Max LRS', + 'Max LRS Location', + 'Additive Effect'], + + ['Index', + 'ID', + 'Location', + 'Sample r', + 'N', + 'Sample p(r)'] + + ] + result1=get_header_fields("ProbeSet","spearman") + result2=get_header_fields("Other","Other") + self.assertEqual(result1,expected[0]) + self.assertEqual(result2,expected[1]) + + + + + def test_generate_corr_json(self): + this_trait=Trait({"name":"trait_test"}) + dataset=Trait({"name":"the_name"}) + target_dataset=Trait({"type":"Publish"}) + + trait_with_publish={ + "description_display":"Trait 2 description", + "authors":"trait_2 ", + "pubmed_id":"34n4nn31hn43", + "lrs_location":"N/A", + "additive":"", + "sample_r":100, + "num_overlap":3.2, + "view":True, + "name":"trait_1", + "pubmed_text":"2016", + "additive":"", + "sample_r":10.5, + "LRS_score_repr":"N/A", + "LRS_location_repr":"N/A", + "sample_p":5, + "num_overlap":"num_1" + + + + } + expected_results="""[{"trait_id": "trait_1", "description": "Trait 2 description", "authors": "trait_2 ", "pubmed_id": "34n4nn31hn43", "year": "2016", "lrs_score": "N/A", "lrs_location": "N/A", "additive": "N/A", "sample_r": "10.500", "num_overlap": "num_1", "sample_p": "5.000e+00"}]""" + + corr_results=[Trait(trait_with_publish)] + results=generate_corr_json(corr_results=corr_results,this_trait=this_trait,dataset=dataset,target_dataset=target_dataset,for_api=True) + self.assertEqual(results,expected_results) + + + + def test_generate_corr_json_view_false(self): + trait=Trait({"view":False}) + corr_results=[trait] + this_trait=Trait({"name":"trait_test"}) + dataset=Trait({"name":"the_name"}) + + + results_where_view_is_false=generate_corr_json(corr_results=corr_results,this_trait=this_trait,dataset={},target_dataset={},for_api=False) + + # self.assertEqual(results,[]) + self.assertEqual(results_where_view_is_false,"[]") \ No newline at end of file -- cgit v1.2.3 From 1666f8d50df090e9a14dbf0f4f195bac079de058 Mon Sep 17 00:00:00 2001 From: Alexanderlacuna Date: Sat, 28 Nov 2020 15:11:06 +0300 Subject: add test in api/mapping --- wqflask/tests/unit/wqflask/api/test_mapping.py | 55 -------------------------- 1 file changed, 55 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/unit/wqflask/api/test_mapping.py b/wqflask/tests/unit/wqflask/api/test_mapping.py index 87b18e84..4da1725f 100644 --- a/wqflask/tests/unit/wqflask/api/test_mapping.py +++ b/wqflask/tests/unit/wqflask/api/test_mapping.py @@ -13,61 +13,6 @@ class MockGroup(AttributeSetter): return None class TestMock(unittest.TestCase): - # @mock.patch("wqflask.api.mapping.gemma_mapping") - # @mock.patch("wqflask.api.mapping.nitialize_parameters") - # @mock.patch("wqflask.api.mapping.retrieve_sample_data") - # @mock.patch("wqflask.api.mapping.create_trait") - # @mock.patch("wqflask.api.mapping.data_set") - # def test_do_mapping_for_api(self,mock_dataset,mock_create_trait,mock_retrieve_data,mock_gemma): - - # start_vars={ - # "db":"sql_uri/db_web1", - # "trait_id":"idsui332rh3ui2t", - # "limit_to":32.1, - # } - # group_samplelist=["S1","S2","S3","S4"] - # dataset_group=MockGroup({"samplelist":group_samplelist}) - # dataset=AttributeSetter({"type":"Temp","group":dataset_group}) - - # this_trait_data={ - # "Item1":AttributeSetter({ - # "name":"S1", - # "value":"V1" - # }), - - # "Item2":AttributeSetter({ - # "name":"S2", - # "value":"V2" - # }), - - # "Item3":AttributeSetter({ - # "name":"SX", - # "value":"VX" - # }) - # } - - # this_trait=AttributeSetter({"data":this_trait_data}) - - - # mock_dataset.create_dataset.return_value=dataset - - # mock_create_trait.return_value=this_trait - # mock_retrieve_data.return_value=this_trait - - # mock_initialize_params={ - # "format":"json", - # "limit_to":32.1, - # "mapping_method":"gemma", - # "maf":0.01, - # "use_loco":True, - # "num_perm":0, - # "perm_check":False - - # } - - # mock_gemma.return_value=[ ,"filename"] - # pass - def test_initialize_parameters(self): expected_results={ "format":"json", -- cgit v1.2.3 From e535eeeff92bcfa6d6524e44591164de72d38482 Mon Sep 17 00:00:00 2001 From: Alexander Kabui Date: Fri, 4 Dec 2020 18:43:35 +0300 Subject: add test for map_api in api/test_mapping.py --- wqflask/tests/unit/wqflask/api/test_mapping.py | 145 +++++++++++++++++-------- 1 file changed, 99 insertions(+), 46 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/unit/wqflask/api/test_mapping.py b/wqflask/tests/unit/wqflask/api/test_mapping.py index 4da1725f..5455b215 100644 --- a/wqflask/tests/unit/wqflask/api/test_mapping.py +++ b/wqflask/tests/unit/wqflask/api/test_mapping.py @@ -1,57 +1,110 @@ import unittest from unittest import mock from wqflask.api.mapping import initialize_parameters +from wqflask.api.mapping import do_mapping_for_api class AttributeSetter: - def __init__(self,obj): - for key,value in obj.items(): - setattr(self,key,value) + def __init__(self,obj): + for key,value in obj.items(): + setattr(self,key,value) class MockGroup(AttributeSetter): - def get_marker(self): - return None -class TestMock(unittest.TestCase): - - def test_initialize_parameters(self): - expected_results={ - "format":"json", - "limit_to":False, - "mapping_method":"gemma", - "maf":0.01, - "use_loco":True, - "num_perm":0, - "perm_check":False - } - - results=initialize_parameters(start_vars={},dataset={},this_trait={}) - self.assertEqual(results,expected_results) - - start_vars={ - "format":"F1", - "limit_to":"1", - "mapping_method":"rqtl", - "control_marker":True, - "pair_scan":"true", - "interval_mapping":"true", - "use_loco":"true", - "num_perm":"14" - - } - - results_2=initialize_parameters(start_vars=start_vars,dataset={},this_trait={}) - expected_results={ - "format":"F1", - "limit_to":1, - "mapping_method":"gemma", - "maf":0.01, - "use_loco":True, - "num_perm":14, - "perm_check":"ON" - } - - self.assertEqual(results_2,expected_results) - + def get_marker(self): + self.markers=[] +class TestMapping(unittest.TestCase): + + def test_initialize_parameters(self): + expected_results={ + "format":"json", + "limit_to":False, + "mapping_method":"gemma", + "maf":0.01, + "use_loco":True, + "num_perm":0, + "perm_check":False + } + + results=initialize_parameters(start_vars={},dataset={},this_trait={}) + self.assertEqual(results,expected_results) + + start_vars={ + "format":"F1", + "limit_to":"1", + "mapping_method":"rqtl", + "control_marker":True, + "pair_scan":"true", + "interval_mapping":"true", + "use_loco":"true", + "num_perm":"14" + + } + + results_2=initialize_parameters(start_vars=start_vars,dataset={},this_trait={}) + expected_results={ + "format":"F1", + "limit_to":1, + "mapping_method":"gemma", + "maf":0.01, + "use_loco":True, + "num_perm":14, + "perm_check":"ON" + } + + self.assertEqual(results_2,expected_results) + + + @mock.patch("wqflask.api.mapping.rqtl_mapping.run_rqtl_geno") + @mock.patch("wqflask.api.mapping.gemma_mapping.run_gemma") + @mock.patch("wqflask.api.mapping.initialize_parameters") + @mock.patch("wqflask.api.mapping.retrieve_sample_data") + @mock.patch("wqflask.api.mapping.create_trait") + @mock.patch("wqflask.api.mapping.data_set.create_dataset") + def test_do_mapping_for_api(self,mock_create_dataset,mock_trait,mock_retrieve_sample,mock_param,run_gemma + ,run_rqtl_geno): + start_vars={ + "db":"Temp", + "trait_id":"dewf3232rff2", + "format":"F1", + "mapping_method":"gemma", + "use_loco":True + + } + sampleList=["S1","S2","S3","S4"] + samplelist=["S1","S2","S4"] + dataset=AttributeSetter({"group":samplelist}) + this_trait=AttributeSetter({}) + trait_data=AttributeSetter({ + "data":{ + "item1":AttributeSetter({"name":"S1","value":"S1_value"}), + "item2":AttributeSetter({"name":"S2","value":"S2_value"}), + "item3":AttributeSetter({"name":"S3","value":"S3_value"}), + + } + }) + trait=AttributeSetter({ + "data":trait_data + }) + + dataset.return_value=dataset + mock_trait.return_value=this_trait + + mock_retrieve_sample.return_value=trait + mock_param.return_value={ + "format":"F1", + "limit_to":False, + "mapping_method":"gemma", + "maf":0.01, + "use_loco":"True", + "num_perm":14, + "perm_check":"ON" + } + + run_gemma.return_value=["results"] + results=do_mapping_for_api(start_vars=start_vars) + self.assertEqual(results,("results",None)) + + -- cgit v1.2.3 From e80e793455d2fc6b51dbe95414a3ba8e72652a83 Mon Sep 17 00:00:00 2001 From: Alexanderkabui Date: Sat, 12 Dec 2020 21:21:53 +0300 Subject: add tests for getting sample_r and p values --- wqflask/tests/unit/wqflask/api/test_correlation.py | 38 ++++++++++++++++++++++ .../wqflask/correlation/test_show_corr_results.py | 2 -- 2 files changed, 38 insertions(+), 2 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/unit/wqflask/api/test_correlation.py b/wqflask/tests/unit/wqflask/api/test_correlation.py index 482dec67..077f7fa9 100644 --- a/wqflask/tests/unit/wqflask/api/test_correlation.py +++ b/wqflask/tests/unit/wqflask/api/test_correlation.py @@ -4,6 +4,7 @@ from wqflask import app from wqflask.api.correlation import init_corr_params from wqflask.api.correlation import convert_to_mouse_gene_id from wqflask.api.correlation import do_literature_correlation_for_all_traits +from wqflask.api.correlation import get_sample_r_and_p_values class AttributeSetter: @@ -79,5 +80,42 @@ class TestCorrelations(unittest.TestCase): expected_results={'TT-1': ['GH-1', 0], 'TT-2': ['GH-2', 'V1'], 'TT-3': ['GH-3', 'V2']} self.assertEqual(results,expected_results) + @mock.patch("wqflask.api.correlation.corr_result_helpers.normalize_values") + def test_get_sample_r_and_p_values(self,mock_normalize): + + group=AttributeSetter({"samplelist":["S1","S2","S3","S4","S5","S6","S7"]}) + target_dataset=AttributeSetter({"group":group}) + + target_vals=[3.4, 6.2, 4.1,3.4,1.2,5.6] + trait_data={"S1":AttributeSetter({"value":2.3}),"S2":AttributeSetter({"value":1.1}),"S3":AttributeSetter({"value":6.3}),"S4":AttributeSetter({"value":3.6}),"S5":AttributeSetter({"value":4.1}),"S6":AttributeSetter({"value":5.0})} + this_trait=AttributeSetter({"data":trait_data}) + mock_normalize.return_value=([2.3,1.1,6.3,3.6,4.1,5.0], [3.4,6.2,4.1,3.4,1.2,5.6], 6) + mock_normalize.side_effect=[([2.3,1.1,6.3,3.6,4.1,5.0], [3.4,6.2,4.1,3.4,1.2,5.6], 6),([2.3,1.1,6.3,3.6,4.1,5.0], [3.4,6.2,4.1,3.4,1.2,5.6], 6),([2.3,1.1,1.4], [3.4,6.2,4.1], 3)] + + results_pearsonr=get_sample_r_and_p_values(this_trait=this_trait,this_dataset={},target_vals=target_vals,target_dataset=target_dataset,type="pearson") + results_spearmanr=get_sample_r_and_p_values(this_trait=this_trait,this_dataset={},target_vals=target_vals,target_dataset=target_dataset,type="spearman") + results_num_overlap=get_sample_r_and_p_values(this_trait=this_trait,this_dataset={},target_vals=target_vals,target_dataset=target_dataset,type="pearson") + self.assertEqual(mock_normalize.call_count,3) + + self.assertEqual(results_pearsonr,[-0.21618688834430866, 0.680771605997119, 6]) + self.assertEqual(results_spearmanr,[-0.11595420713048969, 0.826848213385815, 6]) + self.assertEqual(results_num_overlap,None) + + def test_calculate_results(self): + corr_params={ + "type":"pearson" + } + trait_data={ + "T1":3.4, + "T2":6.2, + "T3":4.1, + "T4":3.4, + "T5":1.2, + "T6":5.6 + } + target_vals=[3.4, 6.2, 4.1,3.4,1.2,5.6] + + + diff --git a/wqflask/tests/unit/wqflask/correlation/test_show_corr_results.py b/wqflask/tests/unit/wqflask/correlation/test_show_corr_results.py index 4e63207e..969a84f5 100644 --- a/wqflask/tests/unit/wqflask/correlation/test_show_corr_results.py +++ b/wqflask/tests/unit/wqflask/correlation/test_show_corr_results.py @@ -12,8 +12,6 @@ class Trait: class TestShowCorrResults(unittest.TestCase): - def test_process_samples(self): - pass def test_get_header_fields(self): expected=[ ['Index', -- cgit v1.2.3 From 0adae692f2f0ce509b32d6654438213deb3da89b Mon Sep 17 00:00:00 2001 From: Alexanderkabui Date: Sat, 12 Dec 2020 23:09:04 +0300 Subject: add test for calculating correlation results --- wqflask/tests/unit/wqflask/api/test_correlation.py | 44 +++++++++++++++------- 1 file changed, 31 insertions(+), 13 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/unit/wqflask/api/test_correlation.py b/wqflask/tests/unit/wqflask/api/test_correlation.py index 077f7fa9..11c7d82b 100644 --- a/wqflask/tests/unit/wqflask/api/test_correlation.py +++ b/wqflask/tests/unit/wqflask/api/test_correlation.py @@ -1,10 +1,12 @@ import unittest from unittest import mock from wqflask import app +from collections import OrderedDict from wqflask.api.correlation import init_corr_params from wqflask.api.correlation import convert_to_mouse_gene_id from wqflask.api.correlation import do_literature_correlation_for_all_traits from wqflask.api.correlation import get_sample_r_and_p_values +from wqflask.api.correlation import calculate_results class AttributeSetter: @@ -12,6 +14,17 @@ class AttributeSetter: for k, v in obj.items(): setattr(self, k, v) +class MockDataset(AttributeSetter): + def get_trait_data(self): + return None + def retrieve_genes(self,id=None): + return { + "TT-1":"GH-1", + "TT-2":"GH-2", + "TT-3":"GH-3" + + } + class TestCorrelations(unittest.TestCase): def setUp(self): @@ -101,19 +114,24 @@ class TestCorrelations(unittest.TestCase): self.assertEqual(results_spearmanr,[-0.11595420713048969, 0.826848213385815, 6]) self.assertEqual(results_num_overlap,None) - def test_calculate_results(self): - corr_params={ - "type":"pearson" - } - trait_data={ - "T1":3.4, - "T2":6.2, - "T3":4.1, - "T4":3.4, - "T5":1.2, - "T6":5.6 - } - target_vals=[3.4, 6.2, 4.1,3.4,1.2,5.6] + @mock.patch("wqflask.api.correlation.do_literature_correlation_for_all_traits") + def test_calculate_results(self,literature_correlation): + + literature_correlation.return_value={'TT-1': ['GH-1', 0], 'TT-2': ['GH-2', 3], 'TT-3': ['GH-3', 1]} + + + + this_dataset=MockDataset({"group":AttributeSetter({"species":"rat"})}) + target_dataset=MockDataset({"group":AttributeSetter({"species":"rat"})}) + this_trait=AttributeSetter({"geneid":"GH-1"}) + corr_params={"type":"literature"} + sorted_results=calculate_results(this_trait=this_trait,this_dataset=this_dataset,target_dataset=target_dataset,corr_params=corr_params) + expected_results={'TT-2': ['GH-2', 3], 'TT-3': ['GH-3', 1], 'TT-1': ['GH-1', 0]} + + self.assertTrue(isinstance(sorted_results,OrderedDict)) + self.assertEqual(type(sorted_results),OrderedDict) + + -- cgit v1.2.3 From b7e2d17536febbeb47dc91015781cc6fc4647905 Mon Sep 17 00:00:00 2001 From: Alexanderkabui Date: Sat, 12 Dec 2020 23:36:27 +0300 Subject: replace assertEqual with assertAlmostEqual for floats --- wqflask/tests/unit/wqflask/api/test_correlation.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/unit/wqflask/api/test_correlation.py b/wqflask/tests/unit/wqflask/api/test_correlation.py index 11c7d82b..9fa848a4 100644 --- a/wqflask/tests/unit/wqflask/api/test_correlation.py +++ b/wqflask/tests/unit/wqflask/api/test_correlation.py @@ -108,10 +108,12 @@ class TestCorrelations(unittest.TestCase): results_pearsonr=get_sample_r_and_p_values(this_trait=this_trait,this_dataset={},target_vals=target_vals,target_dataset=target_dataset,type="pearson") results_spearmanr=get_sample_r_and_p_values(this_trait=this_trait,this_dataset={},target_vals=target_vals,target_dataset=target_dataset,type="spearman") results_num_overlap=get_sample_r_and_p_values(this_trait=this_trait,this_dataset={},target_vals=target_vals,target_dataset=target_dataset,type="pearson") - self.assertEqual(mock_normalize.call_count,3) - - self.assertEqual(results_pearsonr,[-0.21618688834430866, 0.680771605997119, 6]) - self.assertEqual(results_spearmanr,[-0.11595420713048969, 0.826848213385815, 6]) + expected_pearsonr=[-0.21618688834430866, 0.680771605997119, 6] + expected_spearmanr=[-0.11595420713048969, 0.826848213385815, 6] + for i,val in enumerate(expected_pearsonr): + self.assertAlmostEqual(val,results_pearsonr[i]) + for i,val in enumerate(expected_spearmanr): + self.assertAlmostEqual(val,results_spearmanr[i]) self.assertEqual(results_num_overlap,None) @mock.patch("wqflask.api.correlation.do_literature_correlation_for_all_traits") @@ -133,7 +135,6 @@ class TestCorrelations(unittest.TestCase): - -- cgit v1.2.3 From c3bfc7c07bba06c9334350111df0b9444b85b31b Mon Sep 17 00:00:00 2001 From: Alexanderkabui Date: Sat, 12 Dec 2020 23:56:26 +0300 Subject: modify tests for calculate correlation results --- wqflask/tests/unit/wqflask/api/test_correlation.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/unit/wqflask/api/test_correlation.py b/wqflask/tests/unit/wqflask/api/test_correlation.py index 9fa848a4..cbcd006d 100644 --- a/wqflask/tests/unit/wqflask/api/test_correlation.py +++ b/wqflask/tests/unit/wqflask/api/test_correlation.py @@ -131,7 +131,7 @@ class TestCorrelations(unittest.TestCase): expected_results={'TT-2': ['GH-2', 3], 'TT-3': ['GH-3', 1], 'TT-1': ['GH-1', 0]} self.assertTrue(isinstance(sorted_results,OrderedDict)) - self.assertEqual(type(sorted_results),OrderedDict) + self.assertEqual(dict(sorted_results),expected_results) -- cgit v1.2.3 From d10b6a9bc3ed4d3f824a0dfd115f05ed647aa8c3 Mon Sep 17 00:00:00 2001 From: Alexanderkabui Date: Mon, 14 Dec 2020 20:08:41 +0300 Subject: pep8 formatting and refactoring tests --- wqflask/tests/unit/wqflask/api/test_correlation.py | 145 +++++++++++---------- 1 file changed, 79 insertions(+), 66 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/unit/wqflask/api/test_correlation.py b/wqflask/tests/unit/wqflask/api/test_correlation.py index cbcd006d..d0264b87 100644 --- a/wqflask/tests/unit/wqflask/api/test_correlation.py +++ b/wqflask/tests/unit/wqflask/api/test_correlation.py @@ -1,7 +1,7 @@ import unittest from unittest import mock from wqflask import app -from collections import OrderedDict +from collections import OrderedDict from wqflask.api.correlation import init_corr_params from wqflask.api.correlation import convert_to_mouse_gene_id from wqflask.api.correlation import do_literature_correlation_for_all_traits @@ -14,14 +14,16 @@ class AttributeSetter: for k, v in obj.items(): setattr(self, k, v) + class MockDataset(AttributeSetter): def get_trait_data(self): return None - def retrieve_genes(self,id=None): + + def retrieve_genes(self, id=None): return { - "TT-1":"GH-1", - "TT-2":"GH-2", - "TT-3":"GH-3" + "TT-1": "GH-1", + "TT-2": "GH-2", + "TT-3": "GH-3" } @@ -59,8 +61,9 @@ class TestCorrelations(unittest.TestCase): rat_species_results = convert_to_mouse_gene_id( species="rat", gene_id="GH1") - mock_db.db.execute.return_value.fetchone.side_effect = [AttributeSetter({"mouse": "MG-1"}),AttributeSetter({"mouse":"MG-2"})] - + mock_db.db.execute.return_value.fetchone.side_effect = [ + AttributeSetter({"mouse": "MG-1"}), AttributeSetter({"mouse": "MG-2"})] + self.assertEqual(convert_to_mouse_gene_id( species="mouse", gene_id="MG-4"), "MG-4") self.assertEqual(convert_to_mouse_gene_id( @@ -68,73 +71,83 @@ class TestCorrelations(unittest.TestCase): self.assertEqual(convert_to_mouse_gene_id( species="human", gene_id="H1"), "MG-2") - - @mock.patch("wqflask.api.correlation.g") @mock.patch("wqflask.api.correlation.convert_to_mouse_gene_id") - def test_do_literature_correlation_for_all_traits(self,mock_convert_to_mouse_geneid,mock_db): - mock_convert_to_mouse_geneid.side_effect=["MG-1","MG-2;","MG-3","MG-4"] - - - trait_geneid_dict={ - "TT-1":"GH-1", - "TT-2":"GH-2", - "TT-3":"GH-3" + def test_do_literature_correlation_for_all_traits(self, mock_convert_to_mouse_geneid, mock_db): + mock_convert_to_mouse_geneid.side_effect = [ + "MG-1", "MG-2;", "MG-3", "MG-4"] - } - mock_db.db.execute.return_value.fetchone.side_effect=[AttributeSetter({"value":"V1"}),AttributeSetter({"value":"V2"}),AttributeSetter({"value":"V3"})] + trait_geneid_dict = { + "TT-1": "GH-1", + "TT-2": "GH-2", + "TT-3": "GH-3" + } + mock_db.db.execute.return_value.fetchone.side_effect = [AttributeSetter( + {"value": "V1"}), AttributeSetter({"value": "V2"}), AttributeSetter({"value": "V3"})] - this_trait=AttributeSetter({"geneid":"GH-1"}) + this_trait = AttributeSetter({"geneid": "GH-1"}) - target_dataset=AttributeSetter({"group":AttributeSetter({"species":"rat"})}) - results=do_literature_correlation_for_all_traits(this_trait=this_trait,target_dataset=target_dataset,trait_geneid_dict=trait_geneid_dict,corr_params={}) + target_dataset = AttributeSetter( + {"group": AttributeSetter({"species": "rat"})}) + results = do_literature_correlation_for_all_traits( + this_trait=this_trait, target_dataset=target_dataset, trait_geneid_dict=trait_geneid_dict, corr_params={}) - expected_results={'TT-1': ['GH-1', 0], 'TT-2': ['GH-2', 'V1'], 'TT-3': ['GH-3', 'V2']} - self.assertEqual(results,expected_results) + expected_results = {'TT-1': ['GH-1', 0], + 'TT-2': ['GH-2', 'V1'], 'TT-3': ['GH-3', 'V2']} + self.assertEqual(results, expected_results) @mock.patch("wqflask.api.correlation.corr_result_helpers.normalize_values") - def test_get_sample_r_and_p_values(self,mock_normalize): - - group=AttributeSetter({"samplelist":["S1","S2","S3","S4","S5","S6","S7"]}) - target_dataset=AttributeSetter({"group":group}) - - target_vals=[3.4, 6.2, 4.1,3.4,1.2,5.6] - trait_data={"S1":AttributeSetter({"value":2.3}),"S2":AttributeSetter({"value":1.1}),"S3":AttributeSetter({"value":6.3}),"S4":AttributeSetter({"value":3.6}),"S5":AttributeSetter({"value":4.1}),"S6":AttributeSetter({"value":5.0})} - this_trait=AttributeSetter({"data":trait_data}) - mock_normalize.return_value=([2.3,1.1,6.3,3.6,4.1,5.0], [3.4,6.2,4.1,3.4,1.2,5.6], 6) - mock_normalize.side_effect=[([2.3,1.1,6.3,3.6,4.1,5.0], [3.4,6.2,4.1,3.4,1.2,5.6], 6),([2.3,1.1,6.3,3.6,4.1,5.0], [3.4,6.2,4.1,3.4,1.2,5.6], 6),([2.3,1.1,1.4], [3.4,6.2,4.1], 3)] - - results_pearsonr=get_sample_r_and_p_values(this_trait=this_trait,this_dataset={},target_vals=target_vals,target_dataset=target_dataset,type="pearson") - results_spearmanr=get_sample_r_and_p_values(this_trait=this_trait,this_dataset={},target_vals=target_vals,target_dataset=target_dataset,type="spearman") - results_num_overlap=get_sample_r_and_p_values(this_trait=this_trait,this_dataset={},target_vals=target_vals,target_dataset=target_dataset,type="pearson") - expected_pearsonr=[-0.21618688834430866, 0.680771605997119, 6] - expected_spearmanr=[-0.11595420713048969, 0.826848213385815, 6] - for i,val in enumerate(expected_pearsonr): - self.assertAlmostEqual(val,results_pearsonr[i]) - for i,val in enumerate(expected_spearmanr): - self.assertAlmostEqual(val,results_spearmanr[i]) - self.assertEqual(results_num_overlap,None) + def test_get_sample_r_and_p_values(self, mock_normalize): + + group = AttributeSetter( + {"samplelist": ["S1", "S2", "S3", "S4", "S5", "S6", "S7"]}) + target_dataset = AttributeSetter({"group": group}) + + target_vals = [3.4, 6.2, 4.1, 3.4, 1.2, 5.6] + trait_data = {"S1": AttributeSetter({"value": 2.3}), "S2": AttributeSetter({"value": 1.1}), + "S3": AttributeSetter( + {"value": 6.3}), "S4": AttributeSetter({"value": 3.6}), "S5": AttributeSetter({"value": 4.1}), + "S6": AttributeSetter({"value": 5.0})} + this_trait = AttributeSetter({"data": trait_data}) + mock_normalize.return_value = ([2.3, 1.1, 6.3, 3.6, 4.1, 5.0], + [3.4, 6.2, 4.1, 3.4, 1.2, 5.6], 6) + mock_normalize.side_effect = [([2.3, 1.1, 6.3, 3.6, 4.1, 5.0], + [3.4, 6.2, 4.1, 3.4, 1.2, 5.6], 6), + ([2.3, 1.1, 6.3, 3.6, 4.1, 5.0], + [3.4, 6.2, 4.1, 3.4, 1.2, 5.6], 6), + ([2.3, 1.1, 1.4], [3.4, 6.2, 4.1], 3)] + + results_pearsonr = get_sample_r_and_p_values(this_trait=this_trait, this_dataset={ + }, target_vals=target_vals, target_dataset=target_dataset, type="pearson") + results_spearmanr = get_sample_r_and_p_values(this_trait=this_trait, this_dataset={ + }, target_vals=target_vals, target_dataset=target_dataset, type="spearman") + results_num_overlap = get_sample_r_and_p_values(this_trait=this_trait, this_dataset={ + }, target_vals=target_vals, target_dataset=target_dataset, type="pearson") + expected_pearsonr = [-0.21618688834430866, 0.680771605997119, 6] + expected_spearmanr = [-0.11595420713048969, 0.826848213385815, 6] + for i, val in enumerate(expected_pearsonr): + self.assertAlmostEqual(val, results_pearsonr[i],4) + for i, val in enumerate(expected_spearmanr): + self.assertAlmostEqual(val, results_spearmanr[i],4) + self.assertEqual(results_num_overlap, None) @mock.patch("wqflask.api.correlation.do_literature_correlation_for_all_traits") - def test_calculate_results(self,literature_correlation): - - literature_correlation.return_value={'TT-1': ['GH-1', 0], 'TT-2': ['GH-2', 3], 'TT-3': ['GH-3', 1]} - - - - this_dataset=MockDataset({"group":AttributeSetter({"species":"rat"})}) - target_dataset=MockDataset({"group":AttributeSetter({"species":"rat"})}) - this_trait=AttributeSetter({"geneid":"GH-1"}) - corr_params={"type":"literature"} - sorted_results=calculate_results(this_trait=this_trait,this_dataset=this_dataset,target_dataset=target_dataset,corr_params=corr_params) - expected_results={'TT-2': ['GH-2', 3], 'TT-3': ['GH-3', 1], 'TT-1': ['GH-1', 0]} - - self.assertTrue(isinstance(sorted_results,OrderedDict)) - self.assertEqual(dict(sorted_results),expected_results) - - - - - - + def test_calculate_results(self, literature_correlation): + + literature_correlation.return_value = { + 'TT-1': ['GH-1', 0], 'TT-2': ['GH-2', 3], 'TT-3': ['GH-3', 1]} + + this_dataset = MockDataset( + {"group": AttributeSetter({"species": "rat"})}) + target_dataset = MockDataset( + {"group": AttributeSetter({"species": "rat"})}) + this_trait = AttributeSetter({"geneid": "GH-1"}) + corr_params = {"type": "literature"} + sorted_results = calculate_results( + this_trait=this_trait, this_dataset=this_dataset, target_dataset=target_dataset, corr_params=corr_params) + expected_results = {'TT-2': ['GH-2', 3], + 'TT-3': ['GH-3', 1], 'TT-1': ['GH-1', 0]} + + self.assertTrue(isinstance(sorted_results, OrderedDict)) + self.assertEqual(dict(sorted_results), expected_results) -- cgit v1.2.3 From 4773ac8715896489562df9321b4a4d34ae61d6a7 Mon Sep 17 00:00:00 2001 From: Alexanderkabui Date: Mon, 14 Dec 2020 20:10:37 +0300 Subject: pep8 formatting in wqflask/api/test_mapping.py --- wqflask/tests/unit/wqflask/api/test_mapping.py | 154 ++++++++++++------------- 1 file changed, 75 insertions(+), 79 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/unit/wqflask/api/test_mapping.py b/wqflask/tests/unit/wqflask/api/test_mapping.py index 5455b215..b094294a 100644 --- a/wqflask/tests/unit/wqflask/api/test_mapping.py +++ b/wqflask/tests/unit/wqflask/api/test_mapping.py @@ -5,108 +5,104 @@ from wqflask.api.mapping import do_mapping_for_api class AttributeSetter: - def __init__(self,obj): - for key,value in obj.items(): - setattr(self,key,value) + def __init__(self, obj): + for key, value in obj.items(): + setattr(self, key, value) + class MockGroup(AttributeSetter): def get_marker(self): - self.markers=[] + self.markers = [] + + class TestMapping(unittest.TestCase): - + def test_initialize_parameters(self): - expected_results={ - "format":"json", - "limit_to":False, - "mapping_method":"gemma", - "maf":0.01, - "use_loco":True, - "num_perm":0, - "perm_check":False + expected_results = { + "format": "json", + "limit_to": False, + "mapping_method": "gemma", + "maf": 0.01, + "use_loco": True, + "num_perm": 0, + "perm_check": False } - results=initialize_parameters(start_vars={},dataset={},this_trait={}) - self.assertEqual(results,expected_results) + results = initialize_parameters( + start_vars={}, dataset={}, this_trait={}) + self.assertEqual(results, expected_results) - start_vars={ - "format":"F1", - "limit_to":"1", - "mapping_method":"rqtl", - "control_marker":True, - "pair_scan":"true", - "interval_mapping":"true", - "use_loco":"true", - "num_perm":"14" + start_vars = { + "format": "F1", + "limit_to": "1", + "mapping_method": "rqtl", + "control_marker": True, + "pair_scan": "true", + "interval_mapping": "true", + "use_loco": "true", + "num_perm": "14" } - results_2=initialize_parameters(start_vars=start_vars,dataset={},this_trait={}) - expected_results={ - "format":"F1", - "limit_to":1, - "mapping_method":"gemma", - "maf":0.01, - "use_loco":True, - "num_perm":14, - "perm_check":"ON" + results_2 = initialize_parameters( + start_vars=start_vars, dataset={}, this_trait={}) + expected_results = { + "format": "F1", + "limit_to": 1, + "mapping_method": "gemma", + "maf": 0.01, + "use_loco": True, + "num_perm": 14, + "perm_check": "ON" } - self.assertEqual(results_2,expected_results) + self.assertEqual(results_2, expected_results) - @mock.patch("wqflask.api.mapping.rqtl_mapping.run_rqtl_geno") @mock.patch("wqflask.api.mapping.gemma_mapping.run_gemma") @mock.patch("wqflask.api.mapping.initialize_parameters") @mock.patch("wqflask.api.mapping.retrieve_sample_data") @mock.patch("wqflask.api.mapping.create_trait") @mock.patch("wqflask.api.mapping.data_set.create_dataset") - def test_do_mapping_for_api(self,mock_create_dataset,mock_trait,mock_retrieve_sample,mock_param,run_gemma - ,run_rqtl_geno): - start_vars={ - "db":"Temp", - "trait_id":"dewf3232rff2", - "format":"F1", - "mapping_method":"gemma", - "use_loco":True + def test_do_mapping_for_api(self, mock_create_dataset, mock_trait, mock_retrieve_sample, mock_param, run_gemma, run_rqtl_geno): + start_vars = { + "db": "Temp", + "trait_id": "dewf3232rff2", + "format": "F1", + "mapping_method": "gemma", + "use_loco": True } - sampleList=["S1","S2","S3","S4"] - samplelist=["S1","S2","S4"] - dataset=AttributeSetter({"group":samplelist}) - this_trait=AttributeSetter({}) - trait_data=AttributeSetter({ - "data":{ - "item1":AttributeSetter({"name":"S1","value":"S1_value"}), - "item2":AttributeSetter({"name":"S2","value":"S2_value"}), - "item3":AttributeSetter({"name":"S3","value":"S3_value"}), + sampleList = ["S1", "S2", "S3", "S4"] + samplelist = ["S1", "S2", "S4"] + dataset = AttributeSetter({"group": samplelist}) + this_trait = AttributeSetter({}) + trait_data = AttributeSetter({ + "data": { + "item1": AttributeSetter({"name": "S1", "value": "S1_value"}), + "item2": AttributeSetter({"name": "S2", "value": "S2_value"}), + "item3": AttributeSetter({"name": "S3", "value": "S3_value"}), } - }) - trait=AttributeSetter({ - "data":trait_data - }) - - dataset.return_value=dataset - mock_trait.return_value=this_trait - - mock_retrieve_sample.return_value=trait - mock_param.return_value={ - "format":"F1", - "limit_to":False, - "mapping_method":"gemma", - "maf":0.01, - "use_loco":"True", - "num_perm":14, - "perm_check":"ON" + }) + trait = AttributeSetter({ + "data": trait_data + }) + + dataset.return_value = dataset + mock_trait.return_value = this_trait + + mock_retrieve_sample.return_value = trait + mock_param.return_value = { + "format": "F1", + "limit_to": False, + "mapping_method": "gemma", + "maf": 0.01, + "use_loco": "True", + "num_perm": 14, + "perm_check": "ON" } - run_gemma.return_value=["results"] - results=do_mapping_for_api(start_vars=start_vars) - self.assertEqual(results,("results",None)) - - - - - - - + run_gemma.return_value = ["results"] + results = do_mapping_for_api(start_vars=start_vars) + self.assertEqual(results, ("results", None)) -- cgit v1.2.3 From 6b6820ec9975ae4c7e9628e0d2b41754b0429b0e Mon Sep 17 00:00:00 2001 From: Alexanderkabui Date: Wed, 16 Dec 2020 11:29:19 +0300 Subject: modify tests for show_corr_results --- wqflask/tests/unit/wqflask/correlation/__init__.py | 0 .../correlation/test_correlation_functions.py | 3 +- .../wqflask/correlation/test_show_corr_results.py | 174 +++++++++++---------- 3 files changed, 90 insertions(+), 87 deletions(-) create mode 100644 wqflask/tests/unit/wqflask/correlation/__init__.py (limited to 'wqflask/tests') diff --git a/wqflask/tests/unit/wqflask/correlation/__init__.py b/wqflask/tests/unit/wqflask/correlation/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/wqflask/tests/unit/wqflask/correlation/test_correlation_functions.py b/wqflask/tests/unit/wqflask/correlation/test_correlation_functions.py index db449eb1..44d2e0fc 100644 --- a/wqflask/tests/unit/wqflask/correlation/test_correlation_functions.py +++ b/wqflask/tests/unit/wqflask/correlation/test_correlation_functions.py @@ -5,8 +5,7 @@ from wqflask.correlation.correlation_functions import cal_zero_order_corr_for_ti class TestCorrelationFunctions(unittest.TestCase): - - + @mock.patch("wqflask.correlation.correlation_functions.MrnaAssayTissueData") def test_get_trait_symbol_and_tissue_values(self, mock_class): """test for getting trait symbol and tissue_values""" diff --git a/wqflask/tests/unit/wqflask/correlation/test_show_corr_results.py b/wqflask/tests/unit/wqflask/correlation/test_show_corr_results.py index 969a84f5..ffb96dd6 100644 --- a/wqflask/tests/unit/wqflask/correlation/test_show_corr_results.py +++ b/wqflask/tests/unit/wqflask/correlation/test_show_corr_results.py @@ -2,92 +2,96 @@ import unittest from unittest import mock from wqflask.correlation.show_corr_results import get_header_fields from wqflask.correlation.show_corr_results import generate_corr_json -from wqflask.correlation.show_corr_results import do_bicor -class Trait: - def __init__(self,trait_obj): - for key,value in trait_obj.items(): - setattr(self,key,value) +class AttributeSetter: + def __init__(self, trait_obj): + for key, value in trait_obj.items(): + setattr(self, key, value) -class TestShowCorrResults(unittest.TestCase): - def test_get_header_fields(self): - expected=[ - ['Index', - 'Record', - 'Symbol', - 'Description', - 'Location', - 'Mean', - 'Sample rho', - 'N', - 'Sample p(rho)', - 'Lit rho', - 'Tissue rho', - 'Tissue p(rho)', - 'Max LRS', - 'Max LRS Location', - 'Additive Effect'], - - ['Index', - 'ID', - 'Location', - 'Sample r', - 'N', - 'Sample p(r)'] - - ] - result1=get_header_fields("ProbeSet","spearman") - result2=get_header_fields("Other","Other") - self.assertEqual(result1,expected[0]) - self.assertEqual(result2,expected[1]) - - - - - def test_generate_corr_json(self): - this_trait=Trait({"name":"trait_test"}) - dataset=Trait({"name":"the_name"}) - target_dataset=Trait({"type":"Publish"}) - - trait_with_publish={ - "description_display":"Trait 2 description", - "authors":"trait_2 ", - "pubmed_id":"34n4nn31hn43", - "lrs_location":"N/A", - "additive":"", - "sample_r":100, - "num_overlap":3.2, - "view":True, - "name":"trait_1", - "pubmed_text":"2016", - "additive":"", - "sample_r":10.5, - "LRS_score_repr":"N/A", - "LRS_location_repr":"N/A", - "sample_p":5, - "num_overlap":"num_1" - - - - } - expected_results="""[{"trait_id": "trait_1", "description": "Trait 2 description", "authors": "trait_2 ", "pubmed_id": "34n4nn31hn43", "year": "2016", "lrs_score": "N/A", "lrs_location": "N/A", "additive": "N/A", "sample_r": "10.500", "num_overlap": "num_1", "sample_p": "5.000e+00"}]""" - - corr_results=[Trait(trait_with_publish)] - results=generate_corr_json(corr_results=corr_results,this_trait=this_trait,dataset=dataset,target_dataset=target_dataset,for_api=True) - self.assertEqual(results,expected_results) - - - - def test_generate_corr_json_view_false(self): - trait=Trait({"view":False}) - corr_results=[trait] - this_trait=Trait({"name":"trait_test"}) - dataset=Trait({"name":"the_name"}) - - - results_where_view_is_false=generate_corr_json(corr_results=corr_results,this_trait=this_trait,dataset={},target_dataset={},for_api=False) - - # self.assertEqual(results,[]) - self.assertEqual(results_where_view_is_false,"[]") \ No newline at end of file +class TestShowCorrResults(unittest.TestCase): + def test_get_header_fields(self): + expected = [ + ['Index', + 'Record', + 'Symbol', + 'Description', + 'Location', + 'Mean', + 'Sample rho', + 'N', + 'Sample p(rho)', + 'Lit rho', + 'Tissue rho', + 'Tissue p(rho)', + 'Max LRS', + 'Max LRS Location', + 'Additive Effect'], + + ['Index', + 'ID', + 'Location', + 'Sample r', + 'N', + 'Sample p(r)'] + + ] + result1 = get_header_fields("ProbeSet", "spearman") + result2 = get_header_fields("Other", "Other") + self.assertEqual(result1, expected[0]) + self.assertEqual(result2, expected[1]) + + @mock.patch("wqflask.correlation.show_corr_results.hmac.data_hmac") + def test_generate_corr_json(self, mock_data_hmac): + mock_data_hmac.return_value = "hajsdiau" + + dataset = AttributeSetter({"name": "the_name"}) + this_trait = AttributeSetter( + {"name": "trait_test", "dataset": dataset}) + target_dataset = AttributeSetter({"type": "Publish"}) + corr_trait_1 = AttributeSetter({ + "name": "trait_1", + "dataset": AttributeSetter({"name": "dataset_1"}), + "view": True, + "abbreviation": "T1", + "description_display": "Trait I description", + "authors": "JM J,JYEW", + "pubmed_id": "34n4nn31hn43", + "pubmed_text": "2016", + "pubmed_link": "https://www.load", + "lod_score": "", + "LRS_location_repr": "BXBS", + "additive": "", + "sample_r": 10.5, + "num_overlap": 2, + "sample_p": 5 + + + + + }) + corr_results = [corr_trait_1] + + dataset_type_other = { + "location": "cx-3-4", + "sample_4": 12.32, + "num_overlap": 3, + "sample_p": 10.34 + } + + expected_results = '[{"index": 1, "trait_id": "trait_1", "dataset": "dataset_1", "hmac": "hajsdiau", "abbreviation_display": "T1", "description": "Trait I description", "authors_display": "JM J,JYEW", "additive": "N/A", "pubmed_id": "34n4nn31hn43", "year": "2016", "lod_score": "N/A", "lrs_location": "BXBS", "sample_r": "10.500", "num_overlap": 2, "sample_p": "5.000e+00"}]' + + results1 = generate_corr_json(corr_results=corr_results, this_trait=this_trait, + dataset=dataset, target_dataset=target_dataset, for_api=True) + self.assertEqual(expected_results, results1) + + def test_generate_corr_json_view_false(self): + trait = AttributeSetter({"view": False}) + corr_results = [trait] + this_trait = AttributeSetter({"name": "trait_test"}) + dataset = AttributeSetter({"name": "the_name"}) + + results_where_view_is_false = generate_corr_json( + corr_results=corr_results, this_trait=this_trait, dataset={}, target_dataset={}, for_api=False) + self.assertEqual(results_where_view_is_false, "[]") -- cgit v1.2.3 From f2e4e893f5639f216f8cc6fc57984aaebffd82ef Mon Sep 17 00:00:00 2001 From: Alexanderkabui Date: Mon, 14 Dec 2020 14:11:23 +0300 Subject: add tests for snp browser --- wqflask/tests/unit/wqflask/snp_browser/__init__.py | 0 .../unit/wqflask/snp_browser/test_snp_browser.py | 84 ++++++++++++++++++++++ 2 files changed, 84 insertions(+) create mode 100644 wqflask/tests/unit/wqflask/snp_browser/__init__.py create mode 100644 wqflask/tests/unit/wqflask/snp_browser/test_snp_browser.py (limited to 'wqflask/tests') diff --git a/wqflask/tests/unit/wqflask/snp_browser/__init__.py b/wqflask/tests/unit/wqflask/snp_browser/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/wqflask/tests/unit/wqflask/snp_browser/test_snp_browser.py b/wqflask/tests/unit/wqflask/snp_browser/test_snp_browser.py new file mode 100644 index 00000000..e8751778 --- /dev/null +++ b/wqflask/tests/unit/wqflask/snp_browser/test_snp_browser.py @@ -0,0 +1,84 @@ +import unittest +from unittest import mock +from wqflask import app +from wqflask.snp_browser.snp_browser import get_gene_id +from wqflask.snp_browser.snp_browser import get_gene_id_name_dict +from wqflask.snp_browser.snp_browser import check_if_in_gene +from wqflask.snp_browser.snp_browser import get_browser_sample_lists +from wqflask.snp_browser.snp_browser import get_header_list + +class TestSnpBrowser(unittest.TestCase): + def setUp(self): + self.app_context = app.app_context() + self.app_context.push() + + def tearDown(self): + self.app_context.pop() + + + @mock.patch("wqflask.snp_browser.snp_browser.g") + def test_get_gene_id(self, mock_db): + mock_db.db.execute.return_value.fetchone.return_value = "517d729f-aa13-4413-a885-40a3f7ff768a" + called_value="\n SELECT\n geneId\n FROM\n GeneList\n WHERE\n SpeciesId = c9c0f59e-1259-4cba-91e6-831ef1a99c83 AND geneSymbol = 'INSR'\n " + results = get_gene_id( + species_id="c9c0f59e-1259-4cba-91e6-831ef1a99c83", gene_name="INSR") + mock_db.db.execute.assert_called_once_with(called_value) + self.assertEqual(results, "517d729f-aa13-4413-a885-40a3f7ff768a") + + @mock.patch("wqflask.snp_browser.snp_browser.g") + def test_gene_id_name_dict(self,mock_db): + no_gene_names=[] + self.assertEqual("",get_gene_id_name_dict(species_id="fregb343bui43g4",gene_name_list=no_gene_names)) + gene_name_list=["GH1","GH2","GH3"] + mock_db.db.execute.return_value.fetchall.side_effect=[[],[("fsdf43-fseferger-f22","GH1"),("1sdf43-fsewferger-f22","GH2"), + ("fwdj43-fstferger-f22","GH3")]] + no_results=get_gene_id_name_dict(species_id="ret3-32rf32",gene_name_list=gene_name_list) + results_found=get_gene_id_name_dict(species_id="ret3-32rf32",gene_name_list=gene_name_list) + expected_found= {'GH1': 'fsdf43-fseferger-f22', 'GH2': '1sdf43-fsewferger-f22', 'GH3': 'fwdj43-fstferger-f22'} + db_query_value="\n SELECT\n geneId, geneSymbol\n FROM\n GeneList\n WHERE\n SpeciesId = ret3-32rf32 AND geneSymbol in ('GH1','GH2','GH3')\n " + mock_db.db.execute.assert_called_with(db_query_value) + self.assertEqual(results_found,expected_found) + self.assertEqual(no_results,{}) + + @mock.patch("wqflask.snp_browser.snp_browser.g") + def test_check_if_in_gene(self,mock_db): + mock_db.db.execute.return_value.fetchone.side_effect=[("fsdf-232sdf-sdf","GHA"),""] + results_found=check_if_in_gene(species_id="517d729f-aa13-4413-a885-40a3f7ff768a",chr="CH1",mb=12.09) + db_query_value="SELECT geneId, geneSymbol\n FROM GeneList\n WHERE SpeciesId = 517d729f-aa13-4413-a885-40a3f7ff768a AND chromosome = 'CH1' AND\n (txStart < 12.09 AND txEnd > 12.09); " + gene_not_found=check_if_in_gene(species_id="517d729f-aa13-4413-a885-40a3f7ff768a",chr="CH1",mb=12.09) + mock_db.db.execute.assert_called_with(db_query_value) + self.assertEqual(gene_not_found,"") + + @mock.patch("wqflask.snp_browser.snp_browser.g") + def test_get_browser_sample_lists(self,mock_db): + mock_db.db.execute.return_value.fetchall.return_value=[] + + results=get_browser_sample_lists(species_id="12") + self.assertEqual(results, {'mouse': [], 'rat': []}) + + def test_get_header_list(self): + empty_columns={"snp_source":"false","conservation_score":"true","gene_name":"false","transcript":"false","exon":"false","domain_2":"true","function":"false","function_details":"true"} + strains={"mouse":["S1","S2","S3","S4","S5"],"rat":[]} + expected_results=([['Index', 'SNP ID', 'Chr', 'Mb', 'Alleles', 'ConScore', 'Domain 1', 'Domain 2', 'Details'], ['S1', 'S2', 'S3', 'S4', 'S5']], 5) + + results_with_snp=get_header_list(variant_type="SNP",strains=strains,species="Mouse",empty_columns=empty_columns) + results_with_indel=get_header_list(variant_type="InDel",strains=strains,species="rat",empty_columns=[]) + expected_results_with_indel=(['Index', 'ID', 'Type', 'InDel Chr', 'Mb Start', 'Mb End', 'Strand', 'Size', 'Sequence', 'Source'],0) + + self.assertEqual(expected_results,results_with_snp) + self.assertEqual(results_with_indel,expected_results_with_indel) + + + + + + + + + + + + + + + -- cgit v1.2.3 From db3170eb2fe66d8fd337803a730c18367df1b150 Mon Sep 17 00:00:00 2001 From: Alexanderkabui Date: Mon, 14 Dec 2020 16:11:07 +0300 Subject: add tests for type checking --- wqflask/tests/unit/utility/test_type_checking.py | 57 ++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 wqflask/tests/unit/utility/test_type_checking.py (limited to 'wqflask/tests') diff --git a/wqflask/tests/unit/utility/test_type_checking.py b/wqflask/tests/unit/utility/test_type_checking.py new file mode 100644 index 00000000..1ea11695 --- /dev/null +++ b/wqflask/tests/unit/utility/test_type_checking.py @@ -0,0 +1,57 @@ +import unittest +from utility.type_checking import is_float +from utility.type_checking import is_int +from utility.type_checking import is_str +from utility.type_checking import get_float +from utility.type_checking import get_int +from utility.type_checking import get_string +class TestTypeChecking(unittest.TestCase): + def test_is_float(self): + floats=[2,1.2,'3.1'] + not_floats=["String",None,[],()] + for flt in floats: + results=is_float(flt) + self.assertTrue(results) + for nflt in not_floats: + results=is_float(nflt) + self.assertFalse(results) + + def test_is_int(self): + int_values=[1,1.1] + not_int_values=["1sdf",None,[],"1.1"] + for int_val in int_values: + results=is_int(int_val) + self.assertTrue(results) + for not_int in not_int_values: + results=is_int(not_int) + self.assertFalse(results) + + def test_is_str(self): + string_values=[1,False,[],{},"string_value"] + falsey_values=[None] + for string_val in string_values: + results=is_str(string_val) + self.assertTrue(results) + for non_string in falsey_values: + results=is_str(non_string) + self.assertFalse(results) + + + def test_get_float(self): + vars_object={"min_value":"12"} + results=get_float(vars_object,"min_value") + self.assertEqual(results,12.0) + + def test_get_int(self): + vars_object={"lx_value":"1"} + results=get_int(vars_object,"lx_value") + self.assertEqual(results,1) + + def test_get_string(self): + string_object={"mx_value":1} + results=get_string(string_object,"mx_value") + self.assertEqual(results,"1") + + + + -- cgit v1.2.3 From 868b8cba1cda983d8d401e60e30794529b557c80 Mon Sep 17 00:00:00 2001 From: Alexanderkabui Date: Mon, 14 Dec 2020 22:36:36 +0300 Subject: modify get_header tests --- .../unit/wqflask/snp_browser/test_snp_browser.py | 23 +++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/unit/wqflask/snp_browser/test_snp_browser.py b/wqflask/tests/unit/wqflask/snp_browser/test_snp_browser.py index e8751778..9ec32c78 100644 --- a/wqflask/tests/unit/wqflask/snp_browser/test_snp_browser.py +++ b/wqflask/tests/unit/wqflask/snp_browser/test_snp_browser.py @@ -15,6 +15,18 @@ class TestSnpBrowser(unittest.TestCase): def tearDown(self): self.app_context.pop() + def test_get_header_list(self): + empty_columns={"snp_source":"false","conservation_score":"true","gene_name":"false","transcript":"false","exon":"false","domain_2":"true","function":"false","function_details":"true"} + strains={"mouse":["S1","S2","S3","S4","S5"],"rat":[]} + expected_results=([['Index', 'SNP ID', 'Chr', 'Mb', 'Alleles', 'ConScore', 'Domain 1', 'Domain 2', 'Details'], ['S1', 'S2', 'S3', 'S4', 'S5']], 5) + + results_with_snp=get_header_list(variant_type="SNP",strains=strains,species="Mouse",empty_columns=empty_columns) + results_with_indel=get_header_list(variant_type="InDel",strains=strains,species="rat",empty_columns=[]) + expected_results_with_indel=(['Index', 'ID', 'Type', 'InDel Chr', 'Mb Start', 'Mb End', 'Strand', 'Size', 'Sequence', 'Source'],0) + + self.assertEqual(expected_results,results_with_snp) + self.assertEqual(results_with_indel,expected_results_with_indel) + @mock.patch("wqflask.snp_browser.snp_browser.g") def test_get_gene_id(self, mock_db): @@ -56,17 +68,6 @@ class TestSnpBrowser(unittest.TestCase): results=get_browser_sample_lists(species_id="12") self.assertEqual(results, {'mouse': [], 'rat': []}) - def test_get_header_list(self): - empty_columns={"snp_source":"false","conservation_score":"true","gene_name":"false","transcript":"false","exon":"false","domain_2":"true","function":"false","function_details":"true"} - strains={"mouse":["S1","S2","S3","S4","S5"],"rat":[]} - expected_results=([['Index', 'SNP ID', 'Chr', 'Mb', 'Alleles', 'ConScore', 'Domain 1', 'Domain 2', 'Details'], ['S1', 'S2', 'S3', 'S4', 'S5']], 5) - - results_with_snp=get_header_list(variant_type="SNP",strains=strains,species="Mouse",empty_columns=empty_columns) - results_with_indel=get_header_list(variant_type="InDel",strains=strains,species="rat",empty_columns=[]) - expected_results_with_indel=(['Index', 'ID', 'Type', 'InDel Chr', 'Mb Start', 'Mb End', 'Strand', 'Size', 'Sequence', 'Source'],0) - - self.assertEqual(expected_results,results_with_snp) - self.assertEqual(results_with_indel,expected_results_with_indel) -- cgit v1.2.3 From 5a73d56fdbe197e99b476d49d4adce9403c8daeb Mon Sep 17 00:00:00 2001 From: Alexanderkabui Date: Fri, 18 Dec 2020 15:18:19 +0300 Subject: refactor tests and pep8 formatting --- wqflask/tests/unit/utility/test_type_checking.py | 93 ++++++++-------- .../unit/wqflask/snp_browser/test_snp_browser.py | 120 ++++++++++++--------- 2 files changed, 112 insertions(+), 101 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/unit/utility/test_type_checking.py b/wqflask/tests/unit/utility/test_type_checking.py index 1ea11695..48d110c7 100644 --- a/wqflask/tests/unit/utility/test_type_checking.py +++ b/wqflask/tests/unit/utility/test_type_checking.py @@ -5,53 +5,50 @@ from utility.type_checking import is_str from utility.type_checking import get_float from utility.type_checking import get_int from utility.type_checking import get_string -class TestTypeChecking(unittest.TestCase): - def test_is_float(self): - floats=[2,1.2,'3.1'] - not_floats=["String",None,[],()] - for flt in floats: - results=is_float(flt) - self.assertTrue(results) - for nflt in not_floats: - results=is_float(nflt) - self.assertFalse(results) - - def test_is_int(self): - int_values=[1,1.1] - not_int_values=["1sdf",None,[],"1.1"] - for int_val in int_values: - results=is_int(int_val) - self.assertTrue(results) - for not_int in not_int_values: - results=is_int(not_int) - self.assertFalse(results) - - def test_is_str(self): - string_values=[1,False,[],{},"string_value"] - falsey_values=[None] - for string_val in string_values: - results=is_str(string_val) - self.assertTrue(results) - for non_string in falsey_values: - results=is_str(non_string) - self.assertFalse(results) - - - def test_get_float(self): - vars_object={"min_value":"12"} - results=get_float(vars_object,"min_value") - self.assertEqual(results,12.0) - - def test_get_int(self): - vars_object={"lx_value":"1"} - results=get_int(vars_object,"lx_value") - self.assertEqual(results,1) - - def test_get_string(self): - string_object={"mx_value":1} - results=get_string(string_object,"mx_value") - self.assertEqual(results,"1") - - +class TestTypeChecking(unittest.TestCase): + def test_is_float(self): + floats = [2, 1.2, '3.1'] + not_floats = ["String", None, [], ()] + for flt in floats: + results = is_float(flt) + self.assertTrue(results) + for nflt in not_floats: + results = is_float(nflt) + self.assertFalse(results) + + def test_is_int(self): + int_values = [1, 1.1] + not_int_values = ["string", None, [], "1.1"] + for int_val in int_values: + results = is_int(int_val) + self.assertTrue(results) + for not_int in not_int_values: + results = is_int(not_int) + self.assertFalse(results) + + def test_is_str(self): + string_values = [1, False, [], {}, "string_value"] + falsey_values = [None] + for string_val in string_values: + results = is_str(string_val) + self.assertTrue(results) + for non_string in falsey_values: + results = is_str(non_string) + self.assertFalse(results) + + def test_get_float(self): + vars_object = {"min_value": "12"} + results = get_float(vars_object, "min_value") + self.assertEqual(results, 12.0) + + def test_get_int(self): + vars_object = {"lx_value": "1"} + results = get_int(vars_object, "lx_value") + self.assertEqual(results, 1) + + def test_get_string(self): + string_object = {"mx_value": 1} + results = get_string(string_object, "mx_value") + self.assertEqual(results, "1") \ No newline at end of file diff --git a/wqflask/tests/unit/wqflask/snp_browser/test_snp_browser.py b/wqflask/tests/unit/wqflask/snp_browser/test_snp_browser.py index 9ec32c78..496d228f 100644 --- a/wqflask/tests/unit/wqflask/snp_browser/test_snp_browser.py +++ b/wqflask/tests/unit/wqflask/snp_browser/test_snp_browser.py @@ -7,6 +7,7 @@ from wqflask.snp_browser.snp_browser import check_if_in_gene from wqflask.snp_browser.snp_browser import get_browser_sample_lists from wqflask.snp_browser.snp_browser import get_header_list + class TestSnpBrowser(unittest.TestCase): def setUp(self): self.app_context = app.app_context() @@ -16,70 +17,83 @@ class TestSnpBrowser(unittest.TestCase): self.app_context.pop() def test_get_header_list(self): - empty_columns={"snp_source":"false","conservation_score":"true","gene_name":"false","transcript":"false","exon":"false","domain_2":"true","function":"false","function_details":"true"} - strains={"mouse":["S1","S2","S3","S4","S5"],"rat":[]} - expected_results=([['Index', 'SNP ID', 'Chr', 'Mb', 'Alleles', 'ConScore', 'Domain 1', 'Domain 2', 'Details'], ['S1', 'S2', 'S3', 'S4', 'S5']], 5) - - results_with_snp=get_header_list(variant_type="SNP",strains=strains,species="Mouse",empty_columns=empty_columns) - results_with_indel=get_header_list(variant_type="InDel",strains=strains,species="rat",empty_columns=[]) - expected_results_with_indel=(['Index', 'ID', 'Type', 'InDel Chr', 'Mb Start', 'Mb End', 'Strand', 'Size', 'Sequence', 'Source'],0) - - self.assertEqual(expected_results,results_with_snp) - self.assertEqual(results_with_indel,expected_results_with_indel) - + empty_columns = {"snp_source": "false", "conservation_score": "true", "gene_name": "false", + "transcript": "false", "exon": "false", "domain_2": "true", "function": "false", "function_details": "true"} + strains = {"mouse": ["S1", "S2", "S3", "S4", "S5"], "rat": []} + expected_results = ([['Index', 'SNP ID', 'Chr', 'Mb', 'Alleles', 'ConScore', + 'Domain 1', 'Domain 2', 'Details'], ['S1', 'S2', 'S3', 'S4', 'S5']], 5) + + results_with_snp = get_header_list( + variant_type="SNP", strains=strains, species="Mouse", empty_columns=empty_columns) + results_with_indel = get_header_list( + variant_type="InDel", strains=strains, species="rat", empty_columns=[]) + expected_results_with_indel = ( + ['Index', 'ID', 'Type', 'InDel Chr', 'Mb Start', + 'Mb End', 'Strand', 'Size', 'Sequence', 'Source'], 0) + + self.assertEqual(expected_results, results_with_snp) + self.assertEqual(results_with_indel, expected_results_with_indel) @mock.patch("wqflask.snp_browser.snp_browser.g") def test_get_gene_id(self, mock_db): mock_db.db.execute.return_value.fetchone.return_value = "517d729f-aa13-4413-a885-40a3f7ff768a" - called_value="\n SELECT\n geneId\n FROM\n GeneList\n WHERE\n SpeciesId = c9c0f59e-1259-4cba-91e6-831ef1a99c83 AND geneSymbol = 'INSR'\n " + db_query_value = """ + SELECT + geneId + FROM + GeneList + WHERE + SpeciesId = c9c0f59e-1259-4cba-91e6-831ef1a99c83 AND geneSymbol = 'INSR' + """ results = get_gene_id( species_id="c9c0f59e-1259-4cba-91e6-831ef1a99c83", gene_name="INSR") - mock_db.db.execute.assert_called_once_with(called_value) + mock_db.db.execute.assert_called_once_with(db_query_value) self.assertEqual(results, "517d729f-aa13-4413-a885-40a3f7ff768a") @mock.patch("wqflask.snp_browser.snp_browser.g") - def test_gene_id_name_dict(self,mock_db): - no_gene_names=[] - self.assertEqual("",get_gene_id_name_dict(species_id="fregb343bui43g4",gene_name_list=no_gene_names)) - gene_name_list=["GH1","GH2","GH3"] - mock_db.db.execute.return_value.fetchall.side_effect=[[],[("fsdf43-fseferger-f22","GH1"),("1sdf43-fsewferger-f22","GH2"), - ("fwdj43-fstferger-f22","GH3")]] - no_results=get_gene_id_name_dict(species_id="ret3-32rf32",gene_name_list=gene_name_list) - results_found=get_gene_id_name_dict(species_id="ret3-32rf32",gene_name_list=gene_name_list) - expected_found= {'GH1': 'fsdf43-fseferger-f22', 'GH2': '1sdf43-fsewferger-f22', 'GH3': 'fwdj43-fstferger-f22'} - db_query_value="\n SELECT\n geneId, geneSymbol\n FROM\n GeneList\n WHERE\n SpeciesId = ret3-32rf32 AND geneSymbol in ('GH1','GH2','GH3')\n " - mock_db.db.execute.assert_called_with(db_query_value) - self.assertEqual(results_found,expected_found) - self.assertEqual(no_results,{}) + def test_gene_id_name_dict(self, mock_db): + no_gene_names = [] + self.assertEqual("", get_gene_id_name_dict( + species_id="fregb343bui43g4", gene_name_list=no_gene_names)) + gene_name_list = ["GH1", "GH2", "GH3"] + mock_db.db.execute.return_value.fetchall.side_effect = [[], [("fsdf43-fseferger-f22", "GH1"), ("1sdf43-fsewferger-f22", "GH2"), + ("fwdj43-fstferger-f22", "GH3")]] + no_results = get_gene_id_name_dict( + species_id="ret3-32rf32", gene_name_list=gene_name_list) + results_found = get_gene_id_name_dict( + species_id="ret3-32rf32", gene_name_list=gene_name_list) + expected_found = {'GH1': 'fsdf43-fseferger-f22', + 'GH2': '1sdf43-fsewferger-f22', 'GH3': 'fwdj43-fstferger-f22'} + db_query_value = """ + SELECT + geneId, geneSymbol + FROM + GeneList + WHERE + SpeciesId = ret3-32rf32 AND geneSymbol in ('GH1','GH2','GH3') + """ + mock_db.db.execute.assert_called_with(db_query_value) + self.assertEqual(results_found, expected_found) + self.assertEqual(no_results, {}) @mock.patch("wqflask.snp_browser.snp_browser.g") - def test_check_if_in_gene(self,mock_db): - mock_db.db.execute.return_value.fetchone.side_effect=[("fsdf-232sdf-sdf","GHA"),""] - results_found=check_if_in_gene(species_id="517d729f-aa13-4413-a885-40a3f7ff768a",chr="CH1",mb=12.09) - db_query_value="SELECT geneId, geneSymbol\n FROM GeneList\n WHERE SpeciesId = 517d729f-aa13-4413-a885-40a3f7ff768a AND chromosome = 'CH1' AND\n (txStart < 12.09 AND txEnd > 12.09); " - gene_not_found=check_if_in_gene(species_id="517d729f-aa13-4413-a885-40a3f7ff768a",chr="CH1",mb=12.09) - mock_db.db.execute.assert_called_with(db_query_value) - self.assertEqual(gene_not_found,"") + def test_check_if_in_gene(self, mock_db): + mock_db.db.execute.return_value.fetchone.side_effect = [ + ("fsdf-232sdf-sdf", "GHA"), ""] + results_found = check_if_in_gene( + species_id="517d729f-aa13-4413-a885-40a3f7ff768a", chr="CH1", mb=12.09) + db_query_value = """SELECT geneId, geneSymbol + FROM GeneList + WHERE SpeciesId = 517d729f-aa13-4413-a885-40a3f7ff768a AND chromosome = 'CH1' AND + (txStart < 12.09 AND txEnd > 12.09); """ + gene_not_found = check_if_in_gene( + species_id="517d729f-aa13-4413-a885-40a3f7ff768a", chr="CH1", mb=12.09) + mock_db.db.execute.assert_called_with(db_query_value) + self.assertEqual(gene_not_found, "") @mock.patch("wqflask.snp_browser.snp_browser.g") - def test_get_browser_sample_lists(self,mock_db): - mock_db.db.execute.return_value.fetchall.return_value=[] - - results=get_browser_sample_lists(species_id="12") - self.assertEqual(results, {'mouse': [], 'rat': []}) - - - - - - - - - - - - - - - + def test_get_browser_sample_lists(self, mock_db): + mock_db.db.execute.return_value.fetchall.return_value = [] + results = get_browser_sample_lists(species_id="12") + self.assertEqual(results, {'mouse': [], 'rat': []}) -- cgit v1.2.3 From b605f52440e84909631b6afdf510a9e513260901 Mon Sep 17 00:00:00 2001 From: Alexanderkabui Date: Wed, 6 Jan 2021 08:21:44 +0300 Subject: fix tests for show_corr_results --- wqflask/tests/unit/wqflask/correlation/test_show_corr_results.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/unit/wqflask/correlation/test_show_corr_results.py b/wqflask/tests/unit/wqflask/correlation/test_show_corr_results.py index ffb96dd6..33601990 100644 --- a/wqflask/tests/unit/wqflask/correlation/test_show_corr_results.py +++ b/wqflask/tests/unit/wqflask/correlation/test_show_corr_results.py @@ -61,6 +61,7 @@ class TestShowCorrResults(unittest.TestCase): "pubmed_text": "2016", "pubmed_link": "https://www.load", "lod_score": "", + "mean": "", "LRS_location_repr": "BXBS", "additive": "", "sample_r": 10.5, @@ -80,7 +81,7 @@ class TestShowCorrResults(unittest.TestCase): "sample_p": 10.34 } - expected_results = '[{"index": 1, "trait_id": "trait_1", "dataset": "dataset_1", "hmac": "hajsdiau", "abbreviation_display": "T1", "description": "Trait I description", "authors_display": "JM J,JYEW", "additive": "N/A", "pubmed_id": "34n4nn31hn43", "year": "2016", "lod_score": "N/A", "lrs_location": "BXBS", "sample_r": "10.500", "num_overlap": 2, "sample_p": "5.000e+00"}]' + expected_results = '[{"index": 1, "trait_id": "trait_1", "dataset": "dataset_1", "hmac": "hajsdiau", "abbreviation_display": "T1", "description": "Trait I description", "mean": "N/A", "authors_display": "JM J,JYEW", "additive": "N/A", "pubmed_id": "34n4nn31hn43", "year": "2016", "lod_score": "N/A", "lrs_location": "BXBS", "sample_r": "10.500", "num_overlap": 2, "sample_p": "5.000e+00"}]' results1 = generate_corr_json(corr_results=corr_results, this_trait=this_trait, dataset=dataset, target_dataset=target_dataset, for_api=True) -- cgit v1.2.3 From 4203e9609dcf59fa7369e9e0dde02d0da3c8e32f Mon Sep 17 00:00:00 2001 From: Alexanderkabui Date: Wed, 6 Jan 2021 08:50:30 +0300 Subject: update tests for snp_browser --- .../tests/unit/wqflask/snp_browser/test_snp_browser.py | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/unit/wqflask/snp_browser/test_snp_browser.py b/wqflask/tests/unit/wqflask/snp_browser/test_snp_browser.py index 496d228f..7fa96dba 100644 --- a/wqflask/tests/unit/wqflask/snp_browser/test_snp_browser.py +++ b/wqflask/tests/unit/wqflask/snp_browser/test_snp_browser.py @@ -21,18 +21,25 @@ class TestSnpBrowser(unittest.TestCase): "transcript": "false", "exon": "false", "domain_2": "true", "function": "false", "function_details": "true"} strains = {"mouse": ["S1", "S2", "S3", "S4", "S5"], "rat": []} expected_results = ([['Index', 'SNP ID', 'Chr', 'Mb', 'Alleles', 'ConScore', - 'Domain 1', 'Domain 2', 'Details'], ['S1', 'S2', 'S3', 'S4', 'S5']], 5) + 'Domain 1', 'Domain 2', 'Details'], + ['S1', 'S2', 'S3', 'S4', 'S5']], 5, + ['index', 'snp_name', 'chr', 'mb_formatted', 'alleles', + 'conservation_score', 'domain_1', 'domain_2', + 'function_details', 'S1', 'S2', 'S3', 'S4', 'S5']) results_with_snp = get_header_list( variant_type="SNP", strains=strains, species="Mouse", empty_columns=empty_columns) results_with_indel = get_header_list( variant_type="InDel", strains=strains, species="rat", empty_columns=[]) expected_results_with_indel = ( - ['Index', 'ID', 'Type', 'InDel Chr', 'Mb Start', - 'Mb End', 'Strand', 'Size', 'Sequence', 'Source'], 0) + ['Index', 'ID', 'Type', 'InDel Chr', 'Mb Start', + 'Mb End', 'Strand', 'Size', 'Sequence', 'Source'], 0, + ['index', 'indel_name', 'indel_type', 'indel_chr', 'indel_mb_s', + 'indel_mb_e', 'indel_strand', 'indel_size', 'indel_sequence', 'source_name']) self.assertEqual(expected_results, results_with_snp) - self.assertEqual(results_with_indel, expected_results_with_indel) + # self.assertEqual(results_with_indel, expected_results_with_indel) + self.assertEqual(expected_results_with_indel, results_with_indel) @mock.patch("wqflask.snp_browser.snp_browser.g") def test_get_gene_id(self, mock_db): -- cgit v1.2.3 From e55aa51937abf03897a20a52dd7dbf3cfc4ac6c8 Mon Sep 17 00:00:00 2001 From: Alexanderkabui Date: Wed, 6 Jan 2021 08:54:47 +0300 Subject: remove comments --- wqflask/tests/unit/wqflask/snp_browser/test_snp_browser.py | 1 - 1 file changed, 1 deletion(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/unit/wqflask/snp_browser/test_snp_browser.py b/wqflask/tests/unit/wqflask/snp_browser/test_snp_browser.py index 7fa96dba..ce3e7b83 100644 --- a/wqflask/tests/unit/wqflask/snp_browser/test_snp_browser.py +++ b/wqflask/tests/unit/wqflask/snp_browser/test_snp_browser.py @@ -38,7 +38,6 @@ class TestSnpBrowser(unittest.TestCase): 'indel_mb_e', 'indel_strand', 'indel_size', 'indel_sequence', 'source_name']) self.assertEqual(expected_results, results_with_snp) - # self.assertEqual(results_with_indel, expected_results_with_indel) self.assertEqual(expected_results_with_indel, results_with_indel) @mock.patch("wqflask.snp_browser.snp_browser.g") -- cgit v1.2.3 From 5187e582721ddfbb1e864378823f2685748bf5f2 Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Mon, 18 Jan 2021 11:15:33 +0300 Subject: Pass salt as bytes when testing pbkdf2_hex * wqflask/tests/unit/wqflask/test_pbkdf2.py (test_pbkdf2_hex): Make password salt bytes. Breaking change introduced in 0bac313ba. --- wqflask/tests/unit/wqflask/test_pbkdf2.py | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/unit/wqflask/test_pbkdf2.py b/wqflask/tests/unit/wqflask/test_pbkdf2.py index a33fbd4f..7ad6c83e 100644 --- a/wqflask/tests/unit/wqflask/test_pbkdf2.py +++ b/wqflask/tests/unit/wqflask/test_pbkdf2.py @@ -11,43 +11,43 @@ class TestPbkdf2(unittest.TestCase): """ for password, salt, iterations, keylen, expected_value in [ - ('password', 'salt', 1, 20, + ('password', b'salt', 1, 20, '0c60c80f961f0e71f3a9b524af6012062fe037a6'), - ('password', 'salt', 2, 20, + ('password', b'salt', 2, 20, 'ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957'), - ('password', 'salt', 4096, 20, + ('password', b'salt', 4096, 20, '4b007901b765489abead49d926f721d065a429c1'), ('passwordPASSWORDpassword', - 'saltSALTsaltSALTsaltSALTsaltSALTsalt', + b'saltSALTsaltSALTsaltSALTsaltSALTsalt', 4096, 25, '3d2eec4fe41c849b80c8d83662c0e44a8b291a964cf2f07038'), - ('pass\x00word', 'sa\x00lt', 4096, 16, + ('pass\x00word', b'sa\x00lt', 4096, 16, '56fa6aa75548099dcc37d7f03425e0c3'), - ('password', 'ATHENA.MIT.EDUraeburn', 1, 16, + ('password', b'ATHENA.MIT.EDUraeburn', 1, 16, 'cdedb5281bb2f801565a1122b2563515'), - ('password', 'ATHENA.MIT.EDUraeburn', 1, 32, + ('password', b'ATHENA.MIT.EDUraeburn', 1, 32, ('cdedb5281bb2f80' '1565a1122b256351' '50ad1f7a04bb9f3a33' '3ecc0e2e1f70837')), - ('password', 'ATHENA.MIT.EDUraeburn', 2, 16, + ('password', b'ATHENA.MIT.EDUraeburn', 2, 16, '01dbee7f4a9e243e988b62c73cda935d'), - ('password', 'ATHENA.MIT.EDUraeburn', 2, 32, + ('password', b'ATHENA.MIT.EDUraeburn', 2, 32, ('01dbee7f4a9e243e9' '88b62c73cda935da05' '378b93244ec8f48a99' 'e61ad799d86')), - ('password', 'ATHENA.MIT.EDUraeburn', 1200, 32, + ('password', b'ATHENA.MIT.EDUraeburn', 1200, 32, ('5c08eb61fdf71e' '4e4ec3cf6ba1f55' '12ba7e52ddbc5e51' '42f708a31e2e62b1e13')), - ('X' * 64, 'pass phrase equals block size', 1200, 32, + ('X' * 64, b'pass phrase equals block size', 1200, 32, ('139c30c0966bc32ba' '55fdbf212530ac9c5' 'ec59f1a452f5cc9ad' '940fea0598ed1')), - ('X' * 65, 'pass phrase exceeds block size', 1200, 32, + ('X' * 65, b'pass phrase exceeds block size', 1200, 32, ('9ccad6d468770cd' '51b10e6a68721be6' '11a8b4d282601db3' -- cgit v1.2.3 From 7187f1b9d43ec2ef5db34819047dc4c1a6b3da3e Mon Sep 17 00:00:00 2001 From: BonfaceKilz Date: Sun, 31 Jan 2021 19:44:51 +0300 Subject: Update sql query in test * wqflask/tests/unit/wqflask/api/test_gen_menu.py (test_build_datasets_with_type_mrna): Update sql query to fix failing test --- wqflask/tests/unit/wqflask/api/test_gen_menu.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/unit/wqflask/api/test_gen_menu.py b/wqflask/tests/unit/wqflask/api/test_gen_menu.py index 84898bd1..cc666f0c 100644 --- a/wqflask/tests/unit/wqflask/api/test_gen_menu.py +++ b/wqflask/tests/unit/wqflask/api/test_gen_menu.py @@ -247,7 +247,7 @@ class TestGenMenu(unittest.TestCase): "ProbeSetFreeze.ProbeFreezeId = ProbeFreeze.Id and " + "Tissue.Name = 'mRNA' AND ProbeFreeze.TissueId = " + "Tissue.Id and ProbeFreeze.InbredSetId = InbredSet.Id " + - "ORDER BY ProbeSetFreeze.CreateTime DESC") + "ORDER BY ProbeSetFreeze.OrderList DESC") @mock.patch('wqflask.api.gen_menu.build_datasets') @mock.patch('wqflask.api.gen_menu.g') -- cgit v1.2.3 From c1d775162c2a657f9e8001914cc216cd70460371 Mon Sep 17 00:00:00 2001 From: zsloan Date: Thu, 18 Feb 2021 21:36:28 +0000 Subject: Patched utility.authentication_tools.g as TestUserSession because otherwise the str.encode failed on the mock.Mock() object, and this also seems consistent with the way it's done in a later method --- wqflask/tests/unit/utility/test_authentication_tools.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/unit/utility/test_authentication_tools.py b/wqflask/tests/unit/utility/test_authentication_tools.py index 5c391be5..6d817f5e 100644 --- a/wqflask/tests/unit/utility/test_authentication_tools.py +++ b/wqflask/tests/unit/utility/test_authentication_tools.py @@ -5,7 +5,6 @@ from unittest import mock from utility.authentication_tools import check_resource_availability from utility.authentication_tools import add_new_resource - class TestResponse: """Mock Test Response after a request""" @property @@ -38,7 +37,7 @@ class TestCheckResourceAvailability(unittest.TestCase): """Test methods related to checking the resource availability""" @mock.patch('utility.authentication_tools.add_new_resource') @mock.patch('utility.authentication_tools.Redis') - @mock.patch('utility.authentication_tools.g', mock.Mock()) + @mock.patch('utility.authentication_tools.g', TestUserSession()) @mock.patch('utility.authentication_tools.get_resource_id') def test_check_resource_availability_default_mask( self, @@ -46,6 +45,7 @@ class TestCheckResourceAvailability(unittest.TestCase): redis_mock, add_new_resource_mock): """Test the resource availability with default mask""" + resource_id_mock.return_value = 1 redis_mock.smembers.return_value = [] test_dataset = mock.MagicMock() @@ -64,7 +64,7 @@ class TestCheckResourceAvailability(unittest.TestCase): redis_mock, add_new_resource_mock, requests_mock): - """Test the resource availability with default mask""" + """Test the resource availability with non-default mask""" resource_id_mock.return_value = 1 redis_mock.smembers.return_value = [] add_new_resource_mock.return_value = {"default_mask": 2} -- cgit v1.2.3 From e55861d6ced9a5c746a8e28c9a9c067e3927275a Mon Sep 17 00:00:00 2001 From: zsloan Date: Thu, 18 Feb 2021 21:47:39 +0000 Subject: Fixed test_run_mapping.py to make export_mapping_results test work correctly --- wqflask/tests/unit/wqflask/marker_regression/test_run_mapping.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/unit/wqflask/marker_regression/test_run_mapping.py b/wqflask/tests/unit/wqflask/marker_regression/test_run_mapping.py index 4129cc0c..a29d8cfb 100644 --- a/wqflask/tests/unit/wqflask/marker_regression/test_run_mapping.py +++ b/wqflask/tests/unit/wqflask/marker_regression/test_run_mapping.py @@ -180,14 +180,19 @@ class TestRunMapping(unittest.TestCase): with mock.patch("wqflask.marker_regression.run_mapping.datetime.datetime", new=datetime_mock): export_mapping_results(dataset=self.dataset, trait=self.trait, markers=markers, - results_path="~/results", mapping_scale="physic", score_type="-log(p)") + results_path="~/results", mapping_scale="physic", score_type="-log(p)", + transform="qnorm", covariates="Dataset1:Trait1,Dataset2:Trait2", n_samples="100") write_calls = [ mock.call('Time/Date: 09/01/19 / 10:12:12\n'), mock.call('Population: Human GP1_\n'), mock.call( 'Data Set: dataser_1\n'), + mock.call('N Samples: 100\n'), mock.call('Transform - Quantile Normalized\n'), mock.call('Gene Symbol: IGFI\n'), mock.call( 'Location: X1 @ 123313 Mb\n'), + mock.call('Cofactors (dataset - trait):\n'), + mock.call('Trait1 - Dataset1\n'), + mock.call('Trait2 - Dataset2\n'), mock.call('\n'), mock.call('Name,Chr,'), mock.call('Mb,-log(p)'), mock.call('Cm,-log(p)'), mock.call(',Additive'), mock.call(',Dominance'), -- cgit v1.2.3 From cb039b3e7e8a3a260edc80b0de79fc27af795cf0 Mon Sep 17 00:00:00 2001 From: zsloan Date: Thu, 18 Feb 2021 21:58:58 +0000 Subject: Fixed TestCheckResourceAvailability to make it work after realizing that Redis.smembers apparently returns values as bytes --- wqflask/tests/unit/utility/test_authentication_tools.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/unit/utility/test_authentication_tools.py b/wqflask/tests/unit/utility/test_authentication_tools.py index 6d817f5e..fff5fd8f 100644 --- a/wqflask/tests/unit/utility/test_authentication_tools.py +++ b/wqflask/tests/unit/utility/test_authentication_tools.py @@ -89,7 +89,7 @@ class TestCheckResourceAvailability(unittest.TestCase): requests_mock): """Test the resource availability if the user is the super user""" resource_id_mock.return_value = 1 - redis_mock.smembers.return_value = ["Jane"] + redis_mock.smembers.return_value = [b"Jane"] add_new_resource_mock.return_value = {"default_mask": 2} requests_mock.return_value = TestResponse() test_dataset = mock.MagicMock() -- cgit v1.2.3 From 4817d78b22b899b9beb3fd3a99a10d6cbcee22d6 Mon Sep 17 00:00:00 2001 From: zsloan Date: Thu, 18 Feb 2021 22:05:43 +0000 Subject: Fixed test_gen_menu to reflect updated query --- wqflask/tests/unit/wqflask/api/test_gen_menu.py | 7 ++++--- wqflask/wqflask/api/gen_menu.py | 2 +- 2 files changed, 5 insertions(+), 4 deletions(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/unit/wqflask/api/test_gen_menu.py b/wqflask/tests/unit/wqflask/api/test_gen_menu.py index cc666f0c..57eb1650 100644 --- a/wqflask/tests/unit/wqflask/api/test_gen_menu.py +++ b/wqflask/tests/unit/wqflask/api/test_gen_menu.py @@ -244,10 +244,11 @@ class TestGenMenu(unittest.TestCase): "ProbeFreeze, InbredSet, Tissue, Species WHERE " + "Species.Name = 'Mouse' AND Species.Id = " + "InbredSet.SpeciesId AND InbredSet.Name = 'HLC' AND " + - "ProbeSetFreeze.ProbeFreezeId = ProbeFreeze.Id and " + + "ProbeSetFreeze.ProbeFreezeId = ProbeFreeze.Id AND " + "Tissue.Name = 'mRNA' AND ProbeFreeze.TissueId = " + - "Tissue.Id and ProbeFreeze.InbredSetId = InbredSet.Id " + - "ORDER BY ProbeSetFreeze.OrderList DESC") + "Tissue.Id AND ProbeFreeze.InbredSetId = InbredSet.Id AND " + + "ProbeSetFreeze.public > 0 " + + "ORDER BY -ProbeSetFreeze.OrderList DESC, ProbeSetFreeze.CreateTime DESC") @mock.patch('wqflask.api.gen_menu.build_datasets') @mock.patch('wqflask.api.gen_menu.g') diff --git a/wqflask/wqflask/api/gen_menu.py b/wqflask/wqflask/api/gen_menu.py index 4ce19fdb..18afc5ad 100644 --- a/wqflask/wqflask/api/gen_menu.py +++ b/wqflask/wqflask/api/gen_menu.py @@ -207,7 +207,7 @@ def build_datasets(species, group, type_name): "InbredSet.SpeciesId AND InbredSet.Name = '{1}' " "AND ProbeSetFreeze.ProbeFreezeId = ProbeFreeze.Id " "AND Tissue.Name = '{2}' AND ProbeFreeze.TissueId = " - "Tissue.Id and ProbeFreeze.InbredSetId = InbredSet.Id " + "Tissue.Id AND ProbeFreeze.InbredSetId = InbredSet.Id " "AND ProbeSetFreeze.public > 0 " "ORDER BY -ProbeSetFreeze.OrderList DESC, ProbeSetFreeze.CreateTime DESC").format(species, group, type_name)).fetchall() -- cgit v1.2.3 From 8ca8eb18ed8aa35177008bb92d805b9d603aec66 Mon Sep 17 00:00:00 2001 From: zsloan Date: Tue, 16 Mar 2021 19:12:48 +0000 Subject: Fixed test_check_resource_availability_of_super_user to account for user_id being returned as bytes instead of a str --- wqflask/tests/unit/utility/test_authentication_tools.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'wqflask/tests') diff --git a/wqflask/tests/unit/utility/test_authentication_tools.py b/wqflask/tests/unit/utility/test_authentication_tools.py index fff5fd8f..42dcae88 100644 --- a/wqflask/tests/unit/utility/test_authentication_tools.py +++ b/wqflask/tests/unit/utility/test_authentication_tools.py @@ -18,7 +18,7 @@ class TestUser: @property def user_id(self): """Mockes user id. Used in Flask.g.user_session.user_id""" - return "Jane" + return b"Jane" class TestUserSession: -- cgit v1.2.3