Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add new test for _parse_file #181

Merged
merged 1 commit into from
Sep 28, 2018
Merged

Add new test for _parse_file #181

merged 1 commit into from
Sep 28, 2018

Conversation

zurk
Copy link
Contributor

@zurk zurk commented Sep 28, 2018

"".join(n.value for n in nodes) where nodes, _ = self.extractor._parse_file(...) produce bad result.
here is the diff from added test:

- // from https://github.com/freeCodeCamp/freeCodeCamp/blob/master/server/component-passport.js// from https://github.com/freeCodeCamp/freeCodeCamp/blob/master/server/component-passport.js
+ // from https://github.com/freeCodeCamp/freeCodeCamp/blob/master/server/component-passport.js
  import passport from 'passport';
- import { PassportConfiguratorPassportConfigurator } from
?                              --------------------
+ import { PassportConfigurator } from
   '@freecodecamp/loopback-component-passport';
  import passportProviders from './passport-providers';
  import url from 'url';
  import jwt from 'jsonwebtoken';
  import dedent from 'dedent';
  
  const passportOptions={
    emailOptional: true,
    profileToUser: null
  };
  
  const fields = {
    progressTimestamps: false,
  };
  
  function getCompletedCertCount(user) {
    return [
      'isApisMicroservicesCert',
      'is2018DataVisCert',
      'isFrontEndLibsCert',
      'isInfosecQaCert',
      'isJsAlgoDataStructCert',
      'isRespWebDesignCert'
    ].reduce((sum, key) => user[key] ? sum + 1 : sum, 0);
  }
  
  function getLegacyCertCount(user) {
    return [
      'isFrontEndCert',
      'isBackEndCert',
      'isDataVisCert'
    ].reduce((sum,key) => user[key] ? sum + 1 : sum, 0);
  }
  
  PassportConfigurator.prototype.init = function passportInit(noSession) {
    this.app.middleware('session:after', passport.initialize());
  
    if (noSession) {
      return;
    }
  
    this.app.middleware('session:after',passport.session());
  
-   // Serialization and deserialization is only required if passport session is// Serialization and deserialization is only required if passport session is// Serialization and deserialization is only required if passport session is
-   // enabled// enabled// enabled
+   // Serialization and deserialization is only required if passport session is
+   // enabled
  
    passport.serializeUser((user, done) =>
    {
      done(null, user.id);
    });
  
    passport.deserializeUser((id, done) => {
  
-     this.userModel.findById(id, { fieldsfields }, (err, user) => {
?                                         ------
+     this.userModel.findById(id, { fields }, (err, user) => {
        if (err || !user) {
          return done(err, user);
        }
  
        return this.app.dataSources.db.connector
          .collection('user')
          .aggregate([
            { $match: { _id: user.id } },
            { $project: { points: { $size: '$progressTimestamps' } } }
-         ], function(err, [{ pointspoints = 1 } = {}]) {
?                                   ------
+         ], function(err, [{ points = 1 } = {}]) {
            if (err) { return done(err); }
            user.points = points;
            let completedChallengeCount = 0;
            let completedProjectCount = 0;
            if ('completedChallenges' in user) {
              completedChallengeCount = user.completedChallenges.length;
              user.completedChallenges.forEach(item => {
                if (
                  'challengeType' in item &&
                  (item.challengeType === 3 || item.challengeType === 4)
                ) {
                  completedProjectCount++;
                }
              });
            }
            user.completedChallengeCount = completedChallengeCount;
            user.completedProjectCount = completedProjectCount;
            user.completedCertCount = getCompletedCertCount(user);
            user.completedLegacyCertCount = getLegacyCertCount(user);
            user.completedChallenges = [];
            return done(null, user);
          });
      });
    });
  };
  
  export default function setupPassport(app) {
    const configurator = new PassportConfigurator(app);
  
    configurator.setupModels({
      userModel: app.models.user,
      userIdentityModel: app.models.userIdentity,
      userCredentialModel: app.models.userCredential
    });
  
    configurator.init();
  
    Object.keys(passportProviders).map(function(strategy) {
      let config = passportProviders[strategy];
      config.session = config.session !== false;
  
-     // https://stackoverflow.com/q/37430452// https://stackoverflow.com/q/37430452// https://stackoverflow.com/q/37430452
+     // https://stackoverflow.com/q/37430452
      let successRedirect = (req) => {
        if (!!req && req.session && req.session.returnTo) {
          delete req.session.returnTo;
          return'/';}
        return config.successRedirect || '';
      };
  
      config.customCallback = !config.useCustomCallback
        ? null
        : (req, res, next) => {
  
          passport.authenticate(
            strategy,
            { session: false },
            (err, user, userInfo) => {
  
              if (err) {
                return next(err);
              }
  
              if (!user || !userInfo) {
                return res.redirect(config.failureRedirect);
              }
              let redirect = url.parse(successRedirect(req), true);
  
              delete redirect.search;
  
-             const {accessTokenaccessToken} = userInfo;
?                               -----------
+             const {accessToken} = userInfo;
-             const { providerprovider } = config;
?                             --------
+             const { provider } = config;
              if (accessToken && accessToken.id) {
                if (provider === 'auth0') {
                  req.flash(
                    'success',
                    dedent`
                      Success! You have signed in to your account. Happy Coding!
                    `
                  );
                } else if (user.email) {
                  req.flash(
                    'info',
                    dedent`
    We are moving away from social authentication for privacy reasons. Next time
    we recommend using your email address: ${user.email} to sign in instead.
                    `
                  );
                }
                const cookieConfig = {
                  signed: !!req.signedCookies,
                  maxAge:accessToken.ttl,
                  domain: process.env.COOKIE_DOMAIN || 'localhost',
                };
-               const jwtAccess = jwt.sign({accessTokenaccessToken}, process.env.JWT_SECRET);
?                                                      -----------
+               const jwtAccess = jwt.sign({accessToken}, process.env.JWT_SECRET);
                res.cookie('jwt_access_token', jwtAccess, cookieConfig);
                res.cookie('access_token', accessToken.id, cookieConfig);
                res.cookie('userId', accessToken.userId, cookieConfig);
  
                req.login(user);
              }
  
              redirect = url.format(redirect);
              return res.redirect(redirect);
            }
          )(req, res, next);
      };
  
      configurator.configureProvider(
        strategy,
        {
          ... config,
          ...passportOptions
        }
      );
    });}

@zurk zurk changed the title Add new test for _parse_file [WIP] Add new test for _parse_file Sep 28, 2018
@zurk
Copy link
Contributor Author

zurk commented Sep 28, 2018

realted to bblfsh/javascript-driver#36

@zurk zurk force-pushed the master branch 2 times, most recently from ffeac8d to 849e642 Compare September 28, 2018 17:39
@zurk zurk changed the title [WIP] Add new test for _parse_file Add new test for _parse_file Sep 28, 2018
Copy link
Contributor

@m09 m09 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍! Does it also fix #180?

@@ -25,6 +25,15 @@ def setUpClass(cls):
cls.uast = bblfsh.Node.FromString(fin.read())
cls.extractor = FeatureExtractor("javascript", parents_depth=2, siblings_window=5)

def test_parse_file2(self):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please rename to something more informative like test_parse_file_on_comments if comments are causing a problem for example.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

mmm, it is not only for comments. It is for random stuff. I rename it to test_parse_file_exact_match

with lzma.open(str(test_js_code_filepath), mode="rt") as f:
code = f.read()
uast = bblfsh.BblfshClient("0.0.0.0:9432").parse(
filename="", language="javascript", contents=code.encode()).uast
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

no need to specify filename when contents is set. It could also be good to just bypass babelfish and just use a saved uast as we do in the other tests. Up to you :)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nope. here the header of parse function: def parse(self, filename, language=None, contents=None, timeout=None): also the file name goes to bblfsh logs.
When we update to the next version of a bblfsh driver, we have to update this files.
I prefer to have it like that.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fair enough, even though we will have to update all the other files in the folder anyway. And huh, this function signature needs refactoring, I'll open an issue.

@m09 m09 merged commit d6f241a into src-d:master Sep 28, 2018
@zurk
Copy link
Contributor Author

zurk commented Sep 28, 2018

No, I check it and it does not fix #180

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants