Should I test my generic DetailView in Django - django

I am very new to TDD and am trying to create my first Djagno application with tests. I am a bit confused when it comes to generic views. I have read several places (including the official docs) that each view should have tests associated with it. But I have also read that you should avoid testing Django internals because it is unnecessary.
So if I have a view like this:
class ClinicView(DetailView):
model = Clinic
template_name = "directory/clinic.html"
which uses a generic view and works fine, should I write a test for it?
My gut feeling is that I shouldn't have to because I use a generic view but haven't really found much to tell me if my feeling is correct. What are the best practices when it comes to this? Or what would be expected of me if I was to be giving my code over to be maintained by someone else? Should I at least write a test to make sure that my model and the template exist? Thanks in advance.

You want to avoid over-testing. You should only write tests for custom logic or for things that change frequently.
For example, if the Clinic model had a complex method which calculated some result, you would want tests to ensure this does what you think it does.
If you had something that you changed often and others may come in and change, you want tests to ensure that it is still functional after your change. The Django views are already tested. Unless you add a bunch of custom logic to the View (which you should probably be putting in a ModelManager anyway) there's no point to test it repeatedly with automated tests.
Testing is great and I love it! But I hate maintaining it, so I don't aim for full coverage. Once you cover your custom code with tests, you get diminishing returns by testing every little piece.
I once worked for a company that went a little crazy and wanted me to write tests for the automated tests. Don't be like them (:

Related

Create a simple unit tests framework from scratch in Coldfusion

I know there are existing tools for testing a ColdFusion application (MXUnit, MockBox), but I'm creating a custom tool, so that it will require less configuration.
When I run a unit test file, it's done via a generic 'model' which retrieves all functions from the unit test file. Within each test function, I have to call assertEquals -- but these functions are in the model, so I cannot access them.
I tried by passing the model itself to the unit test file so it can call the models functions directly but it doesn't work and it adds logic to the test file, which I don't like.
I can also extend the model in the test file but I will have to call directly the test file, call super.init(this) so the model can fetch test functions, etc..
Is there a way to achieve this kind of process? What's the best option?
In answer to your question, it sounds like you want to inject variables / methods into the subject under test. You can do it like so:
myInstance["methodName"] = myFunction;
You can then call the injected method like so:
myInstance.myFunction();
Both MXUnit and TestBox use this technique.
Having said that I don't quite understand why you want to re-invent the wheel. TestBox is an excellent, proven testing framework which has a wealth of features which would take you an incredible amount of time to replicate. I'm not quite sure what the configuration issue you have could be - it really doesn't require very much setup. Maybe it might be worth asking how to setup and use TestBox rather than how to build your own testing solution :)
There is a good book (which is available in a free version) which you can read on TestBox here : http://testbox.ortusbooks.com/
Good luck!

What aspects can we cover Unit Testing ASP.NET MVC Views

