Skip to content

List users #270

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

Merged
merged 9 commits into from
Apr 22, 2021
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
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,13 @@ how a consumer would use the library (e.g. adding unit tests, updating documenta

## Unreleased

### Added

- New command `code42 users list` with options:
- `--org-uid` filters on org membership.
- `--role-name` filters on users having a particular role.
- `--active` and `--inactive` filter on user status.

### Fixed

- Bug where some CSV outputs on Windows would have an extra newline between the rows.
Expand Down
73 changes: 73 additions & 0 deletions src/code42cli/cmds/users.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import click
from pandas import DataFrame

from code42cli.click_ext.groups import OrderedGroup
from code42cli.click_ext.options import incompatible_with
from code42cli.errors import Code42CLIError
from code42cli.options import format_option
from code42cli.options import sdk_options
from code42cli.output_formats import DataFrameOutputFormatter


@click.group(cls=OrderedGroup)
@sdk_options(hidden=True)
def users(state):
"""Manage users within your Code42 environment."""
pass


org_uid_option = click.option(
"--org-uid",
help="Limit users to only those in the organization you specify. Note that child orgs are included.",
)
role_name_option = click.option(
"--role-name", help="Limit results to only users having the specified role.",
)
active_option = click.option(
"--active", is_flag=True, help="Limits results to only active users.", default=None,
)
inactive_option = click.option(
"--inactive",
is_flag=True,
help="Limits results to only deactivated users.",
cls=incompatible_with("active"),
)


@users.command(name="list")
@org_uid_option
@role_name_option
@active_option
@inactive_option
@format_option
@sdk_options()
def list_users(state, org_uid, role_name, active, inactive, format):
"""List users in your Code42 environment."""
if inactive:
active = False
role_id = _get_role_id(state.sdk, role_name) if role_name else None
df = _get_users_dataframe(state.sdk, org_uid, role_id, active)
if df.empty:
click.echo("No results found.")
else:
formatter = DataFrameOutputFormatter(format)
formatter.echo_formatted_dataframe(df)


def _get_role_id(sdk, role_name):
try:
roles_dataframe = DataFrame.from_records(
sdk.users.get_available_roles().data, index="roleName"
)
role_result = roles_dataframe.at[role_name, "roleId"]
return str(role_result) # extract the role ID from the series
except KeyError:
raise Code42CLIError(f"Role with name {role_name} not found.")


def _get_users_dataframe(sdk, org_uid, role_id, active):
users_generator = sdk.users.get_all(active=active, org_uid=org_uid, role_id=role_id)
users_list = []
for page in users_generator:
users_list.extend(page["users"])
return DataFrame.from_records(users_list)
2 changes: 2 additions & 0 deletions src/code42cli/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
from code42cli.cmds.legal_hold import legal_hold
from code42cli.cmds.profile import profile
from code42cli.cmds.securitydata import security_data
from code42cli.cmds.users import users
from code42cli.options import sdk_options

BANNER = """\b
Expand Down Expand Up @@ -80,5 +81,6 @@ def cli(state, python):
cli.add_command(legal_hold)
cli.add_command(profile)
cli.add_command(devices)
cli.add_command(users)
cli.add_command(audit_logs)
cli.add_command(cases)
110 changes: 110 additions & 0 deletions tests/cmds/test_users.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
import json

import pytest
from py42.response import Py42Response
from requests import Response

from code42cli.main import cli

TEST_ROLE_RETURN_DATA = {
"data": [{"roleName": "Customer Cloud Admin", "roleId": "1234543"}]
}

TEST_USERS_RESPONSE = {
"users": [
{
"userId": 1234,
"userUid": "997962681513153325",
"status": "Active",
"username": "[email protected]",
"creationDate": "2021-03-12T20:07:40.898Z",
"modificationDate": "2021-03-12T20:07:40.938Z",
}
]
}


def _create_py42_response(mocker, text):
response = mocker.MagicMock(spec=Response)
response.text = text
response._content_consumed = mocker.MagicMock()
response.status_code = 200
return Py42Response(response)


def get_all_users_generator():
yield TEST_USERS_RESPONSE


@pytest.fixture
def get_available_roles_response(mocker):
return _create_py42_response(mocker, json.dumps(TEST_ROLE_RETURN_DATA))


@pytest.fixture
def get_all_users_success(cli_state):
cli_state.sdk.users.get_all.return_value = get_all_users_generator()


@pytest.fixture
def get_available_roles_success(cli_state, get_available_roles_response):
cli_state.sdk.users.get_available_roles.return_value = get_available_roles_response


def test_list_outputs_appropriate_columns(runner, cli_state, get_all_users_success):
result = runner.invoke(cli, ["users", "list"], obj=cli_state)
assert "userId" in result.output
assert "userUid" in result.output
assert "status" in result.output
assert "username" in result.output
assert "creationDate" in result.output
assert "modificationDate" in result.output


def test_list_users_calls_users_get_all_with_expected_role_id(
runner, cli_state, get_available_roles_success, get_all_users_success
):
ROLE_NAME = "Customer Cloud Admin"
runner.invoke(cli, ["users", "list", "--role-name", ROLE_NAME], obj=cli_state)
cli_state.sdk.users.get_all.assert_called_once_with(
active=None, org_uid=None, role_id="1234543"
)


def test_list_users_calls_get_all_users_with_correct_parameters(
runner, cli_state, get_all_users_success
):
org_uid = "TEST_ORG_UID"
runner.invoke(
cli, ["users", "list", "--org-uid", org_uid, "--active"], obj=cli_state
)
cli_state.sdk.users.get_all.assert_called_once_with(
active=True, org_uid=org_uid, role_id=None
)


def test_list_users_when_given_inactive_uses_active_equals_false(
runner, cli_state, get_available_roles_success, get_all_users_success
):
runner.invoke(cli, ["users", "list", "--inactive"], obj=cli_state)
cli_state.sdk.users.get_all.assert_called_once_with(
active=False, org_uid=None, role_id=None
)


def test_list_users_when_given_active_and_inactive_raises_error(
runner, cli_state, get_available_roles_success, get_all_users_success
):
result = runner.invoke(
cli, ["users", "list", "--active", "--inactive"], obj=cli_state
)
assert "Error: --inactive can't be used with: --active" in result.output


def test_list_users_when_given_excluding_active_and_inactive_uses_active_equals_none(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

technically don't need the word _given_ in the test signature (not a blocker though)

runner, cli_state, get_available_roles_success, get_all_users_success
):
runner.invoke(cli, ["users", "list"], obj=cli_state)
cli_state.sdk.users.get_all.assert_called_once_with(
active=None, org_uid=None, role_id=None
)