[damned-lies] Replace FakeStatistics by two specific fake classes



commit b29bee87bad6aa7a936473e2ae44395726a82e5f
Author: Claude Paroz <claude 2xlibre net>
Date:   Thu Aug 4 11:42:01 2011 +0200

    Replace FakeStatistics by two specific fake classes

 stats/models.py                    |  102 ++++++++++++-----------------------
 stats/templatetags/stats_extras.py |    4 +-
 stats/tests/__init__.py            |   14 +++++-
 stats/views.py                     |   12 +++--
 templates/module_images.html       |    6 +-
 5 files changed, 61 insertions(+), 77 deletions(-)
---
diff --git a/stats/models.py b/stats/models.py
index d7aa26c..7a43c01 100644
--- a/stats/models.py
+++ b/stats/models.py
@@ -342,9 +342,7 @@ class Branch(models.Model):
         for lang in mandatory_langs:
             for domain in stats.keys():
                 if lang not in stats_langs[domain] and stats[domain][0].full_po:
-                    fake_stat = FakeStatistics(self.module, self, typ, lang)
-                    fake_stat._untranslated = stats[domain][0].untranslated()
-                    stats[domain].append(fake_stat)
+                    stats[domain].append(FakeLangStatistics(stats[domain][0], lang))
         # Sort
         for key, doms in stats.items():
             doms.sort(self.compare_stats)
@@ -1340,12 +1338,12 @@ class Statistics(models.Model):
                                        self.domain.directory, '%s', '%s') + self.branch.img_url_suffix
             for fig in self.figures:
                 fig['orig_remote_url'] = url_model % ('C', fig['path'])
-                fig['trans_remote_url'] = url_model % (self.language.locale, fig['path'])
                 fig['translated_file'] = False
-                if self.language:
-                    # Check if a translated figure really exists or if the English one is used
-                    if os.path.exists(os.path.join(self.branch.co_path(), self.domain.directory, self.language.locale, fig['path'])):
-                        fig['translated_file'] = True
+                # Check if a translated figure really exists or if the English one is used
+                if (self.language and
+                   os.path.exists(os.path.join(self.branch.co_path(), self.domain.directory, self.language.locale, fig['path']))):
+                    fig['trans_remote_url'] = url_model % (self.language.locale, fig['path'])
+                    fig['translated_file'] = True
         return self.figures
 
     def fig_stats(self):
@@ -1486,7 +1484,7 @@ class Statistics(models.Model):
                             <modname>: {
                                 <branchname>:
                                     [(<domname>, <stat>), ...], # List of tuples (domain name, Statistics object)
-                                           # First element is a placeholder for a FakeStatistics object
+                                           # First element is a placeholder for a FakeSummaryStatistics object
                                            # only used for summary if module has more than 1 domain
                                 }
                             }
@@ -1578,7 +1576,7 @@ class Statistics(models.Model):
                 # Here we add the 2nd or more stat to the same module-branch
                 if len(stats['categs'][categdescr]['modules'][modname][branchname]) == 2:
                     # Create a fake statistics object for module summary
-                    stats['categs'][categdescr]['modules'][modname][branchname][0][1] = FakeStatistics(stat.domain.module, stat.branch, dtype)
+                    stats['categs'][categdescr]['modules'][modname][branchname][0][1] = FakeSummaryStatistics(stat.domain.module, stat.branch, dtype)
                     stats['categs'][categdescr]['modules'][modname][branchname][0][1].trans(stats['categs'][categdescr]['modules'][modname][branchname][1][1])
                 stats['categs'][categdescr]['modules'][modname][branchname].append((domname, stat))
                 stats['categs'][categdescr]['modules'][modname][branchname][0][1].trans(stat)
@@ -1606,19 +1604,36 @@ class Statistics(models.Model):
         stats['all_errors'].sort()
         return stats
 
-class FakeStatistics(object):
-    """ This is a fake statistics class where a summary value is needed for a multi-domain module
-        This is used in get_lang_stats for the language-release-stats template """
-    def __init__(self, module, branch, dtype, lang=None):
+
+class FakeLangStatistics(object):
+    """ Statistics class for a non existing lang stats """
+    is_fake = True
+    def __init__(self, pot_stat, lang):
+        self.stat = pot_stat
+        self.language = lang
+
+    def __getattr__(self, attr):
+        # Wrap all unexisting attribute access to self.stat
+        return getattr(self.stat, attr)
+
+    def get_lang(self):
+        return _("%(lang_name)s (%(lang_locale)s)") % {
+            'lang_name': _(self.language.name),
+            'lang_locale': self.language.locale
+        }
+
+
+class FakeSummaryStatistics(object):
+    """ Statistics class that sums up an entire module stats """
+    is_fake = True
+    def __init__(self, module, branch, dtype):
         self.module = module
         self.branch = branch
         self.domain = module.domain_set.filter(dtype=dtype)[0]