I recently came across this nice article from David Ebbo about Unit Testing ASP.NET MVC razor views with the help of new Razor Generator tool. But I've been asking myself the question, what this can be best utilized for. Of course we can pass in a model and check if all the properties have been populated in to proper html as planned.
I'm new to this unit testing view business so need to get my head around what things to be Unit tested in razor views. Suggestions??
I've been wondering the same thing. I can think of a few basic things to check, such as:
HTML is valid/well-formed
Page title (<title>/<h1>) matches the title from the model
Model body appears in the page
Correct CSS/Javascript is included
Important links appear correctly (paging/purchase/more info)
Performance (If you have lazy-loaded models, there could be performance issues you could only spot as the code in the views enumerate/access data)
In a small app, this probably doesn't add a lot of value. However in a big app, testing the views could come in handy to ensure changes things aren't becoming broken as other changes are made (despite best efforts to keep things isolated, it's not entirely unusual to break something that you believe you never made changes to!).
I think you could come up with a few important tests to ensure major things in your app work, but you could only really catch things that would be really obvious with a very quick manual test (or even caught during dev). Some may consider this worthwhile, I guess it depends on the app/team.
Previous experience has taught me that maintaining tests against an ever-changing UI sucks (and if it's not often changing, the tests won't add much value). At my last company we spent so much time trying to fix up tests that became broken with updates to the app, we couldn't add new tests (though this was in part, due to the (crap, but expensive) software we used - Mercury QuickTest). Tests written in C# would probably be more maintainable, but you still need to really weigh up the maintaince work vs the benefit you'll get from the tests.

CakePHP SimpleTest - Controller Test vs. Web Test

I wish to test basic CRUD operations in CakePHP (1.3) using SimpleTest.
For example, I wish to add a new record, and make sure that I get an error message if validation fails and a new record if save goes well.
Is it better to write these tests as (1) Controller tests for the relevant action (e.g. add()), or as (2) Web Tests, using $this->post() or $this->setField()?
This is an old question but still no answer so I'll give it a shot...
I believe that the first thing you need to do is separate your concerns better. Right now what you're doing, at least to me, is a code smell...meaning something ain't right!
How did I come to this conclusion?
Well, the question you asked and how you're answering it. The question that you're asking is:
"How should I test a model's functionality?"
Your answer:
"Test it from the controller or the view"
So, the first thing I would do is setup a method in the appropriate model to do what you're wanting. Write out the code that you think you need. Save a record and return the appropriate values that you're looking for based off whatever conditional statements you come up with.
After that I'd setup some fixtures so you have some data to test against. You can learn more about CakePHP fixtures and how to create them at the CakePHP manual, http://book.cakephp.org/view/1201/Preparing-test-data (In future projects I'd make the fixtures first, but that's just a personal preference)
Once your fixtures are setup you can actually go ahead and test your new model method. Testing models, in my opinion, is the easiest to test in CakePHP. I won't go into the details here, only because the CakePHP manual, http://book.cakephp.org/view/1207/Testing-models, has a bunch of info about how to test models.
At this point you should have a properly unit tested model action and concerns properly being separated.
That being said if you're feeling super spunky and want your code tested from all angles then by all means, setup a controller test to ensure the action is performing correctly. Setup a web test to ensure the whole package is working together.
First though, separate your concerns.

Django test fixtures: How to cope with test data involving time?

Currently I am doing TDD on a reusable Django app. One test should make sure that my view only returns articles that have a publish-date that is in the past. I am quite new to testing in Django. So far I have learned how to use .json files as fixtures for my test classes.
However for this test I do not want to insert publish dates that are 1000 years in the future. After all another species might discover our ancient internet, check out my source and wonder why my test fails :) What other approaches are there to solve this problem? Static .json files seem to be a bit hard to maintain as well as the application grows... mocking the datetime.datetime.now() method in my tests feels tedious as well.
There must be an easy way to produce the .json fixture on the fly before the test runs and always have 2 days from now as the publish-date for some of my entries...
You could try subclassing the datetime functions (see "Using Mock objects in Django for testing the current date").
Mocking datetime was my first thought as well but as LaundroMat pointet out in his blog post himself, this is rather hacky and bad.
I came up with another solution:
I just gave up on .json fixtures. I don't even know why Django encourages to use them. They look ugly and they are impossible to maintain.
Instead I added a module test_data.py to my fixtures folder. That module imports my models and defines some nice methods that create test-data for me. In my tests.py I dropped the fixtures = ['some_json_file'] line and added a setUp() method instead. This method executes my 'dynamic fixtures' from my test_data.py module.
This is so simple and obvious that I wonder if there is anything wrong with this approach. If no one comments on this solution, I will mark is as accepted in a couple of weeks or so...
You can try using django dynamic fixture, it will fill date/time properties automatically for you.
Creating test data
Indeed it is far more flexible to create your test data with Python.
There are several packages that support such things, for instance
model-backery
django-dynamic-fixture
These two use fairly different approaches. Have a look and pick the one you like more.
You can also write data generation functions from scratch. If you partition your logic carefully, this is not overly cumbersome.
Handling time
For tests involving time, the right approach is indeed mocking -- but don't do it yourself, use a nice library. See for instance
freezegun
There is even a pytest plugin for it.

Should I unit-test my grid rendering logic?

I have a simple project, mostly consisting of back-end service code. I have this fully unit-tested, including my DAL layer...
Now I have to write the front-end. I re-use what business objects I can in my front-end, and at one point I have a grid that renders some output. I have my DAL object with some function called DisplayRecords(id) which displays the records for a given ID...
All of this DAL objects are unit tested. But is it worth it to write a unit test for the DisplayRecords() function? This function is calling a stored proc, which is doing some joins. This means that my unit-test would have to set-up multiple tables, one with 15 columns, and its return value is a DataSet (this is the only function in my DAL that returns a datset - because it wasnt worth it to create an object just for this one grid)...
Is stuff like this even worth testing? What about front-end logic in general - do people tend to skip unit tests for the ASP.NET front-end, similar to how people 'skip' the logic for private functions? I know the latter is a bit different - testing behavior vs implementation and all... but, am just curious what the general rule-of-thumb is?
Thanks very much
There are a few things that weigh into whether you should write tests:
It's all about confidence. You build tests so that you have confidence to make changes. Can you confidently make changes without tests?
How important is this code to the consumers of the application? If this is critical and central to everything, test it.
How embarrassing is it if you have regressions? On my last project, my goal was no regressions-- I didn't want the client to have to report the same bug twice. So every important bug got a test to reproduce it before it was fixed.
How hard is it to write the test? There are many tools that can help ease the pain:
Selenium is well understood and straightforward to set up. Can be a little expensive to maintain a large test suite in selenium. You'll need the fixture data for this to work.
Use a mock to stub out your DAL call, assuming its tested elsewhere. That way you can save time creating all the fixture data. This is a common pattern in testing Java/Spring controllers.
Break the code down in other ways simply so that it can be tested. For example, extract out the code that formats a specific grid cell, and write unit tests around that, independent of the view code or real data.
I tend to make quick Selenium tests and just sit and watch the app do its thing - that's a fast validation method which avoids all the manual clicking.
Fully automated UI testing is tedious and should IMO only be done in more mature apps where the UI won't change much. Regarding the 'in-between' code, I would test it if it is reused and/or complicated/ introducing new logic, but if its just more or less a new sequence of DAL method calls and specific to a single view I would skip it.