def su_check_facebook_channels(user): data = request.args if not {'channel', 'account'}.intersection(set(data)): return jsonify(error='Missing channel or account arg (name or id)') from solariat_bottle.scripts.analyze_facebook_channels_config import check_accounts, \ check_service_channels if 'account' in data: from solariat_bottle.db.account import Account items = Account.objects(name=data['account'])[:] items.extend(Account.objects(id=data['account'])[:]) verify_fn = check_accounts elif 'channel' in data: from solariat_bottle.db.channel.base import Channel items = Channel.objects(include_safe_deletes=True, id=data['channel'])[:] items.extend(Channel.objects(title=data['channel'])[:]) verify_fn = check_service_channels else: return jsonify(error='account or channel arg expected') try: result = verify_fn( items, include_safe_deletes=data.get('x', data.get('include_safe_deletes', False)), show_sensitive_info=data.get('s', data.get('show_sensitive_info', False))) except Exception as e: return jsonify({'ok': False, 'error': str(e)}) else: return jsonify(result=result)
def setUp(self): MainCase.setUp(self) self.account = Account(name="Solariat Test") self.account.save() self.user.account = self.account self.user.save() self.account.add_perm(self.user) self.channel.account = self.account self.channel.save() self._create_smart_tag(self.channel, 'laptop', status='Active'),
class PredictorExpression(MainCase): def setUp(self): MainCase.setUp(self) self.account = Account(name="Solariat Test") self.account.save() self.user.account = self.account self.user.save() self.account.add_perm(self.user) def test_upsert_feedback(self): predictor = mock.create_autospec(BasePredictor) predictor.name = "Social Media Predictor" entities_registry = EntitiesRegistry() try: predictor.upsert_feedback() except: self.assertTrue(False) # mockup upsert_feedback method expression = 'collect(InfomartEvent)' expression_data = entities_registry.generate_expression_context( predictor, expression) self.assertEqual(expression_data['expression'], u'collect(predictor, from_dt, to_dt, InfomartEvent)') _from_dt = datetime.datetime.fromtimestamp( int(1466964000)).strftime('%m/%d/%Y') _to_dt = datetime.datetime.fromtimestamp( int(1467050400)).strftime('%m/%d/%Y') expression_data['context']['from_dt'], expression_data['context'][ 'to_dt'] = parse_date_interval(_from_dt, _to_dt) parser = BaseParser(expression_data['expression'], entities_registry.get_all_entries()) parser.evaluate(expression_data['context']) expression = 'int(123.3333)' expression_data = entities_registry.generate_expression_context( predictor, expression) self.assertEqual(expression_data['expression'], u'int(123.3333)') parser = BaseParser(expression_data['expression'], entities_registry.get_all_entries()) result = parser.evaluate(expression_data['context']) self.assertEqual(result, 123) expression = 'str(10)' expression_data = entities_registry.generate_expression_context( predictor, expression) parser = BaseParser(expression_data['expression'], entities_registry.get_all_entries()) result = parser.evaluate(expression_data['context']) self.assertTrue(isinstance(result, basestring))
def parse_accounts(bot_options): from solariat_bottle.db.account import Account only_accounts = [] if bot_options.only_accounts: only_ids = bot_options.only_accounts.split(',') only_accounts = Account.objects(id__in=only_ids)[:] exclude_accounts = [] if bot_options.exclude_accounts: exclude_ids = bot_options.exclude_accounts.split(',') exclude_accounts = Account.objects(id__in=exclude_ids)[:] return { "only_accounts": only_accounts, "exclude_accounts": exclude_accounts }
def tearDown(self): if get_var('TEST_STAT_RESET', False): to_date = now() from_date = to_date - timedelta(days=90) exceptions = get_var('EXCEPTED_RESET_CASES', []) test_name = self.__class__.__name__ + '.' + self._testMethodName if test_name not in exceptions: try: for account in Account.objects(): do_it(test_mode=True, raise_on_diffs=True, account_name=account.name, to_date=to_date, from_date=from_date) except Exception, ex: self.fail(ex)
def account_email_data(user): sender = _get_sender() data = { 'from_address': '%s <%s>' % (sender[0], sender[1]), 'accounts': [{ 'id': str(ac.id), 'value': ac.name } for ac in Account.objects()], 'roles': user.accessible_roles, 'templates': EMAIL_TEMPLATES, } return jsonify(ok=True, data=data)
class AccountStats(MainCase, SmartTagsTestHelper): def setUp(self): MainCase.setUp(self) self.account = Account(name="Solariat Test") self.account.save() self.user.account = self.account self.user.save() self.account.add_perm(self.user) self.channel.account = self.account self.channel.save() self._create_smart_tag(self.channel, 'laptop', status='Active'), def test_single_post_added(self): """ Count of posts for account should increase by one when a post is added. This is for issue #2007 https://github.com/solariat/tango/issues/2007 Previously when smart tag channel was in the account number of posts was aggregated in it too. """ content = '@screen_name I need a laptop' self._create_db_post(content) self._create_smart_tag(self.channel, 'tag1', status='Active'), # just one post is added self.assertEqual( account_stats(self.account, self.user).get('number_of_posts'), 1) def test_account_stats(self): """Account stats should not sum up stats of deleted (archived) channels""" content = '@screen_name I need a laptop' channels_num = 4 archived_channels_num = 3 # should be <= channels_num posts_per_channel = 1 channels = [ Channel.objects.create_by_user(self.user, account=self.account, title='Channel#%d' % _) for _ in range(channels_num) ] posts = [ self._create_db_post(content=content + " #%d" % _, channel=channel) for channel in channels for _ in range(posts_per_channel) ] self.assertEqual( account_stats(self.account, self.user).get('number_of_posts'), channels_num * posts_per_channel) from solariat_bottle.commands.configure import DeleteChannel DeleteChannel(channels=channels[:archived_channels_num]).update_state( self.user) self.assertEqual( account_stats(self.account, self.user).get('number_of_posts'), (channels_num - archived_channels_num) * posts_per_channel) self.assertEqual( all_account_stats(self.account, self.user).get('number_of_posts'), channels_num * posts_per_channel)
class AccountTest(MainCase): def setUp(self): MainCase.setUp(self) self.account = Account(name="Solariat Test") self.account.save() self.user.account = self.account self.user.save() self.account.add_perm(self.user) def test_angel_account_name_format(self): '''Assert that Angel integration account name types are allowed by the system''' # # Removed in #3885 # invalid_account_name = "Un$upported Acc*nt Name!" # with self.assertRaises(AppException): # Account.objects.create_by_user(self.user, name=invalid_account_name) account_name = "Ivana_BBBW(0a140220-04-13118333b6b-64c24491-6e9)" account = Account.objects.create_by_user(self.user, name=account_name, account_type="Angel") self.assertTrue(account is not None) self.assertEqual(account.name, account_name) def test_no_account_or_team(self): user = self._create_db_user(email='*****@*****.**', password='******', roles=[AGENT]) self.assertEqual(user.team, []) def test_team(self): self.assertEqual(self.user.team, []) x = self._create_db_user(email='*****@*****.**', password='******', account=self.account, roles=[AGENT]) self.assertEqual([t.email for t in self.user.team], [x.email]) y = self._create_db_user(email='*****@*****.**', password='******', account=self.account, roles=[AGENT]) self.assertEqual(sorted([t.email for t in self.user.team]), sorted([x.email, y.email])) def test_admin(self): self.assertEqual(self.user.is_admin, True) self.assertEqual([u.email for u in self.account.admins], [self.user.email]) def test_integration_accounts(self): angel = Account.objects.create_by_user(self.user, name="Test-Angel", account_type="Angel") self.assertTrue(angel is not None) self.assertTrue(angel.name == 'Test-Angel') self.assertTrue(angel.account_type == "Angel") def test_outbound_channels(self): from solariat_bottle.db.channel.twitter import EnterpriseTwitterChannel ChannelCls = EnterpriseTwitterChannel self.assertEqual(self.user.get_outbound_channel("Twitter"), None) # Set for account and check defaults outbound_1 = ChannelCls.objects.create_by_user( self.user, title='Outbound1', type='twitter', intention_types=SA_TYPES) self.account.outbound_channels[outbound_1.platform] = outbound_1.id self.account.save() self.assertEqual( self.user.get_outbound_channel("Twitter").id, outbound_1.id) outbound_2 = ChannelCls.objects.create_by_user( self.user, title='Outbound1', type='twitter', intention_types=SA_TYPES) self.user.outbound_channels[outbound_2.platform] = outbound_2.id self.user.save() self.assertEqual( self.user.get_outbound_channel("Twitter").id, outbound_2.id) def test_add_del_perm(self): # test user should be added to account when permission is added user1 = self._create_db_user(email="*****@*****.**", roles=[AGENT]) user2 = self._create_db_user(email="*****@*****.**", roles=[ADMIN]) users = list(self.account.get_users()) self.account.add_perm(user1) self.assertTrue(self.account.can_view(user1)) self.account.add_perm(user2) self.assertTrue(self.account.can_view(user2)) self.assertTrue(self.account.can_edit(user2)) self.assertEquals(len(users) + 2, len(self.account.get_users())) # test user deleted from account self.account.del_perm(user1) # We should only have 1 user left self.assertEquals(len(users) + 1, len(self.account.get_users())) def test_crud_acl(self): n_accounts = len(self.user.accounts) # Create a new account by the user expiry_date = dt.datetime.now() + dt.timedelta(days=1) account = Account.objects.create_by_user(self.user, name="TestAccountCRUD", end_date=expiry_date) acc_id = str(account.id) self.assertTrue(account is not None) self.assertEqual(account.name, "TestAccountCRUD") self.assertTrue(account.has_perm(self.user)) self.assertEqual(len(self.user.accounts), n_accounts + 1) self.assertEqual(account.end_date, expiry_date) # Retrieve it by the user retrieved_account = Account.objects.get_by_user(self.user, id=acc_id) self.assertEqual(account, retrieved_account) # Delete the account new_user = self._create_db_user(email="*****@*****.**", roles=[ADMIN], account=account) channel = ServiceChannel.objects.create(title="TestChannel", account=account) group = Group.objects.create_by_user(new_user, "TestGroup", None, [str(self.user.id)], [], [str(channel.id)], [], []) self.assertTrue(new_user in account.get_users()) Account.objects.remove_by_user(self.user, acc_id) # The admin user should be also removed with self.assertRaises(User.DoesNotExist): User.objects.get(str(new_user.id)) with self.assertRaises(Group.DoesNotExist): Group.objects.get(str(group.id)) self.user.reload() self.assertEqual(len(self.user.accounts), n_accounts) self.assertTrue(acc_id not in self.user.accounts) with self.assertRaises(Account.DoesNotExist): account = Account.objects.get_by_user(self.user, id=acc_id) def test_common_cases(self): acct1 = Account(name='NewAccount1') acct2 = Account(name='NewAccount2') acct1.save() acct2.save() user1 = self._create_db_user(email="*****@*****.**", roles=[AGENT]) user2 = self._create_db_user(email="*****@*****.**", roles=[AGENT]) #Add both users to account with 'read' permission (default) acct1.add_user('*****@*****.**') acct1.add_user('*****@*****.**') current_users = [u.email for u in acct1.get_current_users()] self.assertEqual(set(current_users), set(['*****@*****.**', '*****@*****.**'])) user1.reload() user2.reload() #Users should have the acct1 as their current account for u in [user1, user2]: #accounts() lookup self.assertTrue(acct1.id in u.accounts) self.assertFalse(acct2.id in u.accounts) u.reload() #Current account was set to the first account users were added to self.assertTrue(u.current_account == u.account == acct1) #Total number of available accounts is 1 self.assertEqual(u.available_accounts.count(), 1) #Add users to another account for u in [user1, user2]: acct2.add_user(u, 'rw') #Current account should remain the previous set... u.reload() self.assertTrue(u.current_account == u.account == acct1) #...unless we change it u.current_account = acct2 u.reload() self.assertTrue(u.current_account == acct2) self.assertEqual(u.available_accounts.count(), 2) #Now acct1 should have 0 current users and 2 users with read access #acct2 2 current users 2 have write access self.assertEqual(len(acct1.get_all_users()), 2) self.assertTrue( acct1.get_current_users().count() == acct1.get_users().count() == 0 ) self.assertEqual(len(acct2.get_all_users()), 2) self.assertTrue( acct2.get_current_users().count() == acct2.get_users().count() == 2 ) #Remove user from their current account - superuser can do this acct2.del_user( user1) #Note: del_user deletes both 'rw' perms by default self.assertEqual(len(acct2.get_all_users()), 1) self.assertEqual(len(acct2.get_current_users()), 1) user1.reload() self.assertFalse(bool(user1.account)) # account is None #Now the acct2 should be not settable for user1 user1.current_account = acct2 user1.reload() self.assertFalse(bool(user1.account)) # still None user1.current_account = acct1 user1.reload() self.assertEqual(user1.account, acct1) def test_channels_are_being_filtered_by_account(self): accounts = [ Account.objects.create(name="Acct1"), Account.objects.create(name="Acct2") ] channels = [ Channel.objects.create_by_user(self.user, title='channel1'), Channel.objects.create_by_user(self.user, title='channel2') ] channels[0].account = accounts[0] channels[0].save() channels[1].account = accounts[1] channels[1].save() for a in accounts: a.add_user(self.user) #The current account is 'Solariat Test' so there should be no channels self.assertFalse(list(Channel.objects.find_by_user(self.user))) self.user.current_account = accounts[0] self.user.reload() # Now re-add permissions channels[0].add_perm(self.user) channels[1].add_perm(self.user) ch = list(Channel.objects.find_by_user(self.user)) self.assertEqual(len(ch), 1) self.assertEqual(ch[0].id, channels[0].id) self.user.current_account = accounts[1] self.user.reload() ch = list(Channel.objects.find_by_user(self.user)) self.assertEqual(len(ch), 1) self.assertEqual(ch[0].id, channels[1].id) def test_pricing_packages(self): params = {'name': 'TestAcctInternal'} account = Account.objects.create_by_user(self.user, **params) self.assertTrue(account is not None) self.assertEqual(account.account_type, 'Native') self.assertTrue(account.package is not None) self.assertEqual(account.package.name, 'Internal') params = { 'name': 'TestAcctPackage1', 'account_type': 'Native', 'package': 'Silver' } account = Account.objects.create_by_user(self.user, **params) self.assertTrue(account is not None) self.assertEqual(account.account_type, 'Native') self.assertTrue(account.package is not None) self.assertEqual(account.package.name, 'Silver') params = { 'name': 'TestAcctPackage2', 'account_type': 'Skunkworks', 'package': 'Bronze' } account = Account.objects.create_by_user(self.user, **params) self.assertTrue(account is not None) self.assertEqual(account.package.name, params['package']) self.assertEqual(account.account_type, params['account_type']) self.assertTrue(account.is_active) params = { 'name': 'TestAcctPackage3', 'account_type': 'Native', 'package': 'Foo' } self.assertRaises(AppException, Account.objects.create_by_user, self.user, **params) #today = dt.datetime.now() #yesterday = today - dt.timedelta(days=1) params = { 'name': 'TestAcctExpired', 'package': 'Trial', 'end_date': yesterday } account = Account.objects.create_by_user(self.user, **params) self.assertTrue(account is not None) self.assertFalse(account.is_active) def test_csm(self): '''Test the customer success manager field logic''' # Create an account, if the user is not staff no CSM should be set self.assertFalse(self.user.is_staff) account = Account.objects.create_by_user(self.user, name="TesAcctCSM") self.assertTrue(account.customer_success_manager is None) # Add the staff role to the user and try again, this time CSM should be altered self.user.user_roles.append(STAFF) #self.user.save() self.assertTrue(self.user.is_staff) account = Account.objects.create_by_user(self.user, name="TestAcctCSM2") self.assertTrue(account.customer_success_manager is not None) self.assertEqual(account.customer_success_manager, self.user) # Superusers should not be assigned as a CSM su = self._create_db_user(email="*****@*****.**", password="******", is_superuser=True) account = Account.objects.create_by_user(su, name="TestAcctSU") self.assertTrue(account.customer_success_manager is None) def test_empty_pricing_packages(self): '''Test that the proper pricing packages are created in the case that they don't exist''' Package.objects.coll.drop() account = Account.objects.create_by_user(self.user, name="TestAcctInternal") self.assertTrue(isinstance(account.package, Package)) self.assertEqual(account.package.name, 'Internal') def test_account_acl(self): '''Test Account ACL issues #3640, #3701''' # Super user creates an account su = self._create_db_user(is_superuser=True, email="*****@*****.**", password="******") account = Account.objects.create_by_user(su, name='TestAcctACL') acc_id = str(account.id) # Assign a staff user staff = self._create_db_user(email="*****@*****.**", password="******", roles=[STAFF], account=account) self.assertTrue(acc_id in staff.accounts) n_account = Account.objects.get_by_user(staff, acc_id) self.assertEqual(account, n_account) self.account.add_perm(staff) n_account = Account.objects.get_by_user(staff, id=str(self.account.id)) self.assertEqual(self.account, n_account) no_access_account = Account.objects.create_by_user(su, name='TestNoAccess') with self.assertRaises(AppException): Account.objects.get_by_user(staff, str(no_access_account.id)) with self.assertRaises(AppException): Account.objects.get_by_user(staff, name="TestNoAccess") staff_accounts = Account.objects.find_by_user(staff) self.assertEqual(staff_accounts.count(), 2) staff_accounts = Account.objects.find_by_user(staff, name="TestAcctACL") self.assertEqual(staff_accounts.count(), 1) self.assertEqual(staff_accounts[0], account) # Superuser should see all accounts num_acc = Account.objects.count() n_account = Account.objects.find_by_user(su) self.assertEqual(n_account.count(), num_acc) # Superuser should be able to get an account they may not be assigned to n_account = Account.objects.get_by_user(su, str(self.account.id)) self.assertTrue(n_account is not None) self.assertTrue(str(n_account.id) not in su.accounts) # Delete account via superuser Account.objects.remove_by_user(su, name="TestAcctACL") with self.assertRaises(Account.DoesNotExist): Account.objects.get(name="TestAcctACL") with self.assertRaises(AppException): Account.objects.remove_by_user(staff, name="TestNoAccess") def test_account_status(self): '''Test the various account status states''' # A normal account should be active account = Account.objects.create_by_user(self.user, name="TestAcctStatus") self.assertTrue(account.is_active) # Expire the account yesterday = dt.datetime.now() - dt.timedelta(days=1) account.end_date = yesterday account.save() self.assertFalse(account.is_active)
def test_common_cases(self): acct1 = Account(name='NewAccount1') acct2 = Account(name='NewAccount2') acct1.save() acct2.save() user1 = self._create_db_user(email="*****@*****.**", roles=[AGENT]) user2 = self._create_db_user(email="*****@*****.**", roles=[AGENT]) #Add both users to account with 'read' permission (default) acct1.add_user('*****@*****.**') acct1.add_user('*****@*****.**') current_users = [u.email for u in acct1.get_current_users()] self.assertEqual(set(current_users), set(['*****@*****.**', '*****@*****.**'])) user1.reload() user2.reload() #Users should have the acct1 as their current account for u in [user1, user2]: #accounts() lookup self.assertTrue(acct1.id in u.accounts) self.assertFalse(acct2.id in u.accounts) u.reload() #Current account was set to the first account users were added to self.assertTrue(u.current_account == u.account == acct1) #Total number of available accounts is 1 self.assertEqual(u.available_accounts.count(), 1) #Add users to another account for u in [user1, user2]: acct2.add_user(u, 'rw') #Current account should remain the previous set... u.reload() self.assertTrue(u.current_account == u.account == acct1) #...unless we change it u.current_account = acct2 u.reload() self.assertTrue(u.current_account == acct2) self.assertEqual(u.available_accounts.count(), 2) #Now acct1 should have 0 current users and 2 users with read access #acct2 2 current users 2 have write access self.assertEqual(len(acct1.get_all_users()), 2) self.assertTrue( acct1.get_current_users().count() == acct1.get_users().count() == 0 ) self.assertEqual(len(acct2.get_all_users()), 2) self.assertTrue( acct2.get_current_users().count() == acct2.get_users().count() == 2 ) #Remove user from their current account - superuser can do this acct2.del_user( user1) #Note: del_user deletes both 'rw' perms by default self.assertEqual(len(acct2.get_all_users()), 1) self.assertEqual(len(acct2.get_current_users()), 1) user1.reload() self.assertFalse(bool(user1.account)) # account is None #Now the acct2 should be not settable for user1 user1.current_account = acct2 user1.reload() self.assertFalse(bool(user1.account)) # still None user1.current_account = acct1 user1.reload() self.assertEqual(user1.account, acct1)