-        self.language = lang
         self._translated = 0
         self._fuzzy      = 0
         self._untranslated = 0
         self.partial_po = False
-        self.figures = None
 
     def translated(self, scope=None):
         return self._translated
@@ -1635,74 +1650,27 @@ class FakeStatistics(object):
         self._untranslated += stat.untranslated()
         stat.partial_po = True
 
-    def is_fake(self):
-        return True
-
-    def get_lang(self):
-        if self.language:
-            return _("%(lang_name)s (%(lang_locale)s)") % {
-                'lang_name': _(self.language.name),
-                'lang_locale': self.language.locale
-            }
-        else:
-            return "pot file"
-
-    def fig_stats(self):
-        stats = {'fuzzy':0, 'translated':0, 'untranslated':0, 'total':0, 'prc':0}
-        for fig in self.get_figures():
-            stats['total'] += 1
-            stats['untranslated'] += 1
-        return stats
-
-    def get_figures(self):
-        """ self.figures is a list of dicts:
-            [{'path':, 'hash':, 'fuzzy':, 'translated':, 'translated_file':}, ...] """
-        if self.figures is None and self.domain.dtype == 'doc':
-            self.figures = utils.get_fig_stats(self.po_path())
-            # something like: "http://git.gnome.org/browse/vinagre / plain / help / %s / %s ?h=master"
-            url_model = utils.url_join(self.branch.get_vcs_web_url(), self.branch.img_url_prefix,
-                                       self.domain.directory, '%s', '%s') + self.branch.img_url_suffix
-            for fig in self.figures:
-                fig['orig_remote_url'] = url_model % ('C', fig['path'])
-                fig['trans_remote_url'] = url_model % (self.language.locale, fig['path'])
-                fig['translated_file'] = False
-                if self.language:
-                    # Check if a translated figure really exists or if the English one is used
-                    if os.path.exists(os.path.join(self.branch.co_path(), self.domain.directory, self.language.locale, fig['path'])):
-                        fig['translated_file'] = True
-        return self.figures
-
-    def po_path(self):
-        """ Return path of pot file on local filesystem """
-        subdir = ""
-        if self.domain.dtype == "doc":
-            subdir = "docs"
-        filename = "%s.%s.pot" % (self.domain.potbase(), self.branch.name)
-        return os.path.join(settings.POTDIR, self.module_name()+'.'+self.branch.name, subdir, filename)
-
     def pot_size(self):
         return int(self._translated) + int(self._fuzzy) + int(self._untranslated)
+
     def tr_percentage(self, scope='full'):
         if self.pot_size() == 0:
             return 0
         else:
             return int(100*self._translated/self.pot_size())
+
     def fu_percentage(self, scope='full'):
         if self.pot_size() == 0:
             return 0
         else:
             return int(100*self._fuzzy/self.pot_size())
+
     def un_percentage(self, scope='full'):
         if self.pot_size() == 0:
             return 0
         else:
             return int(100*self._untranslated/self.pot_size())
-    def module_name(self):
-        return self.module.name
-    def module_description(self):
-        return self.module.description
-    def most_important_message(self):
-        return None
+
 
 class StatisticsArchived(models.Model):
     module = models.TextField()
diff --git a/stats/templatetags/stats_extras.py b/stats/templatetags/stats_extras.py
index e147453..0c6dac9 100644
--- a/stats/templatetags/stats_extras.py
+++ b/stats/templatetags/stats_extras.py
@@ -2,7 +2,7 @@ from django import template
 from django.utils.safestring import mark_safe
 from django.utils.translation import get_language_bidi
 
-from stats.models import PoFile, Statistics, FakeStatistics
+from stats.models import PoFile, Statistics, FakeLangStatistics, FakeSummaryStatistics
 
 register = template.Library()
 
@@ -38,7 +38,7 @@ def browse_bugs(module, content):
 @register.filter
 def num_stats(stat, scope='full'):
     """ Produce stat numbers as in: 85% (1265/162/85) """
