2

I have a Django project which is entering its fourth year of development. Over those four years, a number of URLs (and therefore view functions) have become obsolete. Instead of deleting them as I go, I've left them in a "just in case" attitude. Now I'm looking to clean out the unused URLs and unused view functions.

Is there any easy way to do this, or is it just a matter of grunting through all the code to figure it out? I'm nervous about deleting something and not realizing it's important until a few weeks/months later.

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
Garfonzo
  • 3,876
  • 6
  • 43
  • 78

2 Answers2

1

The idea is to iterate over urlpatterns and check that the status_code is 200:

class BasicTestCase(TestCase):
    def test_url_availability(self):
        for url in urls.urlpatterns:
            self.assertEqual(self.client.get(reverse('%s' % url.name)).status_code,
                             200)

I understand that it might not work in all cases, since there could be urls with "dynamic" nature with dynamic url parts, but, it should give you the basic idea. Note that reverse() also accepts arguments in case you need to pass arguments to the underlying view.

Also see: Finding unused Django code to remove.

Hope that helps.

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • From what I understand, the question is more to do with any URL patterns exist that are unused, rather than all all url patterns reachable .. Correct me if i m wrong. – karthikr Mar 22 '14 at 22:27
  • @karthikr mhm, sounds like you are right. Will see if it helps the OP anyway. – alecxe Mar 22 '14 at 22:30
  • @karthikr Correct. I know I have a some that exist and are likely reachable, but haven't been used in a while. Perhaps this answer would be a good start though. – Garfonzo Mar 22 '14 at 22:31
  • @Garfonzo correct me if I'm wrong. Basically, you want to somehow automatically analyze your templates to see what urls/views are not used. If so, end-to-end tests would help here a lot - if you'd have a good coverage, you could analyze coverage report and see what code blocks are not used.. – alecxe Mar 22 '14 at 22:40
  • @alecxe That's about right. I looked through the link you posted, and followed some trails down there. I think there's some good stuff that I'll be able to implement to achieve what I'm after. Thanks! – Garfonzo Mar 22 '14 at 23:41
0

You are looking for coverage, which is basically "how much of the code written is actually being used".

Coverage analysis is usually done with tests - to find how what percentage of your code is covered by tests - but there is nothing stopping you to do the same to find out what views are orphaned.

Rather than repeat the process, @sk1p already answered it at How to get coverage data from a django app when running in gunicorn.

Community
  • 1
  • 1
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284