testing securityConfig mapping in grails + acegi - unit-testing

I'm writing test cases for a project which still uses the Acegi plugin (not the newer Spring Core Security plugin) and as of now, I've managed to do what this site (http://www.zorched.net/2008/09/01/grails-testing-acegi-security/)
has suggested regarding the detection of which user is currently logged in. However, in my controller, I have stuff that looks like this:
def list = {
// code for an "admin account"
}
def list_others = {
// code for other accounts
}
Now, I do not check in the controller the logged in user. Instead, I have these defined in the SecurityConfig.groovy like:
security {
...
requestMapString = """\
/someController/list=ROLE_ADMIN
/someController/list_others=ROLE_OTHERS
"""
...
}
Hence, if I had a test that looked like this:
void testTrial() {
// define here that otherUser has a role of ROLE_OTHERS
authenticate(otherUser, "other") // this calls the authenticate methode in the site I gave earlier
controller.list()
// I do an assertion here to check where this goes to
}
Thing is, when I do the assertion, of course list will tell me that it forwarded to list.gsp... even if the "logged in" user has a role of ROLE_OTHERS and not an admin.
However, what I need is how to test what a logged-in user is only supposed to access? In this case, given that the call is to *.list() and the logged in user has a ROLE_OTHERS role, I should have been forwarded to a "denied" page.
Help? Thanks!

You'll need functional tests for this. Unit tests are just Groovy or Java classes plus some mocking. There's no Spring application context, no Hibernate, no database, and most importantly for this case no plugins.
Integration tests give you more functionality, but even there requests are mostly simulated and since there's no container, no filters fire. Spring Security (which the Acegi plugin uses) is based on a chain of servlet filters. So if you want to test that your security rules are being applied correctly you'll need a running server, hence functional tests.
There are several options for functional testing, the most popular ones being WebTest: http://grails.org/plugin/webtest, the Functional Testing plugin: http://grails.org/plugin/functional-test, and the Selenium RC plugin: http://grails.org/plugin/selenium-rc.
The newest one is Geb: http://grails.org/plugin/geb. The manual is at http://geb.codehaus.org/ and there was a recent blog post written about it here: http://blog.springsource.com/2010/08/28/the-future-of-functional-web-testing/

Related

What should I be testing for in my Django API tests?

I have started to write an API using the Django REST Framework. I am struggling to think about what tests I should be writing.
My ideas so far are...
Authentication: making sure users are logged in
Authorisation: checking users have the correct permissions
Response body: making sure all the desired fields are present
Allowed HTTP methods: making sure that users can't perform unintended actions.
Since the Django REST framework uses Django's underlying permissions system, is it really necessary to test permissions at both the model level and the API level? In this regard, it seems like some of my tests are testing for the same thing.
One of the more important things to test in an API is that it handles requests correctly. Good requests and Bad ones.

How to unit test authorization globally in CakePHP

We're using CakePHP v3.1.x with the CakeDC Users plugin.
We're trying to set up our unit tests to help prevent accidentally allowing non-admins to do things they should not be allowed to do. For example, imagine that a developer creates a new admin feature with a new action in a controller. During development she sets the permissions very lax so she doesn't have to log in each time to test it (or something... you get the idea). I'm trying to write a test that will fail if she tries to push this...
Here's my idea for how to do it:
Create a test that loops over all controllers / actions in the app, and checks to see if a non-admin user is authorized.
The test has a list of every action that a non-admin user can do.
The test fails if a non-admin is allowed to do anything that's not on the list.
The idea is that every time we intentionally let non-admin users do something, the test fails, and reminds us to go update the list of exceptions. But if we accidentally allow an action without knowing it, the test fails and we fix the mistake. It's a safety catch.
My question: Is this the right way to do this? And if so, how can we dynamically generate a list of all of the apps controllers/actions?
Is this the right way to do this?
Fix the problem not the symptoms: Fix your developers behavior of committing "test" and "debug" code or whatever you want to name it. Do peer reviews or have your team leader review the commits. You could try to ask on https://workplace.stackexchange.com/ about how to deal with this situation the best. Check this question for an example.
And if so, how can we dynamically generate a list of all of the apps controllers/actions?
Use this to get a list of folders with controllers:
App::path('Controller'); // App
App::path('Controller', 'MyPlugin'); // Some plugin
Use Plugin::loaded() to get a list of all plugins.
Then use the information to read the controller classes from all the folders. You can then generate test cases (maybe trough a new task of the bake shell?) automatically because you've got a list of controllers from your app and plugin. Use reflections to get a list of public methods from the controllers and filter known public methods like initialize().
Setting up testing auth is described here.
If you write a custom test that uses an array structure describing the controllers and actions and their permissions I'm pretty sure that you'll be able to automate it by running over that array structure and using the information to run the auth tests. But honestly, I'm not going to do that work here.
Or instead of testing the code directly use Codeception acceptance testing. CakePHP has plugin for that. This will allow you to test the "real" site by having automated click-through testing. It should be pretty easy to set up a specific users session and then test against URLs for access by expecting a redirect to the login action or whatever you do.

Create a sitecore admin website

A sitecore newbie here. We have an existing website that's built using Sitecore 8. It's live in our production environment. I recently joined the company and my background is backend .NET development. I have been asked to write a utility module that allows us to remove registered users that meet certain criteria. The website provides the ability for users to register and the registered users are stored in the core database. My initial thought was to go directly against the DB but quickly learned that the data stored is serialized. I also thought about writing a c# console application to do this but it appears that there are a lot of configuration/setup steps to do this and that it's better to do it from a web app. Does anyone have any tips on how I could set up a simple utility web application to connect to an existing Sitecore database? I expect that I will be asked to add more functions/features down the road.
For an admin function like that, I would be tempted to use Sitecore Powershell Extensions: https://marketplace.sitecore.net/en/Modules/Sitecore_PowerShell_console.aspx
The Get-User command can pull users out of the system:
Get-User Documentation
PS master:\> Get-User -Filter "michaellwest#*.com"
Name Domain IsAdministrator IsAuthenticated
---- ------ --------------- ---------------
sitecore\michael sitecore False False
Then you can use Remove-User to delete them: Remove-User Documentation
There are a lot of great resources on how to use SPE, its awesome for stuff like this.
As i understood, the objective is to be able to remove certain users.
The easiest way to do that would be using Sitecore PowerShell module, but for you as a newbie that would not be probably as easy (and you would need to have module installed). With PowerShell module you don't even need to create user interface.
Here is the documentation how to do use Remove-User with PowerShell
If PowerShell option does not work for you, you can use that from the code utilising Sitecore API, so your Delete method would look something like below:
public void DeleteUser(string userName)
{
try
{
Sitecore.Security.Accounts.User user = Sitecore.Security.Accounts.User.FromName(userName, true);
user.Delete();
}
catch (Exception ex)
{
Sitecore.Diagnostics.Log.Error(string.Format("Error in Client.Project.Security.UserMaintenance (DeleteUser): Message: {0}; Source:{1}", ex.Message, ex.Source), this);
}
}
So you would just call this method when iterating usernames to be deleted. Depending on which credentials you would run that code, you may need to wrap it with SecurityDisabler to omit permissions check for delete operation:
using (new SecurityDisabler())
{
// you code to delete here within using block
}
Hope this helps!

generate common tests for django

I'm developing sites on django I'm think what most problems may be found by using smoke coverage tests method. But (in most cases) write the tests to check response code is 200 for every app, every view, and every url is so bored (e.g. when you are develop few sites parallel). I have a question: How can I automate this process, may be exist some complete solutions to generate some common tests for django.
Thanks!
Best practices:
If it can break, it should be tested. This includes models, views,
forms, templates, validators, and so forth.
Each test should generally only test one function.
Keep it simple. You do not want to have to write tests on top of
other tests. Run tests whenever code is PULLed or PUSHed from the
repo and in the staging environment before PUSHing to production.
When upgrading to a newer version of Django:
-upgrade locally,
-run your test suite,
-fix bugs,
-PUSH to the repo and staging, and then
-test again in staging before shipping the code.
https://realpython.com/blog/python/testing-in-django-part-1-best-practices-and-examples/
Django provides a small set of tools that come in handy when writing tests.
The test client
The test client is a Python class that acts as a dummy Web browser, allowing you to test your views and interact with your Django-powered application programmatically.
Some of the things you can do with the test client are:
Simulate GET and POST requests on a URL and observe the response –
everything from low-level HTTP (result headers and status codes) to
page content.
See the chain of redirects (if any) and check the URL and status code
at each step.
Test that a given request is rendered by a given Django template,
with a template context that contains certain values.
Overview and a quick example
To use the test client, instantiate django.test.Client and retrieve Web pages:
from django.test import Client
c = Client()
response = c.post('/login/', {'username': 'john', 'password': 'smith'})
response.status_code
200
response = c.get('/customer/details/')
response.content
'<!DOCTYPE html...'
As this example suggests, you can instantiate Client from within a session of the Python interactive interpreter.
Testing responses
The get() and post() methods both return a Response object. This Response object is not the same as the HttpResponse object returned by Django views; the test response object has some additional data useful for test code to verify.
Making requests
Use the django.test.Client class to make requests.
class Client(enforce_csrf_checks=False, **defaults)
Exceptions
If you point the test client at a view that raises an exception, that exception will be visible in the test case. You can then use a standard try ... except block or assertRaises() to test for exceptions.
Provided test case classes
Normal Python unit test classes extend a base class of unittest.TestCase. Django provides a few extensions of this base class:
Hierarchy of Django unit testing classes (TestCase subclasses)
Hierarchy of Django unit testing classes
For detailed information and more examples visit https://docs.djangoproject.com/en/1.7/topics/testing/tools/

How can I mock a container-provided object (e.g HttpSession) when Unit testing a GWT app?

I am currently trying to unit test my Service layer (all *Impl.java classes) in a GWT app. Well the problem is that in the code, I have a dependency which targets an object provided by the Httpsession. Actually, I'm storing a User object (the currently logged in user) in the httpSession.
In order to get it back from the HttpSession (in the *Impl.java class), I am using this :
User user = ServiceUtil.getUser(getThreadLocalRequest().getSession());
How can I mock this object from my Unit test code ?
thanks a lot,
In the JUnit test case you can write
HttpSession session = new MockHttpSession();
Where MockHttpSession is this
You can put your user object in this session and then execute your test case.
I recommend you change the structure of your application so that the service layer doesn't depend on such things as a session (context agnostic) but instead the methods which need a user object of some kind get it injected (via parameter or however). So actually you include a very thin presentation layer (or however you may call it) which handles things such as responding to HTTP requests, logging a user in and putting the user object in the session and just calls service layer methods.
That way you can mock your user object in the unit test, pass it to your service layer and don't need any mock framework.