-    if isinstance(stat, (Statistics, FakeStatistics)):
+    if isinstance(stat, (Statistics, FakeLangStatistics, FakeSummaryStatistics)):
         stats = {
             'prc':          stat.tr_percentage(scope),
             'translated':   stat.translated(scope),
diff --git a/stats/tests/__init__.py b/stats/tests/__init__.py
index 7df0fd0..92f6246 100644
--- a/stats/tests/__init__.py
+++ b/stats/tests/__init__.py
@@ -24,9 +24,10 @@ from django.test import TestCase
 from django.test.client import Client
 from django.core import mail
 from django.core.exceptions import ValidationError
+from django.core.urlresolvers import reverse
 from django.conf import settings
 
-from stats.models import Module, Domain, Branch, Category, Release, Statistics, Information
+from stats.models import Module, Domain, Branch, Category, Release, Language, Statistics, Information
 from stats.utils import check_program_presence, run_shell_command
 from languages.models import Language
 
@@ -190,6 +191,17 @@ class ModuleTestCase(TestCase):
         self.assertEquals(figs[0]['orig_remote_url'], 'http://git.gnome.org/browse/gnome-hello/plain/help/C/figures/gnome-hello-new.png?h=master')
         self.assertEquals(figs[0]['trans_remote_url'], 'http://git.gnome.org/browse/gnome-hello/plain/help/fr/figures/gnome-hello-new.png?h=master')
 
+    def testFigureView(self):
+        self.b.update_stats(force=True)
+        url = reverse('stats.views.docimages', args=[self.mod.name, 'help', self.b.name, 'fr'])
+        response = self.client.get(url)
+        self.assertContains(response, "gnome-hello-new.png")
+        # Same for a non-existing language
+        Language.objects.create(name='Afrikaans', locale='af')
+        url = reverse('stats.views.docimages', args=[self.mod.name, 'help', self.b.name, 'af'])
+        response = self.client.get(url)
+        self.assertContains(response, "gnome-hello-new.png")
+
     def testCreateUnexistingBranch(self):
         """ Try to create a non-existing branch """
         Branch.checkout_on_creation = True
diff --git a/stats/views.py b/stats/views.py
index b12d9d2..965cb5d 100644
--- a/stats/views.py
+++ b/stats/views.py
@@ -29,7 +29,7 @@ from django.shortcuts import render, get_object_or_404
 from django.utils.translation import ugettext as _
 
 from common.utils import MIME_TYPES
-from stats.models import Statistics, FakeStatistics, Module, Branch, Category, Release
+from stats.models import Statistics, FakeLangStatistics, Module, Branch, Category, Release
 from stats.forms import ModuleBranchForm
 from stats import utils
 from languages.models import Language
@@ -152,9 +152,13 @@ def docimages(request, module_name, potbase, branch_name, langcode):
                                       domain__name=potbase,
                                       language__locale=langcode)
     except Statistics.DoesNotExist:
-        lang   = get_object_or_404(Language, locale=langcode)
-        branch = get_object_or_404(Branch, module__pk=mod.id, name=branch_name)
-        stat   = FakeStatistics(mod, branch, 'doc', lang)
+        pot_stat = Statistics.objects.get(
+            branch__module=mod.id,
+            branch__name=branch_name,
+            domain__name=potbase,
+            language__isnull=True)
+        lang = get_object_or_404(Language, locale=langcode)
+        stat = FakeLangStatistics(pot_stat, lang)
     context = {
         'pageSection': "module",
         'module':   mod,
diff --git a/templates/module_images.html b/templates/module_images.html
index 7ed5fd7..275b9fb 100644
--- a/templates/module_images.html
+++ b/templates/module_images.html
@@ -16,7 +16,7 @@
 {% for fig in stat.get_figures %}
   <tr><td valign="top">
     <a href="{{ fig.orig_remote_url }}"><span class="path">C/{{ fig.path }}</span><br/></a>
-    {% if fig|video %}<video src="{{ fig.orig_remote_url }}" controls></video>
+    {% if fig|is_video %}<video src="{{ fig.orig_remote_url }}" controls></video>
     {% else %}<a href="{{ fig.orig_remote_url }}"><img class="screenshot" src="{{ fig.orig_remote_url }}"/></a>
     {% endif %}
     </td>
@@ -24,7 +24,7 @@
     {% if fig.translated %}
       {% if fig.translated_file %}
         <a href="{{ fig.trans_remote_url }}"><span class="path">{{ locale }}/{{ fig.path }}</span></a><br/>
-        {% if fig|video %}<video src="{{ fig.orig_remote_url }}" controls></video>
+        {% if fig|is_video %}<video src="{{ fig.orig_remote_url }}" controls></video>
         {% else %}<a href="{{ fig.trans_remote_url }}"><img class="screenshot" src="{{ fig.trans_remote_url }}"/></a>
         {% endif %}
       {% else %}
@@ -35,7 +35,7 @@
         <em>{% trans "Fuzzy" %}</em><br/>
         {% if fig.translated_file %}
           <a href="{{ fig.trans_remote_url }}"><span class="path">{{ locale }}/{{ fig.path }}</span></a><br/>
-          {% if fig|video %}<video src="{{ fig.orig_remote_url }}" controls></video>
+          {% if fig|is_video %}<video src="{{ fig.orig_remote_url }}" controls></video>
           {% else %}<a href="{{ fig.trans_remote_url }}"><img class="screenshot" src="{{ fig.trans_remote_url }}"/></a>
           {% endif %}
         {% else %}



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]