Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cleanup dependencies #3597

Merged
merged 6 commits into from
Dec 4, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion aiida/backends/tests/cmdline/commands/test_node.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ def test_node_tree(self):

def test_node_tree_printer(self):
"""Test the `NodeTreePrinter` utility."""
from aiida.cmdline.commands.cmd_node import NodeTreePrinter
from aiida.cmdline.utils.ascii_vis import NodeTreePrinter

with Capturing():
NodeTreePrinter.print_node_tree(self.node, max_depth=1)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,24 +8,19 @@
# For further information please visit http://www.aiida.net #
###########################################################################
"""Tests for the configuration migration functionality."""

import io
import os
import uuid
import unittest

try:
from unittest import mock
except ImportError:
import mock
from unittest import TestCase
from unittest.mock import patch

from aiida.common import json

from aiida.manage.configuration.migrations.utils import check_and_migrate_config
from aiida.manage.configuration.migrations.migrations import _MIGRATION_LOOKUP


class TestConfigMigration(unittest.TestCase):
class TestConfigMigration(TestCase):
"""Tests for the configuration migration functionality."""

@staticmethod
Expand All @@ -43,7 +38,7 @@ def setUp(self):
def test_check_and_migrate(self):
"""Test the full config migration."""
config_initial = self.load_config_sample('input/0.json')
with mock.patch.object(uuid, 'uuid4', return_value=uuid.UUID(hex='0' * 32)):
with patch.object(uuid, 'uuid4', return_value=uuid.UUID(hex='0' * 32)):
config_migrated = check_and_migrate_config(config_initial)
config_reference = self.load_config_sample('reference/final.json')
self.assertEqual(config_migrated, config_reference)
Expand All @@ -59,7 +54,7 @@ def test_1_2_migration(self):
"""Test the step between config versions 1 and 2."""
config_initial = self.load_config_sample('input/1.json')
config_reference = self.load_config_sample('reference/2.json')
with mock.patch.object(uuid, 'uuid4', return_value=uuid.UUID(hex='0' * 32)):
with patch.object(uuid, 'uuid4', return_value=uuid.UUID(hex='0' * 32)):
config_migrated = _MIGRATION_LOOKUP[1].apply(config_initial)
self.assertEqual(config_migrated, config_reference)

Expand Down
11 changes: 5 additions & 6 deletions aiida/backends/tests/manage/external/test_postgres.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,8 @@
# For further information please visit http://www.aiida.net #
###########################################################################
"""Unit tests for postgres database maintenance functionality"""

import unittest
import mock
from unittest import TestCase
from unittest.mock import patch

from aiida.manage.external.postgres import Postgres

Expand All @@ -20,7 +19,7 @@ def _try_connect_always_fail(**kwargs): # pylint: disable=unused-argument
return False


class PostgresTest(unittest.TestCase):
class PostgresTest(TestCase):
"""Test the public API provided by the `Postgres` class"""

def setUp(self):
Expand Down Expand Up @@ -57,8 +56,8 @@ def correct_setup(interactive, dbinfo): # pylint: disable=unused-argument
setup_success = postgres.determine_setup()
self.assertTrue(setup_success)

@mock.patch('aiida.manage.external.pgsu._try_connect_psycopg', new=_try_connect_always_fail)
@mock.patch('aiida.manage.external.pgsu._try_subcmd')
@patch('aiida.manage.external.pgsu._try_connect_psycopg', new=_try_connect_always_fail)
@patch('aiida.manage.external.pgsu._try_subcmd')
def test_fallback_on_subcmd(self, try_subcmd):
"""Ensure that accessing postgres via subcommand is tried if psycopg does not work."""
self._setup_postgres()
Expand Down
6 changes: 1 addition & 5 deletions aiida/backends/tests/plugins/test_factories.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,7 @@
# For further information please visit http://www.aiida.net #
###########################################################################
"""Tests for the :py:mod:`~aiida.plugins.factories` module."""

try:
from unittest.mock import patch
except ImportError:
from mock import patch
from unittest.mock import patch

from aiida.backends.testbase import AiidaTestCase
from aiida.common.exceptions import InvalidEntryPointTypeError
Expand Down
58 changes: 38 additions & 20 deletions aiida/backends/tests/test_dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -2206,9 +2206,7 @@ def test_1(self):

struct = StructureData(pymatgen_structure=pymatgen_struct)

# Testing pymatgen Structure -> StructureData -> pymatgen Structure
# roundtrip.

# Testing pymatgen Structure -> StructureData -> pymatgen Structure roundtrip.
pymatgen_struct_roundtrip = struct.get_pymatgen_structure()
dict1 = pymatgen_struct.as_dict()
dict2 = pymatgen_struct_roundtrip.as_dict()
Expand All @@ -2218,7 +2216,22 @@ def test_1(self):
for i in dict2['sites']:
i['abc'] = [round(j, 2) for j in i['abc']]

self.assertEquals(dict1, dict2)
def recursively_compare_values(left, right):
from collections.abc import Mapping
from numpy import testing

if isinstance(left, Mapping):
for key, value in left.items():
recursively_compare_values(value, right[key])
elif isinstance(left, (list, tuple)):
for val1, val2 in zip(left, right):
recursively_compare_values(val1, val2)
elif isinstance(left, float):
testing.assert_almost_equal(left, right)
else:
assert left == right, '{} is not {}'.format(value, right)

recursively_compare_values(dict1, dict2)

@unittest.skipIf(not has_pymatgen(), 'Unable to import pymatgen')
def test_2(self):
Expand Down Expand Up @@ -2257,13 +2270,13 @@ def test_partial_occ_and_spin(self):
"""
import pymatgen

Fe_spin_up = pymatgen.structure.Specie('Fe', 0, properties={'spin': 1})
Mn_spin_up = pymatgen.structure.Specie('Mn', 0, properties={'spin': 1})
Fe_spin_down = pymatgen.structure.Specie('Fe', 0, properties={'spin': -1})
Mn_spin_down = pymatgen.structure.Specie('Mn', 0, properties={'spin': -1})
Fe_spin_up = pymatgen.Specie('Fe', 0, properties={'spin': 1})
Mn_spin_up = pymatgen.Specie('Mn', 0, properties={'spin': 1})
Fe_spin_down = pymatgen.Specie('Fe', 0, properties={'spin': -1})
Mn_spin_down = pymatgen.Specie('Mn', 0, properties={'spin': -1})
FeMn1 = pymatgen.Composition({Fe_spin_up: 0.5, Mn_spin_up: 0.5})
FeMn2 = pymatgen.Composition({Fe_spin_down: 0.5, Mn_spin_down: 0.5})
a = pymatgen.structure.Structure(
a = pymatgen.Structure(
lattice=[[4, 0, 0], [0, 4, 0], [0, 0, 4]], species=[FeMn1, FeMn2], coords=[[0, 0, 0], [0.5, 0.5, 0.5]])

with self.assertRaises(ValueError):
Expand All @@ -2272,7 +2285,7 @@ def test_partial_occ_and_spin(self):
# same, with vacancies
Fe1 = pymatgen.Composition({Fe_spin_up: 0.5})
Fe2 = pymatgen.Composition({Fe_spin_down: 0.5})
a = pymatgen.structure.Structure(
a = pymatgen.Structure(
lattice=[[4, 0, 0], [0, 4, 0], [0, 0, 4]], species=[Fe1, Fe2], coords=[[0, 0, 0], [0.5, 0.5, 0.5]])

with self.assertRaises(ValueError):
Expand All @@ -2286,10 +2299,10 @@ def test_multiple_kinds_partial_occupancies(self):
"""
import pymatgen

Mg1 = pymatgen.structure.Composition({'Mg': 0.50})
Mg2 = pymatgen.structure.Composition({'Mg': 0.25})
Mg1 = pymatgen.Composition({'Mg': 0.50})
Mg2 = pymatgen.Composition({'Mg': 0.25})

a = pymatgen.structure.Structure(
a = pymatgen.Structure(
lattice=[[4, 0, 0], [0, 4, 0], [0, 0, 4]], species=[Mg1, Mg2], coords=[[0, 0, 0], [0.5, 0.5, 0.5]])

structure = StructureData(pymatgen=a)
Expand All @@ -2302,10 +2315,10 @@ def test_multiple_kinds_alloy(self):
"""
import pymatgen

alloy_one = pymatgen.structure.Composition({'Mg': 0.25, 'Al': 0.75})
alloy_two = pymatgen.structure.Composition({'Mg': 0.45, 'Al': 0.55})
alloy_one = pymatgen.Composition({'Mg': 0.25, 'Al': 0.75})
alloy_two = pymatgen.Composition({'Mg': 0.45, 'Al': 0.55})

a = pymatgen.structure.Structure(
a = pymatgen.Structure(
lattice=[[4, 0, 0], [0, 4, 0], [0, 0, 4]],
species=[alloy_one, alloy_two],
coords=[[0, 0, 0], [0.5, 0.5, 0.5]])
Expand Down Expand Up @@ -2467,6 +2480,8 @@ def test_roundtrip_partial_occ(self):
Tests roundtrip StructureData -> pymatgen -> StructureData
(with partial occupancies).
"""
from numpy import testing

a = StructureData(cell=[[4.0, 0.0, 0.0], [-2., 3.5, 0.0], [0.0, 0.0, 16.]])
a.append_atom(position=(0.0, 0.0, 13.5), symbols='Mn')
a.append_atom(position=(0.0, 0.0, 2.6), symbols='Mn')
Expand Down Expand Up @@ -2522,10 +2537,13 @@ def test_roundtrip_partial_occ(self):
self.assertEquals(c.get_site_kindnames(),
['Mn', 'Mn', 'Mn', 'Mn', 'MnX', 'MnX', 'Si', 'Si', 'N', 'N', 'N', 'N'])
self.assertEquals(c.get_formula(), 'Mn4N4Si2{Mn0.80X0.20}2')
self.assertEquals([s.position for s in c.sites],
[(0.0, 0.0, 13.5), (0.0, 0.0, 2.6), (0.0, 0.0, 5.5), (0.0, 0.0, 11.), (2., 1., 12.),
(0.0, 2.2, 4.), (0.0, 2.2, 12.), (2., 1., 4.), (2., 1., 15.), (0.0, 2.2, 1.5),
(0.0, 2.2, 7.), (2., 1., 9.5)])
testing.assert_allclose(
[s.position for s in c.sites],
[
(0.0, 0.0, 13.5), (0.0, 0.0, 2.6), (0.0, 0.0, 5.5), (0.0, 0.0, 11.), (2., 1., 12.), (0.0, 2.2, 4.),
(0.0, 2.2, 12.), (2., 1., 4.), (2., 1., 15.), (0.0, 2.2, 1.5), (0.0, 2.2, 7.), (2., 1., 9.5)
]
)

@unittest.skipIf(not has_pymatgen(), 'Unable to import pymatgen')
def test_partial_occ_and_spin(self):
Expand Down
51 changes: 2 additions & 49 deletions aiida/cmdline/commands/cmd_node.py
Original file line number Diff line number Diff line change
Expand Up @@ -224,9 +224,11 @@ def extras(nodes, keys, fmt, identifier, raw):
@arguments.NODES()
@click.option('-d', '--depth', 'depth', default=1, help='Show children of nodes up to given depth')
@with_dbenv()
@decorators.deprecated_command('This command will be removed in `aiida-core==2.0.0`.')
def tree(nodes, depth):
"""Show a tree of nodes starting from a given node."""
from aiida.common import LinkType
from aiida.cmdline.utils.ascii_vis import NodeTreePrinter

for node in nodes:
NodeTreePrinter.print_node_tree(node, depth, tuple(LinkType.__members__.values()))
Expand All @@ -235,55 +237,6 @@ def tree(nodes, depth):
echo.echo('')


class NodeTreePrinter:
"""Utility functions for printing node trees."""

@classmethod
def print_node_tree(cls, node, max_depth, follow_links=()):
"""Top-level function for printing node tree."""
from ete3 import Tree
from aiida.cmdline.utils.common import get_node_summary

echo.echo(get_node_summary(node))

tree_string = '({});'.format(cls._build_tree(node, max_depth=max_depth, follow_links=follow_links))
tmp = Tree(tree_string, format=1)
echo.echo(tmp.get_ascii(show_internal=True))

@staticmethod
def _ctime(link_triple):
return link_triple.node.ctime

@classmethod
def _build_tree(cls, node, show_pk=True, max_depth=None, follow_links=(), depth=0):
"""Return string with tree."""
if max_depth is not None and depth > max_depth:
return None

children = []
for entry in sorted(node.get_outgoing(link_type=follow_links).all(), key=cls._ctime):
child_str = cls._build_tree(
entry.node, show_pk, follow_links=follow_links, max_depth=max_depth, depth=depth + 1
)
if child_str:
children.append(child_str)

out_values = []
if children:
out_values.append('(')
out_values.append(', '.join(children))
out_values.append(')')

lab = node.__class__.__name__

if show_pk:
lab += ' [{}]'.format(node.pk)

out_values.append(lab)

return ''.join(out_values)


@verdi_node.command('delete')
@arguments.NODES('nodes', required=True)
@options.VERBOSE()
Expand Down
Loading